You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2466 lines
54 KiB

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