Skip to content
This repository
file 2259 lines (1891 sloc) 48.565 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 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 91 92 93 94 95 96 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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.2.4 or newer
*
* NOTICE OF LICENSE
*
* Licensed under the Open Software License version 3.0
*
* This source file is subject to the Open Software License (OSL 3.0) that is
* bundled with this package in the files license.txt / license.rst. It is
* also available through the world wide web at this URL:
* http://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to obtain it
* through the world wide web, please send an email to
* licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
* @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');

/**
* CodeIgniter Email Class
*
* Permits email to be sent using Mail, Sendmail, or SMTP.
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/email.html
*/
class CI_Email {

/**
* Used as the User-Agent and X-Mailer headers' value.
*
* @var string
*/
public $useragent = 'CodeIgniter';

/**
* Path to the Sendmail binary.
*
* @var string
*/
public $mailpath = '/usr/sbin/sendmail'; // Sendmail path

/**
* Which method to use for sending e-mails.
*
* @var string 'mail', 'sendmail' or 'smtp'
*/
public $protocol = 'mail'; // mail/sendmail/smtp

/**
* STMP Server host
*
* @var string
*/
public $smtp_host = '';

/**
* SMTP Username
*
* @var string
*/
public $smtp_user = '';

/**
* SMTP Password
*
* @var string
*/
public $smtp_pass = '';

/**
* SMTP Server port
*
* @var int
*/
public $smtp_port = 25;

/**
* SMTP connection timeout in seconds
*
* @var int
*/
public $smtp_timeout = 5;

/**
* SMTP persistent connection
*
* @var bool
*/
public $smtp_keepalive = FALSE;

/**
* SMTP Encryption
*
* @var string empty, 'tls' or 'ssl'
*/
public $smtp_crypto = '';

/**
* Whether to apply word-wrapping to the message body.
*
* @var bool
*/
public $wordwrap = TRUE;

/**
* Number of characters to wrap at.
*
* @see CI_Email::$wordwrap
* @var int
*/
public $wrapchars = 76;

/**
* Message format.
*
* @var string 'text' or 'html'
*/
public $mailtype = 'text';

/**
* Character set (default: utf-8)
*
* @var string
*/
public $charset = 'utf-8';

/**
* Multipart message
*
* @var string 'mixed' (in the body) or 'related' (separate)
*/
public $multipart = 'mixed'; // "mixed" (in the body) or "related" (separate)

/**
* Alternative message (for HTML messages only)
*
* @var string
*/
public $alt_message = '';

/**
* Whether to validate e-mail addresses.
*
* @var bool
*/
public $validate = FALSE;

/**
* X-Priority header value.
*
* @var int 1-5
*/
public $priority = 3; // Default priority (1 - 5)

/**
* Newline character sequence.
* Use "\r\n" to comply with RFC 822.
*
* @link http://www.ietf.org/rfc/rfc822.txt
* @var string "\r\n" or "\n"
*/
public $newline = "\n"; // Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822)

/**
* CRLF character sequence
*
* RFC 2045 specifies that for 'quoted-printable' encoding,
* "\r\n" must be used. However, it appears that some servers
* (even on the receiving end) don't handle it properly and
* switching to "\n", while improper, is the only solution
* that seems to work for all environments.
*
* @link http://www.ietf.org/rfc/rfc822.txt
* @var string
*/
public $crlf = "\n";

/**
* Whether to use Delivery Status Notification.
*
* @var bool
*/
public $dsn = FALSE;

/**
* Whether to send multipart alternatives.
* Yahoo! doesn't seem to like these.
*
* @var bool
*/
public $send_multipart = TRUE;

/**
* Whether to send messages to BCC recipients in batches.
*
* @var bool
*/
public $bcc_batch_mode = FALSE;

/**
* BCC Batch max number size.
*
* @see CI_Email::$bcc_batch_mode
* @var int
*/
public $bcc_batch_size = 200;

// --------------------------------------------------------------------

/**
* Whether PHP is running in safe mode. Initialized by the class constructor.
*
* @var bool
*/
protected $_safe_mode = FALSE;

/**
* Subject header
*
* @var string
*/
protected $_subject = '';

/**
* Message body
*
* @var string
*/
protected $_body = '';

/**
* Final message body to be sent.
*
* @var string
*/
protected $_finalbody = '';

/**
* multipart/alternative boundary
*
* @var string
*/
protected $_alt_boundary = '';

/**
* Attachment boundary
*
* @var string
*/
protected $_atc_boundary = '';

/**
* Final headers to send
*
* @var string
*/
protected $_header_str = '';

/**
* SMTP Connection socket placeholder
*
* @var resource
*/
protected $_smtp_connect = '';

/**
* Mail encoding
*
* @var string '8bit' or '7bit'
*/
protected $_encoding = '8bit';

/**
* Whether to perform SMTP authentication
*
* @var bool
*/
protected $_smtp_auth = FALSE;

/**
* Whether to send a Reply-To header
*
* @var bool
*/
protected $_replyto_flag = FALSE;

/**
* Debug messages
*
* @see CI_Email::print_debugger()
* @var string
*/
protected $_debug_msg = array();

/**
* Recipients
*
* @var string[]
*/
protected $_recipients = array();

/**
* CC Recipients
*
* @var string[]
*/
protected $_cc_array = array();

/**
* BCC Recipients
*
* @var string[]
*/
protected $_bcc_array = array();

/**
* Message headers
*
* @var string[]
*/
protected $_headers = array();

/**
* Attachment data
*
* @var array
*/
protected $_attachments = array();

/**
* Valid $protocol values
*
* @see CI_Email::$protocol
* @var string[]
*/
protected $_protocols = array('mail', 'sendmail', 'smtp');

/**
* Base charsets
*
* Character sets valid for 7-bit encoding,
* excluding language suffix.
*
* @var string[]
*/
protected $_base_charsets = array('us-ascii', 'iso-2022-');

/**
* Bit depths
*
* Valid mail encodings
*
* @see CI_Email::$_encoding
* @var string[]
*/
protected $_bit_depths = array('7bit', '8bit');

/**
* $priority translations
*
* Actual values to send with the X-Priority header
*
* @var string[]
*/
protected $_priorities = array(
1 => '1 (Highest)',
2 => '2 (High)',
3 => '3 (Normal)',
4 => '4 (Low)',
5 => '5 (Lowest)'
);

// --------------------------------------------------------------------

/**
* Constructor - Sets Email Preferences
*
* The constructor can be passed an array of config values
*
* @param array $config = array()
* @return void
*/
public function __construct($config = array())
{
$this->charset = config_item('charset');

if (count($config) > 0)
{
$this->initialize($config);
}
else
{
$this->_smtp_auth = ! ($this->smtp_user === '' && $this->smtp_pass === '');
}

$this->_safe_mode = ( ! is_php('5.4') && ini_get('safe_mode'));
$this->charset = strtoupper($this->charset);

log_message('debug', 'Email Class Initialized');
}

// --------------------------------------------------------------------

/**
* Destructor - Releases Resources
*
* @return void
*/
public function __destruct()
{
if (is_resource($this->_smtp_connect))
{
$this->_send_command('quit');
}
}

// --------------------------------------------------------------------

/**
* Initialize preferences
*
* @param array
* @return CI_Email
*/
public function initialize($config = array())
{
foreach ($config as $key => $val)
{
if (isset($this->$key))
{
$method = 'set_'.$key;

if (method_exists($this, $method))
{
$this->$method($val);
}
else
{
$this->$key = $val;
}
}
}
$this->clear();

$this->_smtp_auth = ! ($this->smtp_user === '' && $this->smtp_pass === '');

return $this;
}

// --------------------------------------------------------------------

/**
* Initialize the Email Data
*
* @param bool
* @return CI_Email
*/
public function clear($clear_attachments = FALSE)
{
$this->_subject = '';
$this->_body = '';
$this->_finalbody = '';
$this->_header_str = '';
$this->_replyto_flag = FALSE;
$this->_recipients = array();
$this->_cc_array = array();
$this->_bcc_array = array();
$this->_headers = array();
$this->_debug_msg = array();

$this->set_header('User-Agent', $this->useragent);
$this->set_header('Date', $this->_set_date());

if ($clear_attachments !== FALSE)
{
$this->_attachments = array();
}

return $this;
}

// --------------------------------------------------------------------

/**
* Set FROM
*
* @param string $from
* @param string $name
* @param string $return_path = NULL Return-Path
* @return CI_Email
*/
public function from($from, $name = '', $return_path = NULL)
{
if (preg_match('/\<(.*)\>/', $from, $match))
{
$from = $match[1];
}

if ($this->validate)
{
$this->validate_email($this->_str_to_array($from));
if ($return_path)
{
$this->validate_email($this->_str_to_array($return_path));
}
}

// prepare the display name
if ($name !== '')
{
// only use Q encoding if there are characters that would require it
if ( ! preg_match('/[\200-\377]/', $name))
{
// add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes
$name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"';
}
else
{
$name = $this->_prep_q_encoding($name);
}
}

$this->set_header('From', $name.' <'.$from.'>');

isset($return_path) OR $return_path = $from;
$this->set_header('Return-Path', '<'.$return_path.'>');

return $this;
}

// --------------------------------------------------------------------

/**
* Set Reply-to
*
* @param string
* @param string
* @return CI_Email
*/
public function reply_to($replyto, $name = '')
{
if (preg_match('/\<(.*)\>/', $replyto, $match))
{
$replyto = $match[1];
}

if ($this->validate)
{
$this->validate_email($this->_str_to_array($replyto));
}

if ($name === '')
{
$name = $replyto;
}

if (strpos($name, '"') !== 0)
{
$name = '"'.$name.'"';
}

$this->set_header('Reply-To', $name.' <'.$replyto.'>');
$this->_replyto_flag = TRUE;

return $this;
}

// --------------------------------------------------------------------

/**
* Set Recipients
*
* @param string
* @return CI_Email
*/
public function to($to)
{
$to = $this->_str_to_array($to);
$to = $this->clean_email($to);

if ($this->validate)
{
$this->validate_email($to);
}

if ($this->_get_protocol() !== 'mail')
{
$this->set_header('To', implode(', ', $to));
}

$this->_recipients = $to;

return $this;
}

// --------------------------------------------------------------------

/**
* Set CC
*
* @param string
* @return CI_Email
*/
public function cc($cc)
{
$cc = $this->clean_email($this->_str_to_array($cc));

if ($this->validate)
{
$this->validate_email($cc);
}

$this->set_header('Cc', implode(', ', $cc));

if ($this->_get_protocol() === 'smtp')
{
$this->_cc_array = $cc;
}

return $this;
}

// --------------------------------------------------------------------

/**
* Set BCC
*
* @param string
* @param string
* @return CI_Email
*/
public function bcc($bcc, $limit = '')
{
if ($limit !== '' && is_numeric($limit))
{
$this->bcc_batch_mode = TRUE;
$this->bcc_batch_size = $limit;
}

$bcc = $this->clean_email($this->_str_to_array($bcc));

if ($this->validate)
{
$this->validate_email($bcc);
}

if ($this->_get_protocol() === 'smtp' OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size))
{
$this->_bcc_array = $bcc;
}
else
{
$this->set_header('Bcc', implode(', ', $bcc));
}

return $this;
}

// --------------------------------------------------------------------

/**
* Set Email Subject
*
* @param string
* @return CI_Email
*/
public function subject($subject)
{
$subject = $this->_prep_q_encoding($subject);
$this->set_header('Subject', $subject);
return $this;
}

// --------------------------------------------------------------------

/**
* Set Body
*
* @param string
* @return CI_Email
*/
public function message($body)
{
$this->_body = rtrim(str_replace("\r", '', $body));

/* strip slashes only if magic quotes is ON
if we do it with magic quotes OFF, it strips real, user-inputted chars.

NOTE: In PHP 5.4 get_magic_quotes_gpc() will always return 0 and
it will probably not exist in future versions at all.
*/
if ( ! is_php('5.4') && get_magic_quotes_gpc())
{
$this->_body = stripslashes($this->_body);
}

return $this;
}

// --------------------------------------------------------------------

/**
* Assign file attachments
*
* @param string $file Can be local path, URL or buffered content
* @param string $disposition = 'attachment'
* @param string $newname = NULL
* @param string $mime = ''
* @return CI_Email
*/
public function attach($file, $disposition = '', $newname = NULL, $mime = '')
{
if ($mime === '')
{
if (strpos($file, '://') === FALSE && ! file_exists($file))
{
$this->_set_error_message('lang:email_attachment_missing', $file);
return FALSE;
}

if ( ! $fp = @fopen($file, 'rb'))
{
$this->_set_error_message('lang:email_attachment_unreadable', $file);
return FALSE;
}

$file_content = stream_get_contents($fp);
$mime = $this->_mime_types(pathinfo($file, PATHINFO_EXTENSION));
fclose($fp);
}
else
{
$file_content =& $file; // buffered file
}

$this->_attachments[] = array(
'name' => array($file, $newname),
'disposition' => empty($disposition) ? 'attachment' : $disposition, // Can also be 'inline' Not sure if it matters
'type' => $mime,
'content' => chunk_split(base64_encode($file_content))
);

return $this;
}

// --------------------------------------------------------------------

/**
* Set and return attachment Content-ID
*
* Useful for attached inline pictures
*
* @param string $filename
* @return string
*/
public function attachment_cid($filename)
{
if ($this->multipart !== 'related')
{
$this->multipart = 'related'; // Thunderbird need this for inline images
}

for ($i = 0, $c = count($this->_attachments); $i < $c; $i++)
{
if ($this->_attachments[$i]['name'][0] === $filename)
{
$this->_attachments[$i]['cid'] = uniqid(basename($this->_attachments[$i]['name'][0]).'@');
return $this->_attachments[$i]['cid'];
}
}

return FALSE;
}

// --------------------------------------------------------------------

/**
* Add a Header Item
*
* @param string
* @param string
* @return void
*/
public function set_header($header, $value)
{
$this->_headers[$header] = str_replace(array("\n", "\r"), '', $value);
}

// --------------------------------------------------------------------

/**
* Convert a String to an Array
*
* @param string
* @return array
*/
protected function _str_to_array($email)
{
if ( ! is_array($email))
{
return (strpos($email, ',') !== FALSE)
? preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY)
: (array) trim($email);
}

return $email;
}

// --------------------------------------------------------------------

/**
* Set Multipart Value
*
* @param string
* @return CI_Email
*/
public function set_alt_message($str)
{
$this->alt_message = (string) $str;
return $this;
}

// --------------------------------------------------------------------

/**
* Set Mailtype
*
* @param string
* @return CI_Email
*/
public function set_mailtype($type = 'text')
{
$this->mailtype = ($type === 'html') ? 'html' : 'text';
return $this;
}

// --------------------------------------------------------------------

/**
* Set Wordwrap
*
* @param bool
* @return CI_Email
*/
public function set_wordwrap($wordwrap = TRUE)
{
$this->wordwrap = (bool) $wordwrap;
return $this;
}

// --------------------------------------------------------------------

/**
* Set Protocol
*
* @param string
* @return CI_Email
*/
public function set_protocol($protocol = 'mail')
{
$this->protocol = in_array($protocol, $this->_protocols, TRUE) ? strtolower($protocol) : 'mail';
return $this;
}

// --------------------------------------------------------------------

/**
* Set Priority
*
* @param int
* @return CI_Email
*/
public function set_priority($n = 3)
{
$this->priority = preg_match('/^[1-5]$/', $n) ? (int) $n : 3;
return $this;
}

// --------------------------------------------------------------------

/**
* Set Newline Character
*
* @param string
* @return CI_Email
*/
public function set_newline($newline = "\n")
{
$this->newline = in_array($newline, array("\n", "\r\n", "\r")) ? $newline : "\n";
return $this;
}

// --------------------------------------------------------------------

/**
* Set CRLF
*
* @param string
* @return CI_Email
*/
public function set_crlf($crlf = "\n")
{
$this->crlf = ($crlf !== "\n" && $crlf !== "\r\n" && $crlf !== "\r") ? "\n" : $crlf;
return $this;
}

// --------------------------------------------------------------------

/**
* Set Message Boundary
*
* @return void
*/
protected function _set_boundaries()
{
$this->_alt_boundary = 'B_ALT_'.uniqid(''); // multipart/alternative
$this->_atc_boundary = 'B_ATC_'.uniqid(''); // attachment boundary
}

// --------------------------------------------------------------------

/**
* Get the Message ID
*
* @return string
*/
protected function _get_message_id()
{
$from = str_replace(array('>', '<'), '', $this->_headers['Return-Path']);
return '<'.uniqid('').strstr($from, '@').'>';
}

// --------------------------------------------------------------------

/**
* Get Mail Protocol
*
* @param bool
* @return mixed
*/
protected function _get_protocol($return = TRUE)
{
$this->protocol = strtolower($this->protocol);
in_array($this->protocol, $this->_protocols, TRUE) OR $this->protocol = 'mail';

if ($return === TRUE)
{
return $this->protocol;
}
}

// --------------------------------------------------------------------

/**
* Get Mail Encoding
*
* @param bool
* @return string
*/
protected function _get_encoding($return = TRUE)
{
in_array($this->_encoding, $this->_bit_depths) OR $this->_encoding = '8bit';

foreach ($this->_base_charsets as $charset)
{
if (strpos($charset, $this->charset) === 0)
{
$this->_encoding = '7bit';
}
}

if ($return === TRUE)
{
return $this->_encoding;
}
}

// --------------------------------------------------------------------

/**
* Get content type (text/html/attachment)
*
* @return string
*/
protected function _get_content_type()
{
if ($this->mailtype === 'html')
{
return (count($this->_attachments) === 0) ? 'html' : 'html-attach';
}
elseif ($this->mailtype === 'text' && count($this->_attachments) > 0)
{
return 'plain-attach';
}
else
{
return 'plain';
}
}

// --------------------------------------------------------------------

/**
* Set RFC 822 Date
*
* @return string
*/
protected function _set_date()
{
$timezone = date('Z');
$operator = ($timezone[0] === '-') ? '-' : '+';
$timezone = abs($timezone);
$timezone = floor($timezone/3600) * 100 + ($timezone % 3600) / 60;

return sprintf('%s %s%04d', date('D, j M Y H:i:s'), $operator, $timezone);
}

// --------------------------------------------------------------------

/**
* Mime message
*
* @return string
*/
protected function _get_mime_message()
{
return 'This is a multi-part message in MIME format.'.$this->newline.'Your email application may not support this format.';
}

// --------------------------------------------------------------------

/**
* Validate Email Address
*
* @param string
* @return bool
*/
public function validate_email($email)
{
if ( ! is_array($email))
{
$this->_set_error_message('lang:email_must_be_array');
return FALSE;
}

foreach ($email as $val)
{
if ( ! $this->valid_email($val))
{
$this->_set_error_message('lang:email_invalid_address', $val);
return FALSE;
}
}

return TRUE;
}

// --------------------------------------------------------------------

/**
* Email Validation
*
* @param string
* @return bool
*/
public function valid_email($email)
{
return (bool) filter_var($email, FILTER_VALIDATE_EMAIL);
}

// --------------------------------------------------------------------

/**
* Clean Extended Email Address: Joe Smith <joe@smith.com>
*
* @param string
* @return string
*/
public function clean_email($email)
{
if ( ! is_array($email))
{
return preg_match('/\<(.*)\>/', $email, $match) ? $match[1] : $email;
}

$clean_email = array();

foreach ($email as $addy)
{
$clean_email[] = preg_match('/\<(.*)\>/', $addy, $match) ? $match[1] : $addy;
}

return $clean_email;
}

// --------------------------------------------------------------------

/**
* Build alternative plain text message
*
* Provides the raw message for use in plain-text headers of
* HTML-formatted emails.
* If the user hasn't specified his own alternative message
* it creates one by stripping the HTML
*
* @return string
*/
protected function _get_alt_message()
{
if ( ! empty($this->alt_message))
{
return ($this->wordwrap)
? $this->word_wrap($this->alt_message, 76)
: $this->alt_message;
}

$body = preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->_body, $match) ? $match[1] : $this->_body;
$body = str_replace("\t", '', preg_replace('#<!--(.*)--\>#', '', trim(strip_tags($body))));

for ($i = 20; $i >= 3; $i--)
{
$body = str_replace(str_repeat("\n", $i), "\n\n", $body);
}

// Reduce multiple spaces
$body = preg_replace('| +|', ' ', $body);

return ($this->wordwrap)
? $this->word_wrap($body, 76)
: $body;
}

// --------------------------------------------------------------------

/**
* Word Wrap
*
* @param string
* @param int line-length limit
* @return string
*/
public function word_wrap($str, $charlim = NULL)
{
// Set the character limit, if not already present
if (empty($charlim))
{
$charlim = empty($this->wrapchars) ? 76 : $this->wrapchars;
}

// Standardize newlines
if (strpos($str, "\r") !== FALSE)
{
$str = str_replace(array("\r\n", "\r"), "\n", $str);
}

// Reduce multiple spaces at end of line
$str = preg_replace('| +\n|', "\n", $str);

// If the current word is surrounded by {unwrap} tags we'll
// strip the entire chunk and replace it with a marker.
$unwrap = array();
if (preg_match_all('|(\{unwrap\}.+?\{/unwrap\})|s', $str, $matches))
{
for ($i = 0, $c = count($matches[0]); $i < $c; $i++)
{
$unwrap[] = $matches[1][$i];
$str = str_replace($matches[1][$i], '{{unwrapped'.$i.'}}', $str);
}
}

// Use PHP's native public function to do the initial wordwrap.
// We set the cut flag to FALSE so that any individual words that are
// too long get left alone. In the next step we'll deal with them.
$str = wordwrap($str, $charlim, "\n", FALSE);

// Split the string into individual lines of text and cycle through them
$output = '';
foreach (explode("\n", $str) as $line)
{
// Is the line within the allowed character count?
// If so we'll join it to the output and continue
if (strlen($line) <= $charlim)
{
$output .= $line.$this->newline;
continue;
}

$temp = '';
do
{
// If the over-length word is a URL we won't wrap it
if (preg_match('!\[url.+\]|://|wwww.!', $line))
{
break;
}

// Trim the word down
$temp .= substr($line, 0, $charlim-1);
$line = substr($line, $charlim-1);
}
while (strlen($line) > $charlim);

// If $temp contains data it means we had to split up an over-length
// word into smaller chunks so we'll add it back to our current line
if ($temp !== '')
{
$output .= $temp.$this->newline;
}

$output .= $line.$this->newline;
}

// Put our markers back
if (count($unwrap) > 0)
{
foreach ($unwrap as $key => $val)
{
$output = str_replace('{{unwrapped'.$key.'}}', $val, $output);
}
}

return $output;
}

// --------------------------------------------------------------------

/**
* Build final headers
*
* @return string
*/
protected function _build_headers()
{
$this->set_header('X-Sender', $this->clean_email($this->_headers['From']));
$this->set_header('X-Mailer', $this->useragent);
$this->set_header('X-Priority', $this->_priorities[$this->priority]);
$this->set_header('Message-ID', $this->_get_message_id());
$this->set_header('Mime-Version', '1.0');
}

// --------------------------------------------------------------------

/**
* Write Headers as a string
*
* @return void
*/
protected function _write_headers()
{
if ($this->protocol === 'mail')
{
if (isset($this->_headers['Subject']))
{
$this->_subject = $this->_headers['Subject'];
unset($this->_headers['Subject']);
}
}

reset($this->_headers);
$this->_header_str = '';

foreach ($this->_headers as $key => $val)
{
$val = trim($val);

if ($val !== '')
{
$this->_header_str .= $key.': '.$val.$this->newline;
}
}

if ($this->_get_protocol() === 'mail')
{
$this->_header_str = rtrim($this->_header_str);
}
}

// --------------------------------------------------------------------

/**
* Build Final Body and attachments
*
* @return bool
*/
protected function _build_message()
{
if ($this->wordwrap === TRUE && $this->mailtype !== 'html')
{
$this->_body = $this->word_wrap($this->_body);
}

$this->_set_boundaries();
$this->_write_headers();

$hdr = ($this->_get_protocol() === 'mail') ? $this->newline : '';
$body = '';

switch ($this->_get_content_type())
{
case 'plain' :

$hdr .= 'Content-Type: text/plain; charset='.$this->charset.$this->newline
.'Content-Transfer-Encoding: '.$this->_get_encoding();

if ($this->_get_protocol() === 'mail')
{
$this->_header_str .= $hdr;
$this->_finalbody = $this->_body;
}
else
{
$this->_finalbody = $hdr.$this->newline.$this->newline.$this->_body;
}

return;

case 'html' :

if ($this->send_multipart === FALSE)
{
$hdr .= 'Content-Type: text/html; charset='.$this->charset.$this->newline
.'Content-Transfer-Encoding: quoted-printable';
}
else
{
$hdr .= 'Content-Type: multipart/alternative; boundary="'.$this->_alt_boundary.'"';

$body .= $this->_get_mime_message().$this->newline.$this->newline
.'--'.$this->_alt_boundary.$this->newline

.'Content-Type: text/plain; charset='.$this->charset.$this->newline
.'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline.$this->newline
.$this->_get_alt_message().$this->newline.$this->newline.'--'.$this->_alt_boundary.$this->newline

.'Content-Type: text/html; charset='.$this->charset.$this->newline
.'Content-Transfer-Encoding: quoted-printable'.$this->newline.$this->newline;
}

$this->_finalbody = $body.$this->_prep_quoted_printable($this->_body).$this->newline.$this->newline;

if ($this->_get_protocol() === 'mail')
{
$this->_header_str .= $hdr;
}
else
{
$this->_finalbody = $hdr.$this->newline.$this->newline.$this->_finalbody;
}

if ($this->send_multipart !== FALSE)
{
$this->_finalbody .= '--'.$this->_alt_boundary.'--';
}

return;

case 'plain-attach' :

$hdr .= 'Content-Type: multipart/'.$this->multipart.'; boundary="'.$this->_atc_boundary.'"';

if ($this->_get_protocol() === 'mail')
{
$this->_header_str .= $hdr;
}

$body .= $this->_get_mime_message().$this->newline
.$this->newline
.'--'.$this->_atc_boundary.$this->newline
.'Content-Type: text/plain; charset='.$this->charset.$this->newline
.'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline
.$this->newline
.$this->_body.$this->newline.$this->newline;

break;
case 'html-attach' :

$hdr .= 'Content-Type: multipart/'.$this->multipart.'; boundary="'.$this->_atc_boundary.'"';

if ($this->_get_protocol() === 'mail')
{
$this->_header_str .= $hdr;
}

$body .= $this->_get_mime_message().$this->newline.$this->newline
.'--'.$this->_atc_boundary.$this->newline

.'Content-Type: multipart/alternative; boundary="'.$this->_alt_boundary.'"'.$this->newline.$this->newline
.'--'.$this->_alt_boundary.$this->newline

.'Content-Type: text/plain; charset='.$this->charset.$this->newline
.'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline.$this->newline
.$this->_get_alt_message().$this->newline.$this->newline.'--'.$this->_alt_boundary.$this->newline

.'Content-Type: text/html; charset='.$this->charset.$this->newline
.'Content-Transfer-Encoding: quoted-printable'.$this->newline.$this->newline

.$this->_prep_quoted_printable($this->_body).$this->newline.$this->newline
.'--'.$this->_alt_boundary.'--'.$this->newline.$this->newline;

break;
}

$attachment = array();
for ($i = 0, $c = count($this->_attachments), $z = 0; $i < $c; $i++)
{
$filename = $this->_attachments[$i]['name'][0];
$basename = ($this->_attachments[$i]['name'][1] === NULL)
? basename($filename) : $this->_attachments[$i]['name'][1];

$attachment[$z++] = '--'.$this->_atc_boundary.$this->newline
.'Content-type: '.$this->_attachments[$i]['type'].'; '
.'name="'.$basename.'"'.$this->newline
.'Content-Disposition: '.$this->_attachments[$i]['disposition'].';'.$this->newline
.'Content-Transfer-Encoding: base64'.$this->newline
.(empty($this->_attachments[$i]['cid']) ? '' : 'Content-ID: <'.$this->_attachments[$i]['cid'].'>'.$this->newline);

$attachment[$z++] = $this->_attachments[$i]['content'];
}

$body .= implode($this->newline, $attachment).$this->newline.'--'.$this->_atc_boundary.'--';
$this->_finalbody = ($this->_get_protocol() === 'mail')
? $body
: $hdr.$this->newline.$this->newline.$body;

return TRUE;
}

// --------------------------------------------------------------------

/**
* Prep Quoted Printable
*
* Prepares string for Quoted-Printable Content-Transfer-Encoding
* Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt
*
* @param string
* @return string
*/
protected function _prep_quoted_printable($str)
{
// We are intentionally wrapping so mail servers will encode characters
// properly and MUAs will behave, so {unwrap} must go!
$str = str_replace(array('{unwrap}', '{/unwrap}'), '', $str);

// RFC 2045 specifies CRLF as "\r\n".
// However, many developers choose to override that and violate
// the RFC rules due to (apparently) a bug in MS Exchange,
// which only works with "\n".
if ($this->crlf === "\r\n")
{
if (is_php('5.3'))
{
return quoted_printable_encode($str);
}
elseif (function_exists('imap_8bit'))
{
return imap_8bit($str);
}
}

// Reduce multiple spaces & remove nulls
$str = preg_replace(array('| +|', '/\x00+/'), array(' ', ''), $str);

// Standardize newlines
if (strpos($str, "\r") !== FALSE)
{
$str = str_replace(array("\r\n", "\r"), "\n", $str);
}

$escape = '=';
$output = '';

foreach (explode("\n", $str) as $line)
{
$length = strlen($line);
$temp = '';

// Loop through each character in the line to add soft-wrap
// characters at the end of a line " =\r\n" and add the newly
// processed line(s) to the output (see comment on $crlf class property)
for ($i = 0; $i < $length; $i++)
{
// Grab the next character
$char = $line[$i];
$ascii = ord($char);

// Convert spaces and tabs but only if it's the end of the line
if ($i === ($length - 1) && ($ascii === 32 OR $ascii === 9))
{
$char = $escape.sprintf('%02s', dechex($ascii));
}
elseif ($ascii === 61) // encode = signs
{
$char = $escape.strtoupper(sprintf('%02s', dechex($ascii))); // =3D
}

// If we're at the character limit, add the line to the output,
// reset our temp variable, and keep on chuggin'
if ((strlen($temp) + strlen($char)) >= 76)
{
$output .= $temp.$escape.$this->crlf;
$temp = '';
}

// Add the character to our temporary line
$temp .= $char;
}

// Add our completed line to the output
$output .= $temp.$this->crlf;
}

// get rid of extra CRLF tacked onto the end
return substr($output, 0, strlen($this->crlf) * -1);
}

// --------------------------------------------------------------------

/**
* Prep Q Encoding
*
* Performs "Q Encoding" on a string for use in email headers.
* It's related but not identical to quoted-printable, so it has its
* own method.
*
* @param string
* @return string
*/
protected function _prep_q_encoding($str)
{
$str = str_replace(array("\r", "\n"), '', $str);

if ($this->charset === 'UTF-8')
{
if (MB_ENABLED === TRUE)
{
return mb_encode_mimeheader($str, $this->charset, 'Q', $this->crlf);
}
elseif (ICONV_ENABLED === TRUE)
{
$output = @iconv_mime_encode('', $str,
array(
'scheme' => 'Q',
'line-length' => 76,
'input-charset' => $this->charset,
'output-charset' => $this->charset,
'line-break-chars' => $this->crlf
)
);

// There are reports that iconv_mime_encode() might fail and return FALSE
if ($output !== FALSE)
{
// iconv_mime_encode() will always put a header field name.
// We've passed it an empty one, but it still prepends our
// encoded string with ': ', so we need to strip it.
return substr($output, 2);
}

$chars = iconv_strlen($str, 'UTF-8');
}
}

// We might already have this set for UTF-8
isset($chars) OR $chars = strlen($str);

$output = '=?'.$this->charset.'?Q?';
for ($i = 0, $length = strlen($output); $i < $chars; $i++)
{
$chr = ($this->charset === 'UTF-8' && ICONV_ENABLED === TRUE)
? '='.implode('=', str_split(strtoupper(bin2hex(iconv_substr($str, $i, 1, $this->charset))), 2))
: '='.strtoupper(bin2hex($str[$i]));

// RFC 2045 sets a limit of 76 characters per line.
// We'll append ?= to the end of each line though.
if ($length + ($l = strlen($chr)) > 74)
{
$output .= '?='.$this->crlf // EOL
.' =?'.$this->charset.'?Q?'.$chr; // New line
$length = 6 + strlen($this->charset) + $l; // Reset the length for the new line
}
else
{
$output .= $chr;
$length += $l;
}
}

// End the header
return $output.'?=';
}

// --------------------------------------------------------------------

/**
* Send Email
*
* @param bool $auto_clear = TRUE
* @return bool
*/
public function send($auto_clear = TRUE)
{
if ($this->_replyto_flag === FALSE)
{
$this->reply_to($this->_headers['From']);
}

if ( ! isset($this->_recipients) && ! isset($this->_headers['To'])
&& ! isset($this->_bcc_array) && ! isset($this->_headers['Bcc'])
&& ! isset($this->_headers['Cc']))
{
$this->_set_error_message('lang:email_no_recipients');
return FALSE;
}

$this->_build_headers();

if ($this->bcc_batch_mode && count($this->_bcc_array) > $this->bcc_batch_size)
{
$result = $this->batch_bcc_send();

if ($result && $auto_clear)
{
$this->clear();
}

return $result;
}

if ($this->_build_message() === FALSE)
{
return FALSE;
}

$result = $this->_spool_email();

if ($result && $auto_clear)
{
$this->clear();
}

return $result;
}

// --------------------------------------------------------------------

/**
* Batch Bcc Send. Sends groups of BCCs in batches
*
* @return void
*/
public function batch_bcc_send()
{
$float = $this->bcc_batch_size - 1;
$set = '';
$chunk = array();

for ($i = 0, $c = count($this->_bcc_array); $i < $c; $i++)
{
if (isset($this->_bcc_array[$i]))
{
$set .= ', '.$this->_bcc_array[$i];
}

if ($i === $float)
{
$chunk[] = substr($set, 1);
$float += $this->bcc_batch_size;
$set = '';
}

if ($i === $c-1)
{
$chunk[] = substr($set, 1);
}
}

for ($i = 0, $c = count($chunk); $i < $c; $i++)
{
unset($this->_headers['Bcc']);

$bcc = $this->clean_email($this->_str_to_array($chunk[$i]));

if ($this->protocol !== 'smtp')
{
$this->set_header('Bcc', implode(', ', $bcc));
}
else
{
$this->_bcc_array = $bcc;
}

if ($this->_build_message() === FALSE)
{
return FALSE;
}

$this->_spool_email();
}
}

// --------------------------------------------------------------------

/**
* Unwrap special elements
*
* @return void
*/
protected function _unwrap_specials()
{
$this->_finalbody = preg_replace_callback('/\{unwrap\}(.*?)\{\/unwrap\}/si', array($this, '_remove_nl_callback'), $this->_finalbody);
}

// --------------------------------------------------------------------

/**
* Strip line-breaks via callback
*
* @param string $matches
* @return string
*/
protected function _remove_nl_callback($matches)
{
if (strpos($matches[1], "\r") !== FALSE OR strpos($matches[1], "\n") !== FALSE)
{
$matches[1] = str_replace(array("\r\n", "\r", "\n"), '', $matches[1]);
}

return $matches[1];
}

// --------------------------------------------------------------------

/**
* Spool mail to the mail server
*
* @return bool
*/
protected function _spool_email()
{
$this->_unwrap_specials();

$method = '_send_with_'.$this->_get_protocol();
if ( ! $this->$method())
{
$this->_set_error_message('lang:email_send_failure_'.($this->_get_protocol() === 'mail' ? 'phpmail' : $this->_get_protocol()));
return FALSE;
}

$this->_set_error_message('lang:email_sent', $this->_get_protocol());
return TRUE;
}

// --------------------------------------------------------------------

/**
* Send using mail()
*
* @return bool
*/
protected function _send_with_mail()
{
if (is_array($this->_recipients))
{
$this->_recipients = implode(', ', $this->_recipients);
}

if ($this->_safe_mode === TRUE)
{
return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str);
}
else
{
// most documentation of sendmail using the "-f" flag lacks a space after it, however
// we've encountered servers that seem to require it to be in place.
return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, '-f '.$this->clean_email($this->_headers['Return-Path']));
}
}

// --------------------------------------------------------------------

/**
* Send using Sendmail
*
* @return bool
*/
protected function _send_with_sendmail()
{
// is popen() enabled?
if ( ! function_usable('popen')
OR FALSE === ($fp = @popen(
$this->mailpath.' -oi -f '.$this->clean_email($this->_headers['From'])
.' -t -r '.$this->clean_email($this->_headers['Return-Path'])
, 'w'))
) // server probably has popen disabled, so nothing we can do to get a verbose error.
{
return FALSE;
}

fputs($fp, $this->_header_str);
fputs($fp, $this->_finalbody);

$status = pclose($fp);

if ($status !== 0)
{
$this->_set_error_message('lang:email_exit_status', $status);
$this->_set_error_message('lang:email_no_socket');
return FALSE;
}

return TRUE;
}

// --------------------------------------------------------------------

/**
* Send using SMTP
*
* @return bool
*/
protected function _send_with_smtp()
{
if ($this->smtp_host === '')
{
$this->_set_error_message('lang:email_no_hostname');
return FALSE;
}

if ( ! $this->_smtp_connect() OR ! $this->_smtp_authenticate())
{
return FALSE;
}

$this->_send_command('from', $this->clean_email($this->_headers['From']));

foreach ($this->_recipients as $val)
{
$this->_send_command('to', $val);
}

if (count($this->_cc_array) > 0)
{
foreach ($this->_cc_array as $val)
{
if ($val !== '')
{
$this->_send_command('to', $val);
}
}
}

if (count($this->_bcc_array) > 0)
{
foreach ($this->_bcc_array as $val)
{
if ($val !== '')
{
$this->_send_command('to', $val);
}
}
}

$this->_send_command('data');

// perform dot transformation on any lines that begin with a dot
$this->_send_data($this->_header_str.preg_replace('/^\./m', '..$1', $this->_finalbody));

$this->_send_data('.');

$reply = $this->_get_smtp_data();

$this->_set_error_message($reply);

if (strpos($reply, '250') !== 0)
{
$this->_set_error_message('lang:email_smtp_error', $reply);
return FALSE;
}

if ($this->smtp_keepalive)
{
$this->_send_command('reset');
}
else
{
$this->_send_command('quit');
}

return TRUE;
}

// --------------------------------------------------------------------

/**
* SMTP Connect
*
* @return string
*/
protected function _smtp_connect()
{
if (is_resource($this->_smtp_connect))
{
return TRUE;
}

$ssl = ($this->smtp_crypto === 'ssl') ? 'ssl://' : '';

$this->_smtp_connect = fsockopen($ssl.$this->smtp_host,
$this->smtp_port,
$errno,
$errstr,
$this->smtp_timeout);

if ( ! is_resource($this->_smtp_connect))
{
$this->_set_error_message('lang:email_smtp_error', $errno.' '.$errstr);
return FALSE;
}

stream_set_timeout($this->_smtp_connect, $this->smtp_timeout);
$this->_set_error_message($this->_get_smtp_data());

if ($this->smtp_crypto === 'tls')
{
$this->_send_command('hello');
$this->_send_command('starttls');

$crypto = stream_socket_enable_crypto($this->_smtp_connect, TRUE, STREAM_CRYPTO_METHOD_TLS_CLIENT);

if ($crypto !== TRUE)
{
$this->_set_error_message('lang:email_smtp_error', $this->_get_smtp_data());
return FALSE;
}
}

return $this->_send_command('hello');
}

// --------------------------------------------------------------------

/**
* Send SMTP command
*
* @param string
* @param string
* @return string
*/
protected function _send_command($cmd, $data = '')
{
switch ($cmd)
{
case 'hello' :

if ($this->_smtp_auth OR $this->_get_encoding() === '8bit')
{
$this->_send_data('EHLO '.$this->_get_hostname());
}
else
{
$this->_send_data('HELO '.$this->_get_hostname());
}

$resp = 250;
break;
case 'starttls' :

$this->_send_data('STARTTLS');
$resp = 220;
break;
case 'from' :

$this->_send_data('MAIL FROM:<'.$data.'>');
$resp = 250;
break;
case 'to' :

if ($this->dsn)
{
$this->_send_data('RCPT TO:<'.$data.'> NOTIFY=SUCCESS,DELAY,FAILURE ORCPT=rfc822;'.$data);
}
else
{
$this->_send_data('RCPT TO:<'.$data.'>');
}

$resp = 250;
break;
case 'data' :

$this->_send_data('DATA');
$resp = 354;
break;
case 'reset':

$this->_send_data('RSET');
$resp = 250;
break;
case 'quit' :

$this->_send_data('QUIT');
$resp = 221;
break;
}

$reply = $this->_get_smtp_data();

$this->_debug_msg[] = '<pre>'.$cmd.': '.$reply.'</pre>';

if ((int) substr($reply, 0, 3) !== $resp)
{
$this->_set_error_message('lang:email_smtp_error', $reply);
return FALSE;
}

if ($cmd === 'quit')
{
fclose($this->_smtp_connect);
}

return TRUE;
}

// --------------------------------------------------------------------

/**
* SMTP Authenticate
*
* @return bool
*/
protected function _smtp_authenticate()
{
if ( ! $this->_smtp_auth)
{
return TRUE;
}

if ($this->smtp_user === '' && $this->smtp_pass === '')
{
$this->_set_error_message('lang:email_no_smtp_unpw');
return FALSE;
}

$this->_send_data('AUTH LOGIN');

$reply = $this->_get_smtp_data();

if (strpos($reply, '503') === 0) // Already authenticated
{
return TRUE;
}
elseif (strpos($reply, '334') !== 0)
{
$this->_set_error_message('lang:email_failed_smtp_login', $reply);
return FALSE;
}

$this->_send_data(base64_encode($this->smtp_user));

$reply = $this->_get_smtp_data();

if (strpos($reply, '334') !== 0)
{
$this->_set_error_message('lang:email_smtp_auth_un', $reply);
return FALSE;
}

$this->_send_data(base64_encode($this->smtp_pass));

$reply = $this->_get_smtp_data();

if (strpos($reply, '235') !== 0)
{
$this->_set_error_message('lang:email_smtp_auth_pw', $reply);
return FALSE;
}

return TRUE;
}

// --------------------------------------------------------------------

/**
* Send SMTP data
*
* @param string $data
* @return bool
*/
protected function _send_data($data)
{
$data .= $this->newline;
for ($written = 0, $length = strlen($data); $written < $length; $written += $result)
{
if (($result = fwrite($this->_smtp_connect, substr($data, $written))) === FALSE)
{
break;
}
}

if ($result === FALSE)
{
$this->_set_error_message('lang:email_smtp_data_failure', $data);
return FALSE;
}

return TRUE;
}

// --------------------------------------------------------------------

/**
* Get SMTP data
*
* @return string
*/
protected function _get_smtp_data()
{
$data = '';

while ($str = fgets($this->_smtp_connect, 512))
{
$data .= $str;

if ($str[3] === ' ')
{
break;
}
}

return $data;
}

// --------------------------------------------------------------------

/**
* Get Hostname
*
* @return string
*/
protected function _get_hostname()
{
return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost.localdomain';
}

// --------------------------------------------------------------------

/**
* Get Debug Message
*
* @param array $include List of raw data chunks to include in the output
* Valid options are: 'headers', 'subject', 'body'
* @return string
*/
public function print_debugger($include = array('headers', 'subject', 'body'))
{
$msg = '';

if (count($this->_debug_msg) > 0)
{
foreach ($this->_debug_msg as $val)
{
$msg .= $val;
}
}

// Determine which parts of our raw data needs to be printed
$raw_data = '';
is_array($include) OR $include = array($include);

if (in_array('headers', $include, TRUE))
{
$raw_data = htmlspecialchars($this->_header_str)."\n";
}

if (in_array('subject', $include, TRUE))
{
$raw_data .= htmlspecialchars($this->_subject)."\n";
}

if (in_array('body', $include, TRUE))
{
$raw_data .= htmlspecialchars($this->_finalbody);
}

return $msg.($raw_data === '' ? '' : '<pre>'.$raw_data.'</pre>');
}

// --------------------------------------------------------------------

/**
* Set Message
*
* @param string $msg
* @param string $val = ''
* @return void
*/
protected function _set_error_message($msg, $val = '')
{
$CI =& get_instance();
$CI->lang->load('email');

if (sscanf($msg, 'lang:%s', $line) !== 1 OR FALSE === ($line = $CI->lang->line($line)))
{
$this->_debug_msg[] = str_replace('%s', $val, $msg).'<br />';
}
else
{
$this->_debug_msg[] = str_replace('%s', $val, $line).'<br />';
}
}

// --------------------------------------------------------------------

/**
* Mime Types
*
* @param string
* @return string
*/
protected function _mime_types($ext = '')
{
static $mimes;

$ext = strtolower($ext);

if ( ! is_array($mimes))
{
$mimes =& get_mimes();
}

if (isset($mimes[$ext]))
{
return is_array($mimes[$ext])
? current($mimes[$ext])
: $mimes[$ext];
}

return 'application/x-unknown-content-type';
}

}

/* End of file Email.php */
/* Location: ./system/libraries/Email.php */
Something went wrong with that request. Please try again.