PageRenderTime 57ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/system/libraries/Email.php

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