Advertisement
Guest User

Untitled

a guest
Aug 30th, 2018
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 67.80 KB | None | 0 0
  1. <?php
  2. /**
  3.  * CodeIgniter
  4.  *
  5.  * An open source application development framework for PHP
  6.  *
  7.  * This content is released under the MIT License (MIT)
  8.  *
  9.  * Copyright (c) 2014 - 2018, British Columbia Institute of Technology
  10.  *
  11.  * Permission is hereby granted, free of charge, to any person obtaining a copy
  12.  * of this software and associated documentation files (the "Software"), to deal
  13.  * in the Software without restriction, including without limitation the rights
  14.  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15.  * copies of the Software, and to permit persons to whom the Software is
  16.  * furnished to do so, subject to the following conditions:
  17.  *
  18.  * The above copyright notice and this permission notice shall be included in
  19.  * all copies or substantial portions of the Software.
  20.  *
  21.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22.  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23.  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24.  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25.  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26.  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27.  * THE SOFTWARE.
  28.  *
  29.  * @package CodeIgniter
  30.  * @author  EllisLab Dev Team
  31.  * @copyright   Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32.  * @copyright   Copyright (c) 2014 - 2018, British Columbia Institute of Technology (http://bcit.ca/)
  33.  * @license http://opensource.org/licenses/MIT  MIT License
  34.  * @link    https://codeigniter.com
  35.  * @since   Version 1.0.0
  36.  * @filesource
  37.  */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39.  
  40. /**
  41.  * CodeIgniter Email Class
  42.  *
  43.  * Permits email to be sent using Mail, Sendmail, or SMTP.
  44.  *
  45.  * @package     CodeIgniter
  46.  * @subpackage  Libraries
  47.  * @category    Libraries
  48.  * @author      EllisLab Dev Team
  49.  * @link        https://codeigniter.com/user_guide/libraries/email.html
  50.  */
  51. class CI_Email {
  52.  
  53.     /**
  54.      * Used as the User-Agent and X-Mailer headers' value.
  55.      *
  56.      * @var string
  57.      */
  58.     public $useragent   = 'CodeIgniter';
  59.  
  60.     /**
  61.      * Path to the Sendmail binary.
  62.      *
  63.      * @var string
  64.      */
  65.     public $mailpath    = '/usr/sbin/sendmail'; // Sendmail path
  66.  
  67.     /**
  68.      * Which method to use for sending e-mails.
  69.      *
  70.      * @var string  'mail', 'sendmail' or 'smtp'
  71.      */
  72.     public $protocol    = 'smtp';       // mail/sendmail/smtp
  73.  
  74.     /**
  75.      * STMP Server host
  76.      *
  77.      * @var string
  78.      */
  79.     public $smtp_host   = 'n3plcpnl0080.prod.ams3.secureserver.net';
  80.  
  81.     /**
  82.      * SMTP Username
  83.      *
  84.      * @var string
  85.      */
  86.     public $smtp_user   = 'no-reply@fragment.al';
  87.  
  88.     /**
  89.      * SMTP Password
  90.      *
  91.      * @var string
  92.      */
  93.     public $smtp_pass   = '#######';
  94.  
  95.     /**
  96.      * SMTP Server port
  97.      *
  98.      * @var int
  99.      */
  100.     public $smtp_port   = 587;
  101.  
  102.     /**
  103.      * SMTP connection timeout in seconds
  104.      *
  105.      * @var int
  106.      */
  107.     public $smtp_timeout    = 5;
  108.  
  109.     /**
  110.      * SMTP persistent connection
  111.      *
  112.      * @var bool
  113.      */
  114.     public $smtp_keepalive  = FALSE;
  115.  
  116.     /**
  117.      * SMTP Encryption
  118.      *
  119.      * @var string  empty, 'tls' or 'ssl'
  120.      */
  121.     public $smtp_crypto = 'SSL';
  122.  
  123.     /**
  124.      * Whether to apply word-wrapping to the message body.
  125.      *
  126.      * @var bool
  127.      */
  128.     public $wordwrap    = TRUE;
  129.  
  130.     /**
  131.      * Number of characters to wrap at.
  132.      *
  133.      * @see CI_Email::$wordwrap
  134.      * @var int
  135.      */
  136.     public $wrapchars   = 76;
  137.  
  138.     /**
  139.      * Message format.
  140.      *
  141.      * @var string  'text' or 'html'
  142.      */
  143.     public $mailtype    = 'html';
  144.  
  145.     /**
  146.      * Character set (default: utf-8)
  147.      *
  148.      * @var string
  149.      */
  150.     public $charset     = 'utf-8';
  151.  
  152.     /**
  153.      * Alternative message (for HTML messages only)
  154.      *
  155.      * @var string
  156.      */
  157.     public $alt_message = '';
  158.  
  159.     /**
  160.      * Whether to validate e-mail addresses.
  161.      *
  162.      * @var bool
  163.      */
  164.     public $validate    = TRUE;
  165.  
  166.     /**
  167.      * X-Priority header value.
  168.      *
  169.      * @var int 1-5
  170.      */
  171.     public $priority    = 3;            // Default priority (1 - 5)
  172.  
  173.     /**
  174.      * Newline character sequence.
  175.      * Use "\r\n" to comply with RFC 822.
  176.      *
  177.      * @link    http://www.ietf.org/rfc/rfc822.txt
  178.      * @var string  "\r\n" or "\n"
  179.      */
  180.     public $newline     = "\r\n";           // Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822)
  181.  
  182.     /**
  183.      * CRLF character sequence
  184.      *
  185.      * RFC 2045 specifies that for 'quoted-printable' encoding,
  186.      * "\r\n" must be used. However, it appears that some servers
  187.      * (even on the receiving end) don't handle it properly and
  188.      * switching to "\n", while improper, is the only solution
  189.      * that seems to work for all environments.
  190.      *
  191.      * @link    http://www.ietf.org/rfc/rfc822.txt
  192.      * @var string
  193.      */
  194.     public $crlf        = "\r\n";
  195.  
  196.     /**
  197.      * Whether to use Delivery Status Notification.
  198.      *
  199.      * @var bool
  200.      */
  201.     public $dsn     = FALSE;
  202.  
  203.     /**
  204.      * Whether to send multipart alternatives.
  205.      * Yahoo! doesn't seem to like these.
  206.      *
  207.      * @var bool
  208.      */
  209.     public $send_multipart  = TRUE;
  210.  
  211.     /**
  212.      * Whether to send messages to BCC recipients in batches.
  213.      *
  214.      * @var bool
  215.      */
  216.     public $bcc_batch_mode  = FALSE;
  217.  
  218.     /**
  219.      * BCC Batch max number size.
  220.      *
  221.      * @see CI_Email::$bcc_batch_mode
  222.      * @var int
  223.      */
  224.     public $bcc_batch_size  = 200;
  225.  
  226.     // --------------------------------------------------------------------
  227.  
  228.     /**
  229.      * Subject header
  230.      *
  231.      * @var string
  232.      */
  233.     protected $_subject     = '';
  234.  
  235.     /**
  236.      * Message body
  237.      *
  238.      * @var string
  239.      */
  240.     protected $_body        = '';
  241.  
  242.     /**
  243.      * Final message body to be sent.
  244.      *
  245.      * @var string
  246.      */
  247.     protected $_finalbody       = '';
  248.  
  249.     /**
  250.      * Final headers to send
  251.      *
  252.      * @var string
  253.      */
  254.     protected $_header_str      = '';
  255.  
  256.     /**
  257.      * SMTP Connection socket placeholder
  258.      *
  259.      * @var resource
  260.      */
  261.     protected $_smtp_connect    = '';
  262.  
  263.     /**
  264.      * Mail encoding
  265.      *
  266.      * @var string  '8bit' or '7bit'
  267.      */
  268.     protected $_encoding        = '8bit';
  269.  
  270.     /**
  271.      * Whether to perform SMTP authentication
  272.      *
  273.      * @var bool
  274.      */
  275.     protected $_smtp_auth       = FALSE;
  276.  
  277.     /**
  278.      * Whether to send a Reply-To header
  279.      *
  280.      * @var bool
  281.      */
  282.     protected $_replyto_flag    = FALSE;
  283.  
  284.     /**
  285.      * Debug messages
  286.      *
  287.      * @see CI_Email::print_debugger()
  288.      * @var string
  289.      */
  290.     protected $_debug_msg       = array();
  291.  
  292.     /**
  293.      * Recipients
  294.      *
  295.      * @var string[]
  296.      */
  297.     protected $_recipients      = array();
  298.  
  299.     /**
  300.      * CC Recipients
  301.      *
  302.      * @var string[]
  303.      */
  304.     protected $_cc_array        = array();
  305.  
  306.     /**
  307.      * BCC Recipients
  308.      *
  309.      * @var string[]
  310.      */
  311.     protected $_bcc_array       = array();
  312.  
  313.     /**
  314.      * Message headers
  315.      *
  316.      * @var string[]
  317.      */
  318.     protected $_headers     = array();
  319.  
  320.     /**
  321.      * Attachment data
  322.      *
  323.      * @var array
  324.      */
  325.     protected $_attachments     = array();
  326.  
  327.     /**
  328.      * Valid $protocol values
  329.      *
  330.      * @see CI_Email::$protocol
  331.      * @var string[]
  332.      */
  333.     protected $_protocols       = array('mail', 'sendmail', 'smtp');
  334.  
  335.     /**
  336.      * Base charsets
  337.      *
  338.      * Character sets valid for 7-bit encoding,
  339.      * excluding language suffix.
  340.      *
  341.      * @var string[]
  342.      */
  343.     protected $_base_charsets   = array('us-ascii', 'iso-2022-');
  344.  
  345.     /**
  346.      * Bit depths
  347.      *
  348.      * Valid mail encodings
  349.      *
  350.      * @see CI_Email::$_encoding
  351.      * @var string[]
  352.      */
  353.     protected $_bit_depths      = array('7bit', '8bit');
  354.  
  355.     /**
  356.      * $priority translations
  357.      *
  358.      * Actual values to send with the X-Priority header
  359.      *
  360.      * @var string[]
  361.      */
  362.     protected $_priorities = array(
  363.         1 => '1 (Highest)',
  364.         2 => '2 (High)',
  365.         3 => '3 (Normal)',
  366.         4 => '4 (Low)',
  367.         5 => '5 (Lowest)'
  368.     );
  369.  
  370.     /**
  371.      * mbstring.func_overload flag
  372.      *
  373.      * @var bool
  374.      */
  375.     protected static $func_overload;
  376.  
  377.     // --------------------------------------------------------------------
  378.  
  379.     /**
  380.      * Constructor - Sets Email Preferences
  381.      *
  382.      * The constructor can be passed an array of config values
  383.      *
  384.      * @param   array   $config = array()
  385.      * @return  void
  386.      */
  387.     public function __construct(array $config = array())
  388.     {
  389.         $this->charset = config_item('charset');
  390.         $this->initialize($config);
  391.  
  392.         isset(self::$func_overload) OR self::$func_overload = (extension_loaded('mbstring') && ini_get('mbstring.func_overload'));
  393.  
  394.         log_message('info', 'Email Class Initialized');
  395.     }
  396.  
  397.     // --------------------------------------------------------------------
  398.  
  399.     /**
  400.      * Initialize preferences
  401.      *
  402.      * @param   array   $config
  403.      * @return  CI_Email
  404.      */
  405.     public function initialize(array $config = array())
  406.     {
  407.         $this->clear();
  408.  
  409.         foreach ($config as $key => $val)
  410.         {
  411.             if (isset($this->$key))
  412.             {
  413.                 $method = 'set_'.$key;
  414.  
  415.                 if (method_exists($this, $method))
  416.                 {
  417.                     $this->$method($val);
  418.                 }
  419.                 else
  420.                 {
  421.                     $this->$key = $val;
  422.                 }
  423.             }
  424.         }
  425.  
  426.         $this->charset = strtoupper($this->charset);
  427.         $this->_smtp_auth = isset($this->smtp_user[0], $this->smtp_pass[0]);
  428.  
  429.         return $this;
  430.     }
  431.  
  432.     // --------------------------------------------------------------------
  433.  
  434.     /**
  435.      * Initialize the Email Data
  436.      *
  437.      * @param   bool
  438.      * @return  CI_Email
  439.      */
  440.     public function clear($clear_attachments = FALSE)
  441.     {
  442.         $this->_subject     = '';
  443.         $this->_body        = '';
  444.         $this->_finalbody   = '';
  445.         $this->_header_str  = '';
  446.         $this->_replyto_flag    = FALSE;
  447.         $this->_recipients  = array();
  448.         $this->_cc_array    = array();
  449.         $this->_bcc_array   = array();
  450.         $this->_headers     = array();
  451.         $this->_debug_msg   = array();
  452.  
  453.         $this->set_header('Date', $this->_set_date());
  454.  
  455.         if ($clear_attachments !== FALSE)
  456.         {
  457.             $this->_attachments = array();
  458.         }
  459.  
  460.         return $this;
  461.     }
  462.  
  463.     // --------------------------------------------------------------------
  464.  
  465.     /**
  466.      * Set FROM
  467.      *
  468.      * @param   string  $from
  469.      * @param   string  $name
  470.      * @param   string  $return_path = NULL Return-Path
  471.      * @return  CI_Email
  472.      */
  473.     public function from($from, $name = '', $return_path = NULL)
  474.     {
  475.         if (preg_match('/\<(.*)\>/', $from, $match))
  476.         {
  477.             $from = $match[1];
  478.         }
  479.  
  480.         if ($this->validate)
  481.         {
  482.             $this->validate_email($this->_str_to_array($from));
  483.             if ($return_path)
  484.             {
  485.                 $this->validate_email($this->_str_to_array($return_path));
  486.             }
  487.         }
  488.  
  489.         // prepare the display name
  490.         if ($name !== '')
  491.         {
  492.             // only use Q encoding if there are characters that would require it
  493.             if ( ! preg_match('/[\200-\377]/', $name))
  494.             {
  495.                 // add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes
  496.                 $name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"';
  497.             }
  498.             else
  499.             {
  500.                 $name = $this->_prep_q_encoding($name);
  501.             }
  502.         }
  503.  
  504.         $this->set_header('From', $name.' <'.$from.'>');
  505.  
  506.         isset($return_path) OR $return_path = $from;
  507.         $this->set_header('Return-Path', '<'.$return_path.'>');
  508.  
  509.         return $this;
  510.     }
  511.  
  512.     // --------------------------------------------------------------------
  513.  
  514.     /**
  515.      * Set Reply-to
  516.      *
  517.      * @param   string
  518.      * @param   string
  519.      * @return  CI_Email
  520.      */
  521.     public function reply_to($replyto, $name = '')
  522.     {
  523.         if (preg_match('/\<(.*)\>/', $replyto, $match))
  524.         {
  525.             $replyto = $match[1];
  526.         }
  527.  
  528.         if ($this->validate)
  529.         {
  530.             $this->validate_email($this->_str_to_array($replyto));
  531.         }
  532.  
  533.         if ($name !== '')
  534.         {
  535.             // only use Q encoding if there are characters that would require it
  536.             if ( ! preg_match('/[\200-\377]/', $name))
  537.             {
  538.                 // add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes
  539.                 $name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"';
  540.             }
  541.             else
  542.             {
  543.                 $name = $this->_prep_q_encoding($name);
  544.             }
  545.         }
  546.  
  547.         $this->set_header('Reply-To', $name.' <'.$replyto.'>');
  548.         $this->_replyto_flag = TRUE;
  549.  
  550.         return $this;
  551.     }
  552.  
  553.     // --------------------------------------------------------------------
  554.  
  555.     /**
  556.      * Set Recipients
  557.      *
  558.      * @param   string
  559.      * @return  CI_Email
  560.      */
  561.     public function to($to)
  562.     {
  563.         $to = $this->_str_to_array($to);
  564.         $to = $this->clean_email($to);
  565.  
  566.         if ($this->validate)
  567.         {
  568.             $this->validate_email($to);
  569.         }
  570.  
  571.         if ($this->_get_protocol() !== 'mail')
  572.         {
  573.             $this->set_header('To', implode(', ', $to));
  574.         }
  575.  
  576.         $this->_recipients = $to;
  577.  
  578.         return $this;
  579.     }
  580.  
  581.     // --------------------------------------------------------------------
  582.  
  583.     /**
  584.      * Set CC
  585.      *
  586.      * @param   string
  587.      * @return  CI_Email
  588.      */
  589.     public function cc($cc)
  590.     {
  591.         $cc = $this->clean_email($this->_str_to_array($cc));
  592.  
  593.         if ($this->validate)
  594.         {
  595.             $this->validate_email($cc);
  596.         }
  597.  
  598.         $this->set_header('Cc', implode(', ', $cc));
  599.  
  600.         if ($this->_get_protocol() === 'smtp')
  601.         {
  602.             $this->_cc_array = $cc;
  603.         }
  604.  
  605.         return $this;
  606.     }
  607.  
  608.     // --------------------------------------------------------------------
  609.  
  610.     /**
  611.      * Set BCC
  612.      *
  613.      * @param   string
  614.      * @param   string
  615.      * @return  CI_Email
  616.      */
  617.     public function bcc($bcc, $limit = '')
  618.     {
  619.         if ($limit !== '' && is_numeric($limit))
  620.         {
  621.             $this->bcc_batch_mode = TRUE;
  622.             $this->bcc_batch_size = $limit;
  623.         }
  624.  
  625.         $bcc = $this->clean_email($this->_str_to_array($bcc));
  626.  
  627.         if ($this->validate)
  628.         {
  629.             $this->validate_email($bcc);
  630.         }
  631.  
  632.         if ($this->_get_protocol() === 'smtp' OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size))
  633.         {
  634.             $this->_bcc_array = $bcc;
  635.         }
  636.         else
  637.         {
  638.             $this->set_header('Bcc', implode(', ', $bcc));
  639.         }
  640.  
  641.         return $this;
  642.     }
  643.  
  644.     // --------------------------------------------------------------------
  645.  
  646.     /**
  647.      * Set Email Subject
  648.      *
  649.      * @param   string
  650.      * @return  CI_Email
  651.      */
  652.     public function subject($subject)
  653.     {
  654.         $subject = $this->_prep_q_encoding($subject);
  655.         $this->set_header('Subject', $subject);
  656.         return $this;
  657.     }
  658.  
  659.     // --------------------------------------------------------------------
  660.  
  661.     /**
  662.      * Set Body
  663.      *
  664.      * @param   string
  665.      * @return  CI_Email
  666.      */
  667.     public function message($body)
  668.     {
  669.         $this->_body = rtrim(str_replace("\r", '', $body));
  670.         return $this;
  671.     }
  672.  
  673.     // --------------------------------------------------------------------
  674.  
  675.     /**
  676.      * Assign file attachments
  677.      *
  678.      * @param   string  $file   Can be local path, URL or buffered content
  679.      * @param   string  $disposition = 'attachment'
  680.      * @param   string  $newname = NULL
  681.      * @param   string  $mime = ''
  682.      * @return  CI_Email
  683.      */
  684.     public function attach($file, $disposition = '', $newname = NULL, $mime = '')
  685.     {
  686.         if ($mime === '')
  687.         {
  688.             if (strpos($file, '://') === FALSE && ! file_exists($file))
  689.             {
  690.                 $this->_set_error_message('lang:email_attachment_missing', $file);
  691.                 return FALSE;
  692.             }
  693.  
  694.             if ( ! $fp = @fopen($file, 'rb'))
  695.             {
  696.                 $this->_set_error_message('lang:email_attachment_unreadable', $file);
  697.                 return FALSE;
  698.             }
  699.  
  700.             $file_content = stream_get_contents($fp);
  701.             $mime = $this->_mime_types(pathinfo($file, PATHINFO_EXTENSION));
  702.             fclose($fp);
  703.         }
  704.         else
  705.         {
  706.             $file_content =& $file; // buffered file
  707.         }
  708.  
  709.         $this->_attachments[] = array(
  710.             'name'      => array($file, $newname),
  711.             'disposition'   => empty($disposition) ? 'attachment' : $disposition,  // Can also be 'inline'  Not sure if it matters
  712.             'type'      => $mime,
  713.             'content'   => chunk_split(base64_encode($file_content)),
  714.             'multipart' => 'mixed'
  715.         );
  716.  
  717.         return $this;
  718.     }
  719.  
  720.     // --------------------------------------------------------------------
  721.  
  722.     /**
  723.      * Set and return attachment Content-ID
  724.      *
  725.      * Useful for attached inline pictures
  726.      *
  727.      * @param   string  $filename
  728.      * @return  string
  729.      */
  730.     public function attachment_cid($filename)
  731.     {
  732.         for ($i = 0, $c = count($this->_attachments); $i < $c; $i++)
  733.         {
  734.             if ($this->_attachments[$i]['name'][0] === $filename)
  735.             {
  736.                 $this->_attachments[$i]['multipart'] = 'related';
  737.                 $this->_attachments[$i]['cid'] = uniqid(basename($this->_attachments[$i]['name'][0]).'@');
  738.                 return $this->_attachments[$i]['cid'];
  739.             }
  740.         }
  741.  
  742.         return FALSE;
  743.     }
  744.  
  745.     // --------------------------------------------------------------------
  746.  
  747.     /**
  748.      * Add a Header Item
  749.      *
  750.      * @param   string
  751.      * @param   string
  752.      * @return  CI_Email
  753.      */
  754.     public function set_header($header, $value)
  755.     {
  756.         $this->_headers[$header] = str_replace(array("\n", "\r"), '', $value);
  757.         return $this;
  758.     }
  759.  
  760.     // --------------------------------------------------------------------
  761.  
  762.     /**
  763.      * Convert a String to an Array
  764.      *
  765.      * @param   string
  766.      * @return  array
  767.      */
  768.     protected function _str_to_array($email)
  769.     {
  770.         if ( ! is_array($email))
  771.         {
  772.             return (strpos($email, ',') !== FALSE)
  773.                 ? preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY)
  774.                 : (array) trim($email);
  775.         }
  776.  
  777.         return $email;
  778.     }
  779.  
  780.     // --------------------------------------------------------------------
  781.  
  782.     /**
  783.      * Set Multipart Value
  784.      *
  785.      * @param   string
  786.      * @return  CI_Email
  787.      */
  788.     public function set_alt_message($str)
  789.     {
  790.         $this->alt_message = (string) $str;
  791.         return $this;
  792.     }
  793.  
  794.     // --------------------------------------------------------------------
  795.  
  796.     /**
  797.      * Set Mailtype
  798.      *
  799.      * @param   string
  800.      * @return  CI_Email
  801.      */
  802.     public function set_mailtype($type = 'text')
  803.     {
  804.         $this->mailtype = ($type === 'html') ? 'html' : 'text';
  805.         return $this;
  806.     }
  807.  
  808.     // --------------------------------------------------------------------
  809.  
  810.     /**
  811.      * Set Wordwrap
  812.      *
  813.      * @param   bool
  814.      * @return  CI_Email
  815.      */
  816.     public function set_wordwrap($wordwrap = TRUE)
  817.     {
  818.         $this->wordwrap = (bool) $wordwrap;
  819.         return $this;
  820.     }
  821.  
  822.     // --------------------------------------------------------------------
  823.  
  824.     /**
  825.      * Set Protocol
  826.      *
  827.      * @param   string
  828.      * @return  CI_Email
  829.      */
  830.     public function set_protocol($protocol = 'mail')
  831.     {
  832.         $this->protocol = in_array($protocol, $this->_protocols, TRUE) ? strtolower($protocol) : 'mail';
  833.         return $this;
  834.     }
  835.  
  836.     // --------------------------------------------------------------------
  837.  
  838.     /**
  839.      * Set Priority
  840.      *
  841.      * @param   int
  842.      * @return  CI_Email
  843.      */
  844.     public function set_priority($n = 3)
  845.     {
  846.         $this->priority = preg_match('/^[1-5]$/', $n) ? (int) $n : 3;
  847.         return $this;
  848.     }
  849.  
  850.     // --------------------------------------------------------------------
  851.  
  852.     /**
  853.      * Set Newline Character
  854.      *
  855.      * @param   string
  856.      * @return  CI_Email
  857.      */
  858.     public function set_newline($newline = "\n")
  859.     {
  860.         $this->newline = in_array($newline, array("\n", "\r\n", "\r")) ? $newline : "\n";
  861.         return $this;
  862.     }
  863.  
  864.     // --------------------------------------------------------------------
  865.  
  866.     /**
  867.      * Set CRLF
  868.      *
  869.      * @param   string
  870.      * @return  CI_Email
  871.      */
  872.     public function set_crlf($crlf = "\n")
  873.     {
  874.         $this->crlf = ($crlf !== "\n" && $crlf !== "\r\n" && $crlf !== "\r") ? "\n" : $crlf;
  875.         return $this;
  876.     }
  877.  
  878.     // --------------------------------------------------------------------
  879.  
  880.     /**
  881.      * Get the Message ID
  882.      *
  883.      * @return  string
  884.      */
  885.     protected function _get_message_id()
  886.     {
  887.         $from = str_replace(array('>', '<'), '', $this->_headers['Return-Path']);
  888.         return '<'.uniqid('').strstr($from, '@').'>';
  889.     }
  890.  
  891.     // --------------------------------------------------------------------
  892.  
  893.     /**
  894.      * Get Mail Protocol
  895.      *
  896.      * @return  mixed
  897.      */
  898.     protected function _get_protocol()
  899.     {
  900.         $this->protocol = strtolower($this->protocol);
  901.         in_array($this->protocol, $this->_protocols, TRUE) OR $this->protocol = 'mail';
  902.         return $this->protocol;
  903.     }
  904.  
  905.     // --------------------------------------------------------------------
  906.  
  907.     /**
  908.      * Get Mail Encoding
  909.      *
  910.      * @return  string
  911.      */
  912.     protected function _get_encoding()
  913.     {
  914.         in_array($this->_encoding, $this->_bit_depths) OR $this->_encoding = '8bit';
  915.  
  916.         foreach ($this->_base_charsets as $charset)
  917.         {
  918.             if (strpos($this->charset, $charset) === 0)
  919.             {
  920.                 $this->_encoding = '7bit';
  921.             }
  922.         }
  923.  
  924.         return $this->_encoding;
  925.     }
  926.  
  927.     // --------------------------------------------------------------------
  928.  
  929.     /**
  930.      * Get content type (text/html/attachment)
  931.      *
  932.      * @return  string
  933.      */
  934.     protected function _get_content_type()
  935.     {
  936.         if ($this->mailtype === 'html')
  937.         {
  938.             return empty($this->_attachments) ? 'html' : 'html-attach';
  939.         }
  940.         elseif  ($this->mailtype === 'text' && ! empty($this->_attachments))
  941.         {
  942.             return 'plain-attach';
  943.         }
  944.  
  945.         return 'plain';
  946.     }
  947.  
  948.     // --------------------------------------------------------------------
  949.  
  950.     /**
  951.      * Set RFC 822 Date
  952.      *
  953.      * @return  string
  954.      */
  955.     protected function _set_date()
  956.     {
  957.         $timezone = date('Z');
  958.         $operator = ($timezone[0] === '-') ? '-' : '+';
  959.         $timezone = abs($timezone);
  960.         $timezone = floor($timezone/3600) * 100 + ($timezone % 3600) / 60;
  961.  
  962.         return sprintf('%s %s%04d', date('D, j M Y H:i:s'), $operator, $timezone);
  963.     }
  964.  
  965.     // --------------------------------------------------------------------
  966.  
  967.     /**
  968.      * Mime message
  969.      *
  970.      * @return  string
  971.      */
  972.     protected function _get_mime_message()
  973.     {
  974.         return 'This is a multi-part message in MIME format.'.$this->newline.'Your email application may not support this format.';
  975.     }
  976.  
  977.     // --------------------------------------------------------------------
  978.  
  979.     /**
  980.      * Validate Email Address
  981.      *
  982.      * @param   string
  983.      * @return  bool
  984.      */
  985.     public function validate_email($email)
  986.     {
  987.         if ( ! is_array($email))
  988.         {
  989.             $this->_set_error_message('lang:email_must_be_array');
  990.             return FALSE;
  991.         }
  992.  
  993.         foreach ($email as $val)
  994.         {
  995.             if ( ! $this->valid_email($val))
  996.             {
  997.                 $this->_set_error_message('lang:email_invalid_address', $val);
  998.                 return FALSE;
  999.             }
  1000.         }
  1001.  
  1002.         return TRUE;
  1003.     }
  1004.  
  1005.     // --------------------------------------------------------------------
  1006.  
  1007.     /**
  1008.      * Email Validation
  1009.      *
  1010.      * @param   string
  1011.      * @return  bool
  1012.      */
  1013.     public function valid_email($email)
  1014.     {
  1015.         if (function_exists('idn_to_ascii') && preg_match('#\A([^@]+)@(.+)\z#', $email, $matches))
  1016.         {
  1017.             $domain = defined('INTL_IDNA_VARIANT_UTS46')
  1018.                 ? idn_to_ascii($matches[2], 0, INTL_IDNA_VARIANT_UTS46)
  1019.                 : idn_to_ascii($matches[2]);
  1020.             $email = $matches[1].'@'.$domain;
  1021.         }
  1022.  
  1023.         return (bool) filter_var($email, FILTER_VALIDATE_EMAIL);
  1024.     }
  1025.  
  1026.     // --------------------------------------------------------------------
  1027.  
  1028.     /**
  1029.      * Clean Extended Email Address: Joe Smith <joe@smith.com>
  1030.      *
  1031.      * @param   string
  1032.      * @return  string
  1033.      */
  1034.     public function clean_email($email)
  1035.     {
  1036.         if ( ! is_array($email))
  1037.         {
  1038.             return preg_match('/\<(.*)\>/', $email, $match) ? $match[1] : $email;
  1039.         }
  1040.  
  1041.         $clean_email = array();
  1042.  
  1043.         foreach ($email as $addy)
  1044.         {
  1045.             $clean_email[] = preg_match('/\<(.*)\>/', $addy, $match) ? $match[1] : $addy;
  1046.         }
  1047.  
  1048.         return $clean_email;
  1049.     }
  1050.  
  1051.     // --------------------------------------------------------------------
  1052.  
  1053.     /**
  1054.      * Build alternative plain text message
  1055.      *
  1056.      * Provides the raw message for use in plain-text headers of
  1057.      * HTML-formatted emails.
  1058.      * If the user hasn't specified his own alternative message
  1059.      * it creates one by stripping the HTML
  1060.      *
  1061.      * @return  string
  1062.      */
  1063.     protected function _get_alt_message()
  1064.     {
  1065.         if ( ! empty($this->alt_message))
  1066.         {
  1067.             return ($this->wordwrap)
  1068.                 ? $this->word_wrap($this->alt_message, 76)
  1069.                 : $this->alt_message;
  1070.         }
  1071.  
  1072.         $body = preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->_body, $match) ? $match[1] : $this->_body;
  1073.         $body = str_replace("\t", '', preg_replace('#<!--(.*)--\>#', '', trim(strip_tags($body))));
  1074.  
  1075.         for ($i = 20; $i >= 3; $i--)
  1076.         {
  1077.             $body = str_replace(str_repeat("\n", $i), "\n\n", $body);
  1078.         }
  1079.  
  1080.         // Reduce multiple spaces
  1081.         $body = preg_replace('| +|', ' ', $body);
  1082.  
  1083.         return ($this->wordwrap)
  1084.             ? $this->word_wrap($body, 76)
  1085.             : $body;
  1086.     }
  1087.  
  1088.     // --------------------------------------------------------------------
  1089.  
  1090.     /**
  1091.      * Word Wrap
  1092.      *
  1093.      * @param   string
  1094.      * @param   int line-length limit
  1095.      * @return  string
  1096.      */
  1097.     public function word_wrap($str, $charlim = NULL)
  1098.     {
  1099.         // Set the character limit, if not already present
  1100.         if (empty($charlim))
  1101.         {
  1102.             $charlim = empty($this->wrapchars) ? 76 : $this->wrapchars;
  1103.         }
  1104.  
  1105.         // Standardize newlines
  1106.         if (strpos($str, "\r") !== FALSE)
  1107.         {
  1108.             $str = str_replace(array("\r\n", "\r"), "\n", $str);
  1109.         }
  1110.  
  1111.         // Reduce multiple spaces at end of line
  1112.         $str = preg_replace('| +\n|', "\n", $str);
  1113.  
  1114.         // If the current word is surrounded by {unwrap} tags we'll
  1115.         // strip the entire chunk and replace it with a marker.
  1116.         $unwrap = array();
  1117.         if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches))
  1118.         {
  1119.             for ($i = 0, $c = count($matches[0]); $i < $c; $i++)
  1120.             {
  1121.                 $unwrap[] = $matches[1][$i];
  1122.                 $str = str_replace($matches[0][$i], '{{unwrapped'.$i.'}}', $str);
  1123.             }
  1124.         }
  1125.  
  1126.         // Use PHP's native function to do the initial wordwrap.
  1127.         // We set the cut flag to FALSE so that any individual words that are
  1128.         // too long get left alone. In the next step we'll deal with them.
  1129.         $str = wordwrap($str, $charlim, "\n", FALSE);
  1130.  
  1131.         // Split the string into individual lines of text and cycle through them
  1132.         $output = '';
  1133.         foreach (explode("\n", $str) as $line)
  1134.         {
  1135.             // Is the line within the allowed character count?
  1136.             // If so we'll join it to the output and continue
  1137.             if (self::strlen($line) <= $charlim)
  1138.             {
  1139.                 $output .= $line.$this->newline;
  1140.                 continue;
  1141.             }
  1142.  
  1143.             $temp = '';
  1144.             do
  1145.             {
  1146.                 // If the over-length word is a URL we won't wrap it
  1147.                 if (preg_match('!\[url.+\]|://|www\.!', $line))
  1148.                 {
  1149.                     break;
  1150.                 }
  1151.  
  1152.                 // Trim the word down
  1153.                 $temp .= self::substr($line, 0, $charlim - 1);
  1154.                 $line = self::substr($line, $charlim - 1);
  1155.             }
  1156.             while (self::strlen($line) > $charlim);
  1157.  
  1158.             // If $temp contains data it means we had to split up an over-length
  1159.             // word into smaller chunks so we'll add it back to our current line
  1160.             if ($temp !== '')
  1161.             {
  1162.                 $output .= $temp.$this->newline;
  1163.             }
  1164.  
  1165.             $output .= $line.$this->newline;
  1166.         }
  1167.  
  1168.         // Put our markers back
  1169.         if (count($unwrap) > 0)
  1170.         {
  1171.             foreach ($unwrap as $key => $val)
  1172.             {
  1173.                 $output = str_replace('{{unwrapped'.$key.'}}', $val, $output);
  1174.             }
  1175.         }
  1176.  
  1177.         return $output;
  1178.     }
  1179.  
  1180.     // --------------------------------------------------------------------
  1181.  
  1182.     /**
  1183.      * Build final headers
  1184.      *
  1185.      * @return  void
  1186.      */
  1187.     protected function _build_headers()
  1188.     {
  1189.         $this->set_header('User-Agent', $this->useragent);
  1190.         $this->set_header('X-Sender', $this->clean_email($this->_headers['From']));
  1191.         $this->set_header('X-Mailer', $this->useragent);
  1192.         $this->set_header('X-Priority', $this->_priorities[$this->priority]);
  1193.         $this->set_header('Message-ID', $this->_get_message_id());
  1194.         $this->set_header('Mime-Version', '1.0');
  1195.     }
  1196.  
  1197.     // --------------------------------------------------------------------
  1198.  
  1199.     /**
  1200.      * Write Headers as a string
  1201.      *
  1202.      * @return  void
  1203.      */
  1204.     protected function _write_headers()
  1205.     {
  1206.         if ($this->protocol === 'mail')
  1207.         {
  1208.             if (isset($this->_headers['Subject']))
  1209.             {
  1210.                 $this->_subject = $this->_headers['Subject'];
  1211.                 unset($this->_headers['Subject']);
  1212.             }
  1213.         }
  1214.  
  1215.         reset($this->_headers);
  1216.         $this->_header_str = '';
  1217.  
  1218.         foreach ($this->_headers as $key => $val)
  1219.         {
  1220.             $val = trim($val);
  1221.  
  1222.             if ($val !== '')
  1223.             {
  1224.                 $this->_header_str .= $key.': '.$val.$this->newline;
  1225.             }
  1226.         }
  1227.  
  1228.         if ($this->_get_protocol() === 'mail')
  1229.         {
  1230.             $this->_header_str = rtrim($this->_header_str);
  1231.         }
  1232.     }
  1233.  
  1234.     // --------------------------------------------------------------------
  1235.  
  1236.     /**
  1237.      * Build Final Body and attachments
  1238.      *
  1239.      * @return  void
  1240.      */
  1241.     protected function _build_message()
  1242.     {
  1243.         if ($this->wordwrap === TRUE && $this->mailtype !== 'html')
  1244.         {
  1245.             $this->_body = $this->word_wrap($this->_body);
  1246.         }
  1247.  
  1248.         $this->_write_headers();
  1249.  
  1250.         $hdr = ($this->_get_protocol() === 'mail') ? $this->newline : '';
  1251.         $body = '';
  1252.  
  1253.         switch ($this->_get_content_type())
  1254.         {
  1255.             case 'plain':
  1256.  
  1257.                 $hdr .= 'Content-Type: text/plain; charset='.$this->charset.$this->newline
  1258.                     .'Content-Transfer-Encoding: '.$this->_get_encoding();
  1259.  
  1260.                 if ($this->_get_protocol() === 'mail')
  1261.                 {
  1262.                     $this->_header_str .= $hdr;
  1263.                     $this->_finalbody = $this->_body;
  1264.                 }
  1265.                 else
  1266.                 {
  1267.                     $this->_finalbody = $hdr.$this->newline.$this->newline.$this->_body;
  1268.                 }
  1269.  
  1270.                 return;
  1271.  
  1272.             case 'html':
  1273.  
  1274.                 if ($this->send_multipart === FALSE)
  1275.                 {
  1276.                     $hdr .= 'Content-Type: text/html; charset='.$this->charset.$this->newline
  1277.                         .'Content-Transfer-Encoding: quoted-printable';
  1278.                 }
  1279.                 else
  1280.                 {
  1281.                     $boundary = uniqid('B_ALT_');
  1282.                     $hdr .= 'Content-Type: multipart/alternative; boundary="'.$boundary.'"';
  1283.  
  1284.                     $body .= $this->_get_mime_message().$this->newline.$this->newline
  1285.                         .'--'.$boundary.$this->newline
  1286.  
  1287.                         .'Content-Type: text/plain; charset='.$this->charset.$this->newline
  1288.                         .'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline.$this->newline
  1289.                         .$this->_get_alt_message().$this->newline.$this->newline
  1290.                         .'--'.$boundary.$this->newline
  1291.  
  1292.                         .'Content-Type: text/html; charset='.$this->charset.$this->newline
  1293.                         .'Content-Transfer-Encoding: quoted-printable'.$this->newline.$this->newline;
  1294.                 }
  1295.  
  1296.                 $this->_finalbody = $body.$this->_prep_quoted_printable($this->_body).$this->newline.$this->newline;
  1297.  
  1298.                 if ($this->_get_protocol() === 'mail')
  1299.                 {
  1300.                     $this->_header_str .= $hdr;
  1301.                 }
  1302.                 else
  1303.                 {
  1304.                     $this->_finalbody = $hdr.$this->newline.$this->newline.$this->_finalbody;
  1305.                 }
  1306.  
  1307.                 if ($this->send_multipart !== FALSE)
  1308.                 {
  1309.                     $this->_finalbody .= '--'.$boundary.'--';
  1310.                 }
  1311.  
  1312.                 return;
  1313.  
  1314.             case 'plain-attach':
  1315.  
  1316.                 $boundary = uniqid('B_ATC_');
  1317.                 $hdr .= 'Content-Type: multipart/mixed; boundary="'.$boundary.'"';
  1318.  
  1319.                 if ($this->_get_protocol() === 'mail')
  1320.                 {
  1321.                     $this->_header_str .= $hdr;
  1322.                 }
  1323.  
  1324.                 $body .= $this->_get_mime_message().$this->newline
  1325.                     .$this->newline
  1326.                     .'--'.$boundary.$this->newline
  1327.                     .'Content-Type: text/plain; charset='.$this->charset.$this->newline
  1328.                     .'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline
  1329.                     .$this->newline
  1330.                     .$this->_body.$this->newline.$this->newline;
  1331.  
  1332.                 $this->_append_attachments($body, $boundary);
  1333.  
  1334.                 break;
  1335.             case 'html-attach':
  1336.  
  1337.                 $alt_boundary = uniqid('B_ALT_');
  1338.                 $last_boundary = NULL;
  1339.  
  1340.                 if ($this->_attachments_have_multipart('mixed'))
  1341.                 {
  1342.                     $atc_boundary = uniqid('B_ATC_');
  1343.                     $hdr .= 'Content-Type: multipart/mixed; boundary="'.$atc_boundary.'"';
  1344.                     $last_boundary = $atc_boundary;
  1345.                 }
  1346.  
  1347.                 if ($this->_attachments_have_multipart('related'))
  1348.                 {
  1349.                     $rel_boundary = uniqid('B_REL_');
  1350.                     $rel_boundary_header = 'Content-Type: multipart/related; boundary="'.$rel_boundary.'"';
  1351.  
  1352.                     if (isset($last_boundary))
  1353.                     {
  1354.                         $body .= '--'.$last_boundary.$this->newline.$rel_boundary_header;
  1355.                     }
  1356.                     else
  1357.                     {
  1358.                         $hdr .= $rel_boundary_header;
  1359.                     }
  1360.  
  1361.                     $last_boundary = $rel_boundary;
  1362.                 }
  1363.  
  1364.                 if ($this->_get_protocol() === 'mail')
  1365.                 {
  1366.                     $this->_header_str .= $hdr;
  1367.                 }
  1368.  
  1369.                 self::strlen($body) && $body .= $this->newline.$this->newline;
  1370.                 $body .= $this->_get_mime_message().$this->newline.$this->newline
  1371.                     .'--'.$last_boundary.$this->newline
  1372.  
  1373.                     .'Content-Type: multipart/alternative; boundary="'.$alt_boundary.'"'.$this->newline.$this->newline
  1374.                     .'--'.$alt_boundary.$this->newline
  1375.  
  1376.                     .'Content-Type: text/plain; charset='.$this->charset.$this->newline
  1377.                     .'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline.$this->newline
  1378.                     .$this->_get_alt_message().$this->newline.$this->newline
  1379.                     .'--'.$alt_boundary.$this->newline
  1380.  
  1381.                     .'Content-Type: text/html; charset='.$this->charset.$this->newline
  1382.                     .'Content-Transfer-Encoding: quoted-printable'.$this->newline.$this->newline
  1383.  
  1384.                     .$this->_prep_quoted_printable($this->_body).$this->newline.$this->newline
  1385.                     .'--'.$alt_boundary.'--'.$this->newline.$this->newline;
  1386.  
  1387.                 if ( ! empty($rel_boundary))
  1388.                 {
  1389.                     $body .= $this->newline.$this->newline;
  1390.                     $this->_append_attachments($body, $rel_boundary, 'related');
  1391.                 }
  1392.  
  1393.                 // multipart/mixed attachments
  1394.                 if ( ! empty($atc_boundary))
  1395.                 {
  1396.                     $body .= $this->newline.$this->newline;
  1397.                     $this->_append_attachments($body, $atc_boundary, 'mixed');
  1398.                 }
  1399.  
  1400.                 break;
  1401.         }
  1402.  
  1403.         $this->_finalbody = ($this->_get_protocol() === 'mail')
  1404.             ? $body
  1405.             : $hdr.$this->newline.$this->newline.$body;
  1406.     }
  1407.  
  1408.     // --------------------------------------------------------------------
  1409.  
  1410.     protected function _attachments_have_multipart($type)
  1411.     {
  1412.         foreach ($this->_attachments as &$attachment)
  1413.         {
  1414.             if ($attachment['multipart'] === $type)
  1415.             {
  1416.                 return TRUE;
  1417.             }
  1418.         }
  1419.  
  1420.         return FALSE;
  1421.     }
  1422.  
  1423.     // --------------------------------------------------------------------
  1424.  
  1425.     /**
  1426.      * Prepares attachment string
  1427.      *
  1428.      * @param   string  $body       Message body to append to
  1429.      * @param   string  $boundary   Multipart boundary
  1430.      * @param   string  $multipart  When provided, only attachments of this type will be processed
  1431.      * @return  string
  1432.      */
  1433.     protected function _append_attachments(&$body, $boundary, $multipart = null)
  1434.     {
  1435.         for ($i = 0, $c = count($this->_attachments); $i < $c; $i++)
  1436.         {
  1437.             if (isset($multipart) && $this->_attachments[$i]['multipart'] !== $multipart)
  1438.             {
  1439.                 continue;
  1440.             }
  1441.  
  1442.             $name = isset($this->_attachments[$i]['name'][1])
  1443.                 ? $this->_attachments[$i]['name'][1]
  1444.                 : basename($this->_attachments[$i]['name'][0]);
  1445.  
  1446.             $body .= '--'.$boundary.$this->newline
  1447.                 .'Content-Type: '.$this->_attachments[$i]['type'].'; name="'.$name.'"'.$this->newline
  1448.                 .'Content-Disposition: '.$this->_attachments[$i]['disposition'].';'.$this->newline
  1449.                 .'Content-Transfer-Encoding: base64'.$this->newline
  1450.                 .(empty($this->_attachments[$i]['cid']) ? '' : 'Content-ID: <'.$this->_attachments[$i]['cid'].'>'.$this->newline)
  1451.                 .$this->newline
  1452.                 .$this->_attachments[$i]['content'].$this->newline;
  1453.         }
  1454.  
  1455.         // $name won't be set if no attachments were appended,
  1456.         // and therefore a boundary wouldn't be necessary
  1457.         empty($name) OR $body .= '--'.$boundary.'--';
  1458.     }
  1459.  
  1460.     // --------------------------------------------------------------------
  1461.  
  1462.     /**
  1463.      * Prep Quoted Printable
  1464.      *
  1465.      * Prepares string for Quoted-Printable Content-Transfer-Encoding
  1466.      * Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt
  1467.      *
  1468.      * @param   string
  1469.      * @return  string
  1470.      */
  1471.     protected function _prep_quoted_printable($str)
  1472.     {
  1473.         // ASCII code numbers for "safe" characters that can always be
  1474.         // used literally, without encoding, as described in RFC 2049.
  1475.         // http://www.ietf.org/rfc/rfc2049.txt
  1476.         static $ascii_safe_chars = array(
  1477.             // ' (  )   +   ,   -   .   /   :   =   ?
  1478.             39, 40, 41, 43, 44, 45, 46, 47, 58, 61, 63,
  1479.             // numbers
  1480.             48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  1481.             // upper-case letters
  1482.             65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  1483.             // lower-case letters
  1484.             97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122
  1485.         );
  1486.  
  1487.         // We are intentionally wrapping so mail servers will encode characters
  1488.         // properly and MUAs will behave, so {unwrap} must go!
  1489.         $str = str_replace(array('{unwrap}', '{/unwrap}'), '', $str);
  1490.  
  1491.         // RFC 2045 specifies CRLF as "\r\n".
  1492.         // However, many developers choose to override that and violate
  1493.         // the RFC rules due to (apparently) a bug in MS Exchange,
  1494.         // which only works with "\n".
  1495.         if ($this->crlf === "\r\n")
  1496.         {
  1497.             return quoted_printable_encode($str);
  1498.         }
  1499.  
  1500.         // Reduce multiple spaces & remove nulls
  1501.         $str = preg_replace(array('| +|', '/\x00+/'), array(' ', ''), $str);
  1502.  
  1503.         // Standardize newlines
  1504.         if (strpos($str, "\r") !== FALSE)
  1505.         {
  1506.             $str = str_replace(array("\r\n", "\r"), "\n", $str);
  1507.         }
  1508.  
  1509.         $escape = '=';
  1510.         $output = '';
  1511.  
  1512.         foreach (explode("\n", $str) as $line)
  1513.         {
  1514.             $length = self::strlen($line);
  1515.             $temp = '';
  1516.  
  1517.             // Loop through each character in the line to add soft-wrap
  1518.             // characters at the end of a line " =\r\n" and add the newly
  1519.             // processed line(s) to the output (see comment on $crlf class property)
  1520.             for ($i = 0; $i < $length; $i++)
  1521.             {
  1522.                 // Grab the next character
  1523.                 $char = $line[$i];
  1524.                 $ascii = ord($char);
  1525.  
  1526.                 // Convert spaces and tabs but only if it's the end of the line
  1527.                 if ($ascii === 32 OR $ascii === 9)
  1528.                 {
  1529.                     if ($i === ($length - 1))
  1530.                     {
  1531.                         $char = $escape.sprintf('%02s', dechex($ascii));
  1532.                     }
  1533.                 }
  1534.                 // DO NOT move this below the $ascii_safe_chars line!
  1535.                 //
  1536.                 // = (equals) signs are allowed by RFC2049, but must be encoded
  1537.                 // as they are the encoding delimiter!
  1538.                 elseif ($ascii === 61)
  1539.                 {
  1540.                     $char = $escape.strtoupper(sprintf('%02s', dechex($ascii)));  // =3D
  1541.                 }
  1542.                 elseif ( ! in_array($ascii, $ascii_safe_chars, TRUE))
  1543.                 {
  1544.                     $char = $escape.strtoupper(sprintf('%02s', dechex($ascii)));
  1545.                 }
  1546.  
  1547.                 // If we're at the character limit, add the line to the output,
  1548.                 // reset our temp variable, and keep on chuggin'
  1549.                 if ((self::strlen($temp) + self::strlen($char)) >= 76)
  1550.                 {
  1551.                     $output .= $temp.$escape.$this->crlf;
  1552.                     $temp = '';
  1553.                 }
  1554.  
  1555.                 // Add the character to our temporary line
  1556.                 $temp .= $char;
  1557.             }
  1558.  
  1559.             // Add our completed line to the output
  1560.             $output .= $temp.$this->crlf;
  1561.         }
  1562.  
  1563.         // get rid of extra CRLF tacked onto the end
  1564.         return self::substr($output, 0, self::strlen($this->crlf) * -1);
  1565.     }
  1566.  
  1567.     // --------------------------------------------------------------------
  1568.  
  1569.     /**
  1570.      * Prep Q Encoding
  1571.      *
  1572.      * Performs "Q Encoding" on a string for use in email headers.
  1573.      * It's related but not identical to quoted-printable, so it has its
  1574.      * own method.
  1575.      *
  1576.      * @param   string
  1577.      * @return  string
  1578.      */
  1579.     protected function _prep_q_encoding($str)
  1580.     {
  1581.         $str = str_replace(array("\r", "\n"), '', $str);
  1582.  
  1583.         if ($this->charset === 'UTF-8')
  1584.         {
  1585.             // Note: We used to have mb_encode_mimeheader() as the first choice
  1586.             //       here, but it turned out to be buggy and unreliable. DO NOT
  1587.             //       re-add it! -- Narf
  1588.             if (ICONV_ENABLED === TRUE)
  1589.             {
  1590.                 $output = @iconv_mime_encode('', $str,
  1591.                     array(
  1592.                         'scheme' => 'Q',
  1593.                         'line-length' => 76,
  1594.                         'input-charset' => $this->charset,
  1595.                         'output-charset' => $this->charset,
  1596.                         'line-break-chars' => $this->crlf
  1597.                     )
  1598.                 );
  1599.  
  1600.                 // There are reports that iconv_mime_encode() might fail and return FALSE
  1601.                 if ($output !== FALSE)
  1602.                 {
  1603.                     // iconv_mime_encode() will always put a header field name.
  1604.                     // We've passed it an empty one, but it still prepends our
  1605.                     // encoded string with ': ', so we need to strip it.
  1606.                     return self::substr($output, 2);
  1607.                 }
  1608.  
  1609.                 $chars = iconv_strlen($str, 'UTF-8');
  1610.             }
  1611.             elseif (MB_ENABLED === TRUE)
  1612.             {
  1613.                 $chars = mb_strlen($str, 'UTF-8');
  1614.             }
  1615.         }
  1616.  
  1617.         // We might already have this set for UTF-8
  1618.         isset($chars) OR $chars = self::strlen($str);
  1619.  
  1620.         $output = '=?'.$this->charset.'?Q?';
  1621.         for ($i = 0, $length = self::strlen($output); $i < $chars; $i++)
  1622.         {
  1623.             $chr = ($this->charset === 'UTF-8' && ICONV_ENABLED === TRUE)
  1624.                 ? '='.implode('=', str_split(strtoupper(bin2hex(iconv_substr($str, $i, 1, $this->charset))), 2))
  1625.                 : '='.strtoupper(bin2hex($str[$i]));
  1626.  
  1627.             // RFC 2045 sets a limit of 76 characters per line.
  1628.             // We'll append ?= to the end of each line though.
  1629.             if ($length + ($l = self::strlen($chr)) > 74)
  1630.             {
  1631.                 $output .= '?='.$this->crlf // EOL
  1632.                     .' =?'.$this->charset.'?Q?'.$chr; // New line
  1633.                 $length = 6 + self::strlen($this->charset) + $l; // Reset the length for the new line
  1634.             }
  1635.             else
  1636.             {
  1637.                 $output .= $chr;
  1638.                 $length += $l;
  1639.             }
  1640.         }
  1641.  
  1642.         // End the header
  1643.         return $output.'?=';
  1644.     }
  1645.  
  1646.     // --------------------------------------------------------------------
  1647.  
  1648.     /**
  1649.      * Send Email
  1650.      *
  1651.      * @param   bool    $auto_clear = TRUE
  1652.      * @return  bool
  1653.      */
  1654.     public function send($auto_clear = TRUE)
  1655.     {
  1656.         if ( ! isset($this->_headers['From']))
  1657.         {
  1658.             $this->_set_error_message('lang:email_no_from');
  1659.             return FALSE;
  1660.         }
  1661.  
  1662.         if ($this->_replyto_flag === FALSE)
  1663.         {
  1664.             $this->reply_to($this->_headers['From']);
  1665.         }
  1666.  
  1667.         if (empty($this->_recipients) && ! isset($this->_headers['To'])
  1668.             && empty($this->_bcc_array) && ! isset($this->_headers['Bcc'])
  1669.             && ! isset($this->_headers['Cc']))
  1670.         {
  1671.             $this->_set_error_message('lang:email_no_recipients');
  1672.             return FALSE;
  1673.         }
  1674.  
  1675.         $this->_build_headers();
  1676.  
  1677.         if ($this->bcc_batch_mode && count($this->_bcc_array) > $this->bcc_batch_size)
  1678.         {
  1679.             $this->batch_bcc_send();
  1680.  
  1681.             if ($auto_clear)
  1682.             {
  1683.                 $this->clear();
  1684.             }
  1685.  
  1686.             return TRUE;
  1687.         }
  1688.  
  1689.         $this->_build_message();
  1690.         $result = $this->_spool_email();
  1691.  
  1692.         if ($result && $auto_clear)
  1693.         {
  1694.             $this->clear();
  1695.         }
  1696.  
  1697.         return $result;
  1698.     }
  1699.  
  1700.     // --------------------------------------------------------------------
  1701.  
  1702.     /**
  1703.      * Batch Bcc Send. Sends groups of BCCs in batches
  1704.      *
  1705.      * @return  void
  1706.      */
  1707.     public function batch_bcc_send()
  1708.     {
  1709.         $float = $this->bcc_batch_size - 1;
  1710.         $set = '';
  1711.         $chunk = array();
  1712.  
  1713.         for ($i = 0, $c = count($this->_bcc_array); $i < $c; $i++)
  1714.         {
  1715.             if (isset($this->_bcc_array[$i]))
  1716.             {
  1717.                 $set .= ', '.$this->_bcc_array[$i];
  1718.             }
  1719.  
  1720.             if ($i === $float)
  1721.             {
  1722.                 $chunk[] = self::substr($set, 1);
  1723.                 $float += $this->bcc_batch_size;
  1724.                 $set = '';
  1725.             }
  1726.  
  1727.             if ($i === $c-1)
  1728.             {
  1729.                 $chunk[] = self::substr($set, 1);
  1730.             }
  1731.         }
  1732.  
  1733.         for ($i = 0, $c = count($chunk); $i < $c; $i++)
  1734.         {
  1735.             unset($this->_headers['Bcc']);
  1736.  
  1737.             $bcc = $this->clean_email($this->_str_to_array($chunk[$i]));
  1738.  
  1739.             if ($this->protocol !== 'smtp')
  1740.             {
  1741.                 $this->set_header('Bcc', implode(', ', $bcc));
  1742.             }
  1743.             else
  1744.             {
  1745.                 $this->_bcc_array = $bcc;
  1746.             }
  1747.  
  1748.             $this->_build_message();
  1749.             $this->_spool_email();
  1750.         }
  1751.     }
  1752.  
  1753.     // --------------------------------------------------------------------
  1754.  
  1755.     /**
  1756.      * Unwrap special elements
  1757.      *
  1758.      * @return  void
  1759.      */
  1760.     protected function _unwrap_specials()
  1761.     {
  1762.         $this->_finalbody = preg_replace_callback('/\{unwrap\}(.*?)\{\/unwrap\}/si', array($this, '_remove_nl_callback'), $this->_finalbody);
  1763.     }
  1764.  
  1765.     // --------------------------------------------------------------------
  1766.  
  1767.     /**
  1768.      * Strip line-breaks via callback
  1769.      *
  1770.      * @param   string  $matches
  1771.      * @return  string
  1772.      */
  1773.     protected function _remove_nl_callback($matches)
  1774.     {
  1775.         if (strpos($matches[1], "\r") !== FALSE OR strpos($matches[1], "\n") !== FALSE)
  1776.         {
  1777.             $matches[1] = str_replace(array("\r\n", "\r", "\n"), '', $matches[1]);
  1778.         }
  1779.  
  1780.         return $matches[1];
  1781.     }
  1782.  
  1783.     // --------------------------------------------------------------------
  1784.  
  1785.     /**
  1786.      * Spool mail to the mail server
  1787.      *
  1788.      * @return  bool
  1789.      */
  1790.     protected function _spool_email()
  1791.     {
  1792.         $this->_unwrap_specials();
  1793.  
  1794.         $protocol = $this->_get_protocol();
  1795.         $method   = '_send_with_'.$protocol;
  1796.         if ( ! $this->$method())
  1797.         {
  1798.             $this->_set_error_message('lang:email_send_failure_'.($protocol === 'mail' ? 'phpmail' : $protocol));
  1799.             return FALSE;
  1800.         }
  1801.  
  1802.         $this->_set_error_message('lang:email_sent', $protocol);
  1803.         return TRUE;
  1804.     }
  1805.  
  1806.     // --------------------------------------------------------------------
  1807.  
  1808.     /**
  1809.      * Validate email for shell
  1810.      *
  1811.      * Applies stricter, shell-safe validation to email addresses.
  1812.      * Introduced to prevent RCE via sendmail's -f option.
  1813.      *
  1814.      * @see https://github.com/bcit-ci/CodeIgniter/issues/4963
  1815.      * @see https://gist.github.com/Zenexer/40d02da5e07f151adeaeeaa11af9ab36
  1816.      * @license https://creativecommons.org/publicdomain/zero/1.0/  CC0 1.0, Public Domain
  1817.      *
  1818.      * Credits for the base concept go to Paul Buonopane <paul@namepros.com>
  1819.      *
  1820.      * @param   string  $email
  1821.      * @return  bool
  1822.      */
  1823.     protected function _validate_email_for_shell(&$email)
  1824.     {
  1825.         if (function_exists('idn_to_ascii') && $atpos = strpos($email, '@'))
  1826.         {
  1827.             list($account, $domain) = explode('@', $email, 2);
  1828.             $domain = defined('INTL_IDNA_VARIANT_UTS46')
  1829.                 ? idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46)
  1830.                 : idn_to_ascii($domain);
  1831.             $email = $account.'@'.$domain;
  1832.         }
  1833.  
  1834.         return (filter_var($email, FILTER_VALIDATE_EMAIL) === $email && preg_match('#\A[a-z0-9._+-]+@[a-z0-9.-]{1,253}\z#i', $email));
  1835.     }
  1836.  
  1837.     // --------------------------------------------------------------------
  1838.  
  1839.     /**
  1840.      * Send using mail()
  1841.      *
  1842.      * @return  bool
  1843.      */
  1844.     protected function _send_with_mail()
  1845.     {
  1846.         if (is_array($this->_recipients))
  1847.         {
  1848.             $this->_recipients = implode(', ', $this->_recipients);
  1849.         }
  1850.  
  1851.         // _validate_email_for_shell() below accepts by reference,
  1852.         // so this needs to be assigned to a variable
  1853.         $from = $this->clean_email($this->_headers['Return-Path']);
  1854.  
  1855.         if ( ! $this->_validate_email_for_shell($from))
  1856.         {
  1857.             return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str);
  1858.         }
  1859.  
  1860.         // most documentation of sendmail using the "-f" flag lacks a space after it, however
  1861.         // we've encountered servers that seem to require it to be in place.
  1862.         return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, '-f '.$from);
  1863.     }
  1864.  
  1865.     // --------------------------------------------------------------------
  1866.  
  1867.     /**
  1868.      * Send using Sendmail
  1869.      *
  1870.      * @return  bool
  1871.      */
  1872.     protected function _send_with_sendmail()
  1873.     {
  1874.         // _validate_email_for_shell() below accepts by reference,
  1875.         // so this needs to be assigned to a variable
  1876.         $from = $this->clean_email($this->_headers['From']);
  1877.         if ($this->_validate_email_for_shell($from))
  1878.         {
  1879.             $from = '-f '.$from;
  1880.         }
  1881.         else
  1882.         {
  1883.             $from = '';
  1884.         }
  1885.  
  1886.         // is popen() enabled?
  1887.         if ( ! function_usable('popen') OR FALSE === ($fp = @popen($this->mailpath.' -oi '.$from.' -t', 'w')))
  1888.         {
  1889.             // server probably has popen disabled, so nothing we can do to get a verbose error.
  1890.             return FALSE;
  1891.         }
  1892.  
  1893.         fputs($fp, $this->_header_str);
  1894.         fputs($fp, $this->_finalbody);
  1895.  
  1896.         $status = pclose($fp);
  1897.  
  1898.         if ($status !== 0)
  1899.         {
  1900.             $this->_set_error_message('lang:email_exit_status', $status);
  1901.             $this->_set_error_message('lang:email_no_socket');
  1902.             return FALSE;
  1903.         }
  1904.  
  1905.         return TRUE;
  1906.     }
  1907.  
  1908.     // --------------------------------------------------------------------
  1909.  
  1910.     /**
  1911.      * Send using SMTP
  1912.      *
  1913.      * @return  bool
  1914.      */
  1915.     protected function _send_with_smtp()
  1916.     {
  1917.         if ($this->smtp_host === '')
  1918.         {
  1919.             $this->_set_error_message('lang:email_no_hostname');
  1920.             return FALSE;
  1921.         }
  1922.  
  1923.         if ( ! $this->_smtp_connect() OR ! $this->_smtp_authenticate())
  1924.         {
  1925.             return FALSE;
  1926.         }
  1927.  
  1928.         if ( ! $this->_send_command('from', $this->clean_email($this->_headers['From'])))
  1929.         {
  1930.             $this->_smtp_end();
  1931.             return FALSE;
  1932.         }
  1933.  
  1934.         foreach ($this->_recipients as $val)
  1935.         {
  1936.             if ( ! $this->_send_command('to', $val))
  1937.             {
  1938.                 $this->_smtp_end();
  1939.                 return FALSE;
  1940.             }
  1941.         }
  1942.  
  1943.         foreach ($this->_cc_array as $val)
  1944.         {
  1945.             if ($val !== '' && ! $this->_send_command('to', $val))
  1946.             {
  1947.                 $this->_smtp_end();
  1948.                 return FALSE;
  1949.             }
  1950.         }
  1951.  
  1952.         foreach ($this->_bcc_array as $val)
  1953.         {
  1954.             if ($val !== '' && ! $this->_send_command('to', $val))
  1955.             {
  1956.                 $this->_smtp_end();
  1957.                 return FALSE;
  1958.             }
  1959.         }
  1960.  
  1961.         if ( ! $this->_send_command('data'))
  1962.         {
  1963.             $this->_smtp_end();
  1964.             return FALSE;
  1965.         }
  1966.  
  1967.         // perform dot transformation on any lines that begin with a dot
  1968.         $this->_send_data($this->_header_str.preg_replace('/^\./m', '..$1', $this->_finalbody));
  1969.  
  1970.         $this->_send_data('.');
  1971.         $reply = $this->_get_smtp_data();
  1972.         $this->_set_error_message($reply);
  1973.  
  1974.         $this->_smtp_end();
  1975.  
  1976.         if (strpos($reply, '250') !== 0)
  1977.         {
  1978.             $this->_set_error_message('lang:email_smtp_error', $reply);
  1979.             return FALSE;
  1980.         }
  1981.  
  1982.         return TRUE;
  1983.     }
  1984.  
  1985.     // --------------------------------------------------------------------
  1986.  
  1987.     /**
  1988.      * SMTP End
  1989.      *
  1990.      * Shortcut to send RSET or QUIT depending on keep-alive
  1991.      *
  1992.      * @return  void
  1993.      */
  1994.     protected function _smtp_end()
  1995.     {
  1996.         $this->_send_command($this->smtp_keepalive ? 'reset' : 'quit');
  1997.     }
  1998.  
  1999.     // --------------------------------------------------------------------
  2000.  
  2001.     /**
  2002.      * SMTP Connect
  2003.      *
  2004.      * @return  string
  2005.      */
  2006.     protected function _smtp_connect()
  2007.     {
  2008.         if (is_resource($this->_smtp_connect))
  2009.         {
  2010.             return TRUE;
  2011.         }
  2012.  
  2013.         $ssl = ($this->smtp_crypto === 'ssl') ? 'ssl://' : '';
  2014.  
  2015.         $this->_smtp_connect = fsockopen(
  2016.             $ssl.$this->smtp_host,
  2017.             $this->smtp_port,
  2018.             $errno,
  2019.             $errstr,
  2020.             $this->smtp_timeout
  2021.         );
  2022.  
  2023.         if ( ! is_resource($this->_smtp_connect))
  2024.         {
  2025.             $this->_set_error_message('lang:email_smtp_error', $errno.' '.$errstr);
  2026.             return FALSE;
  2027.         }
  2028.  
  2029.         stream_set_timeout($this->_smtp_connect, $this->smtp_timeout);
  2030.         $this->_set_error_message($this->_get_smtp_data());
  2031.  
  2032.         if ($this->smtp_crypto === 'tls')
  2033.         {
  2034.             $this->_send_command('hello');
  2035.             $this->_send_command('starttls');
  2036.  
  2037.             /**
  2038.              * STREAM_CRYPTO_METHOD_TLS_CLIENT is quite the mess ...
  2039.              *
  2040.              * - On PHP <5.6 it doesn't even mean TLS, but SSL 2.0, and there's no option to use actual TLS
  2041.              * - On PHP 5.6.0-5.6.6, >=7.2 it means negotiation with any of TLS 1.0, 1.1, 1.2
  2042.              * - On PHP 5.6.7-7.1.* it means only TLS 1.0
  2043.              *
  2044.              * We want the negotiation, so we'll force it below ...
  2045.              */
  2046.             $method = is_php('5.6')
  2047.                 ? STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
  2048.                 : STREAM_CRYPTO_METHOD_TLS_CLIENT;
  2049.             $crypto = stream_socket_enable_crypto($this->_smtp_connect, TRUE, $method);
  2050.  
  2051.             if ($crypto !== TRUE)
  2052.             {
  2053.                 $this->_set_error_message('lang:email_smtp_error', $this->_get_smtp_data());
  2054.                 return FALSE;
  2055.             }
  2056.         }
  2057.  
  2058.         return $this->_send_command('hello');
  2059.     }
  2060.  
  2061.     // --------------------------------------------------------------------
  2062.  
  2063.     /**
  2064.      * Send SMTP command
  2065.      *
  2066.      * @param   string
  2067.      * @param   string
  2068.      * @return  bool
  2069.      */
  2070.     protected function _send_command($cmd, $data = '')
  2071.     {
  2072.         switch ($cmd)
  2073.         {
  2074.             case 'hello':
  2075.                 if ($this->_smtp_auth OR $this->_get_encoding() === '8bit')
  2076.                 {
  2077.                     $this->_send_data('EHLO '.$this->_get_hostname());
  2078.                 }
  2079.                 else
  2080.                 {
  2081.                     $this->_send_data('HELO '.$this->_get_hostname());
  2082.                 }
  2083.  
  2084.                 $resp = 250;
  2085.                 break;
  2086.             case 'starttls':
  2087.                 $this->_send_data('STARTTLS');
  2088.                 $resp = 220;
  2089.                 break;
  2090.             case 'from':
  2091.                 $this->_send_data('MAIL FROM:<'.$data.'>');
  2092.                 $resp = 250;
  2093.                 break;
  2094.             case 'to':
  2095.                 if ($this->dsn)
  2096.                 {
  2097.                     $this->_send_data('RCPT TO:<'.$data.'> NOTIFY=SUCCESS,DELAY,FAILURE ORCPT=rfc822;'.$data);
  2098.                 }
  2099.                 else
  2100.                 {
  2101.                     $this->_send_data('RCPT TO:<'.$data.'>');
  2102.                 }
  2103.                 $resp = 250;
  2104.                 break;
  2105.             case 'data':
  2106.                 $this->_send_data('DATA');
  2107.                 $resp = 354;
  2108.                 break;
  2109.             case 'reset':
  2110.                 $this->_send_data('RSET');
  2111.                 $resp = 250;
  2112.                 break;
  2113.             case 'quit':
  2114.                 $this->_send_data('QUIT');
  2115.                 $resp = 221;
  2116.                 break;
  2117.         }
  2118.  
  2119.         $reply = $this->_get_smtp_data();
  2120.  
  2121.         $this->_debug_msg[] = '<pre>'.$cmd.': '.$reply.'</pre>';
  2122.  
  2123.         if ((int) self::substr($reply, 0, 3) !== $resp)
  2124.         {
  2125.             $this->_set_error_message('lang:email_smtp_error', $reply);
  2126.             return FALSE;
  2127.         }
  2128.  
  2129.         if ($cmd === 'quit')
  2130.         {
  2131.             fclose($this->_smtp_connect);
  2132.         }
  2133.  
  2134.         return TRUE;
  2135.     }
  2136.  
  2137.     // --------------------------------------------------------------------
  2138.  
  2139.     /**
  2140.      * SMTP Authenticate
  2141.      *
  2142.      * @return  bool
  2143.      */
  2144.     protected function _smtp_authenticate()
  2145.     {
  2146.         if ( ! $this->_smtp_auth)
  2147.         {
  2148.             return TRUE;
  2149.         }
  2150.  
  2151.         if ($this->smtp_user === '' && $this->smtp_pass === '')
  2152.         {
  2153.             $this->_set_error_message('lang:email_no_smtp_unpw');
  2154.             return FALSE;
  2155.         }
  2156.  
  2157.         $this->_send_data('AUTH LOGIN');
  2158.         $reply = $this->_get_smtp_data();
  2159.  
  2160.         if (strpos($reply, '503') === 0)    // Already authenticated
  2161.         {
  2162.             return TRUE;
  2163.         }
  2164.         elseif (strpos($reply, '334') !== 0)
  2165.         {
  2166.             $this->_set_error_message('lang:email_failed_smtp_login', $reply);
  2167.             return FALSE;
  2168.         }
  2169.  
  2170.         $this->_send_data(base64_encode($this->smtp_user));
  2171.         $reply = $this->_get_smtp_data();
  2172.  
  2173.         if (strpos($reply, '334') !== 0)
  2174.         {
  2175.             $this->_set_error_message('lang:email_smtp_auth_un', $reply);
  2176.             return FALSE;
  2177.         }
  2178.  
  2179.         $this->_send_data(base64_encode($this->smtp_pass));
  2180.         $reply = $this->_get_smtp_data();
  2181.  
  2182.         if (strpos($reply, '235') !== 0)
  2183.         {
  2184.             $this->_set_error_message('lang:email_smtp_auth_pw', $reply);
  2185.             return FALSE;
  2186.         }
  2187.  
  2188.         if ($this->smtp_keepalive)
  2189.         {
  2190.             $this->_smtp_auth = FALSE;
  2191.         }
  2192.  
  2193.         return TRUE;
  2194.     }
  2195.  
  2196.     // --------------------------------------------------------------------
  2197.  
  2198.     /**
  2199.      * Send SMTP data
  2200.      *
  2201.      * @param   string  $data
  2202.      * @return  bool
  2203.      */
  2204.     protected function _send_data($data)
  2205.     {
  2206.         $data .= $this->newline;
  2207.         for ($written = $timestamp = 0, $length = self::strlen($data); $written < $length; $written += $result)
  2208.         {
  2209.             if (($result = fwrite($this->_smtp_connect, self::substr($data, $written))) === FALSE)
  2210.             {
  2211.                 break;
  2212.             }
  2213.             // See https://bugs.php.net/bug.php?id=39598 and http://php.net/manual/en/function.fwrite.php#96951
  2214.             elseif ($result === 0)
  2215.             {
  2216.                 if ($timestamp === 0)
  2217.                 {
  2218.                     $timestamp = time();
  2219.                 }
  2220.                 elseif ($timestamp < (time() - $this->smtp_timeout))
  2221.                 {
  2222.                     $result = FALSE;
  2223.                     break;
  2224.                 }
  2225.  
  2226.                 usleep(250000);
  2227.                 continue;
  2228.             }
  2229.  
  2230.             $timestamp = 0;
  2231.         }
  2232.  
  2233.         if ($result === FALSE)
  2234.         {
  2235.             $this->_set_error_message('lang:email_smtp_data_failure', $data);
  2236.             return FALSE;
  2237.         }
  2238.  
  2239.         return TRUE;
  2240.     }
  2241.  
  2242.     // --------------------------------------------------------------------
  2243.  
  2244.     /**
  2245.      * Get SMTP data
  2246.      *
  2247.      * @return  string
  2248.      */
  2249.     protected function _get_smtp_data()
  2250.     {
  2251.         $data = '';
  2252.  
  2253.         while ($str = fgets($this->_smtp_connect, 512))
  2254.         {
  2255.             $data .= $str;
  2256.  
  2257.             if ($str[3] === ' ')
  2258.             {
  2259.                 break;
  2260.             }
  2261.         }
  2262.  
  2263.         return $data;
  2264.     }
  2265.  
  2266.     // --------------------------------------------------------------------
  2267.  
  2268.     /**
  2269.      * Get Hostname
  2270.      *
  2271.      * There are only two legal types of hostname - either a fully
  2272.      * qualified domain name (eg: "mail.example.com") or an IP literal
  2273.      * (eg: "[1.2.3.4]").
  2274.      *
  2275.      * @link    https://tools.ietf.org/html/rfc5321#section-2.3.5
  2276.      * @link    http://cbl.abuseat.org/namingproblems.html
  2277.      * @return  string
  2278.      */
  2279.     protected function _get_hostname()
  2280.     {
  2281.         if (isset($_SERVER['SERVER_NAME']))
  2282.         {
  2283.             return $_SERVER['SERVER_NAME'];
  2284.         }
  2285.  
  2286.         return isset($_SERVER['SERVER_ADDR']) ? '['.$_SERVER['SERVER_ADDR'].']' : '[127.0.0.1]';
  2287.     }
  2288.  
  2289.     // --------------------------------------------------------------------
  2290.  
  2291.     /**
  2292.      * Get Debug Message
  2293.      *
  2294.      * @param   array   $include    List of raw data chunks to include in the output
  2295.      *                  Valid options are: 'headers', 'subject', 'body'
  2296.      * @return  string
  2297.      */
  2298.     public function print_debugger($include = array('headers', 'subject', 'body'))
  2299.     {
  2300.         $msg = implode('', $this->_debug_msg);
  2301.  
  2302.         // Determine which parts of our raw data needs to be printed
  2303.         $raw_data = '';
  2304.         is_array($include) OR $include = array($include);
  2305.  
  2306.         in_array('headers', $include, TRUE) && $raw_data  = htmlspecialchars($this->_header_str)."\n";
  2307.         in_array('subject', $include, TRUE) && $raw_data .= htmlspecialchars($this->_subject)."\n";
  2308.         in_array('body', $include, TRUE)    && $raw_data .= htmlspecialchars($this->_finalbody);
  2309.  
  2310.         return $msg.($raw_data === '' ? '' : '<pre>'.$raw_data.'</pre>');
  2311.     }
  2312.  
  2313.     // --------------------------------------------------------------------
  2314.  
  2315.     /**
  2316.      * Set Message
  2317.      *
  2318.      * @param   string  $msg
  2319.      * @param   string  $val = ''
  2320.      * @return  void
  2321.      */
  2322.     protected function _set_error_message($msg, $val = '')
  2323.     {
  2324.         $CI =& get_instance();
  2325.         $CI->lang->load('email');
  2326.  
  2327.         if (sscanf($msg, 'lang:%s', $line) !== 1 OR FALSE === ($line = $CI->lang->line($line)))
  2328.         {
  2329.             $this->_debug_msg[] = str_replace('%s', $val, $msg).'<br />';
  2330.         }
  2331.         else
  2332.         {
  2333.             $this->_debug_msg[] = str_replace('%s', $val, $line).'<br />';
  2334.         }
  2335.     }
  2336.  
  2337.     // --------------------------------------------------------------------
  2338.  
  2339.     /**
  2340.      * Mime Types
  2341.      *
  2342.      * @param   string
  2343.      * @return  string
  2344.      */
  2345.     protected function _mime_types($ext = '')
  2346.     {
  2347.         $ext = strtolower($ext);
  2348.  
  2349.         $mimes =& get_mimes();
  2350.  
  2351.         if (isset($mimes[$ext]))
  2352.         {
  2353.             return is_array($mimes[$ext])
  2354.                 ? current($mimes[$ext])
  2355.                 : $mimes[$ext];
  2356.         }
  2357.  
  2358.         return 'application/x-unknown-content-type';
  2359.     }
  2360.  
  2361.     // --------------------------------------------------------------------
  2362.  
  2363.     /**
  2364.      * Destructor
  2365.      *
  2366.      * @return  void
  2367.      */
  2368.     public function __destruct()
  2369.     {
  2370.         is_resource($this->_smtp_connect) && $this->_send_command('quit');
  2371.     }
  2372.  
  2373.     // --------------------------------------------------------------------
  2374.  
  2375.     /**
  2376.      * Byte-safe strlen()
  2377.      *
  2378.      * @param   string  $str
  2379.      * @return  int
  2380.      */
  2381.     protected static function strlen($str)
  2382.     {
  2383.         return (self::$func_overload)
  2384.             ? mb_strlen($str, '8bit')
  2385.             : strlen($str);
  2386.     }
  2387.  
  2388.     // --------------------------------------------------------------------
  2389.  
  2390.     /**
  2391.      * Byte-safe substr()
  2392.      *
  2393.      * @param   string  $str
  2394.      * @param   int $start
  2395.      * @param   int $length
  2396.      * @return  string
  2397.      */
  2398.     protected static function substr($str, $start, $length = NULL)
  2399.     {
  2400.         if (self::$func_overload)
  2401.         {
  2402.             return mb_substr($str, $start, $length, '8bit');
  2403.         }
  2404.  
  2405.         return isset($length)
  2406.             ? substr($str, $start, $length)
  2407.             : substr($str, $start);
  2408.     }
  2409. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement