PageRenderTime 49ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/protected/extensions/mailer/phpmailer/class.phpmailer.php

https://bitbucket.org/RSol/fotobank
PHP | 2068 lines | 1389 code | 154 blank | 525 comment | 211 complexity | 649d9538bfa7906485cabf6cecb6750c MD5 | raw file
Possible License(s): MIT, LGPL-2.1, BSD-3-Clause, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*~ class.phpmailer.php
  3. .---------------------------------------------------------------------------.
  4. | Software: PHPMailer - PHP email class |
  5. | Version: 5.0.0 |
  6. | Contact: via sourceforge.net support pages (also www.codeworxtech.com) |
  7. | Info: http://phpmailer.sourceforge.net |
  8. | Support: http://sourceforge.net/projects/phpmailer/ |
  9. | ------------------------------------------------------------------------- |
  10. | Admin: Andy Prevost (project admininistrator) |
  11. | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
  12. | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
  13. | Founder: Brent R. Matzelle (original founder) |
  14. | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
  15. | Copyright (c) 2001-2003, Brent R. Matzelle |
  16. | ------------------------------------------------------------------------- |
  17. | License: Distributed under the Lesser General Public License (LGPL) |
  18. | http://www.gnu.org/copyleft/lesser.html |
  19. | This program is distributed in the hope that it will be useful - WITHOUT |
  20. | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
  21. | FITNESS FOR A PARTICULAR PURPOSE. |
  22. | ------------------------------------------------------------------------- |
  23. | We offer a number of paid services (www.codeworxtech.com): |
  24. | - Web Hosting on highly optimized fast and secure servers |
  25. | - Technology Consulting |
  26. | - Oursourcing (highly qualified programmers and graphic designers) |
  27. '---------------------------------------------------------------------------'
  28. */
  29. /**
  30. * PHPMailer - PHP email transport class
  31. * NOTE: Requires PHP version 5 or later
  32. * @package PHPMailer
  33. * @author Andy Prevost
  34. * @author Marcus Bointon
  35. * @copyright 2004 - 2009 Andy Prevost
  36. * @version $Id: class.phpmailer.php 254 2009-04-02 18:52:18Z codeworxtech $
  37. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  38. */
  39. if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
  40. class PHPMailer {
  41. /////////////////////////////////////////////////
  42. // PROPERTIES, PUBLIC
  43. /////////////////////////////////////////////////
  44. /**
  45. * Email priority (1 = High, 3 = Normal, 5 = low).
  46. * @var int
  47. */
  48. public $Priority = 3;
  49. /**
  50. * Sets the CharSet of the message.
  51. * @var string
  52. */
  53. public $CharSet = 'iso-8859-1';
  54. /**
  55. * Sets the Content-type of the message.
  56. * @var string
  57. */
  58. public $ContentType = 'text/plain';
  59. /**
  60. * Sets the Encoding of the message. Options for this are
  61. * "8bit", "7bit", "binary", "base64", and "quoted-printable".
  62. * @var string
  63. */
  64. public $Encoding = '8bit';
  65. /**
  66. * Holds the most recent mailer error message.
  67. * @var string
  68. */
  69. public $ErrorInfo = '';
  70. /**
  71. * Sets the From email address for the message.
  72. * @var string
  73. */
  74. public $From = 'root@localhost';
  75. /**
  76. * Sets the From name of the message.
  77. * @var string
  78. */
  79. public $FromName = 'Root User';
  80. /**
  81. * Sets the Sender email (Return-Path) of the message. If not empty,
  82. * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  83. * @var string
  84. */
  85. public $Sender = '';
  86. /**
  87. * Sets the Subject of the message.
  88. * @var string
  89. */
  90. public $Subject = '';
  91. /**
  92. * Sets the Body of the message. This can be either an HTML or text body.
  93. * If HTML then run IsHTML(true).
  94. * @var string
  95. */
  96. public $Body = '';
  97. /**
  98. * Sets the text-only body of the message. This automatically sets the
  99. * email to multipart/alternative. This body can be read by mail
  100. * clients that do not have HTML email capability such as mutt. Clients
  101. * that can read HTML will view the normal Body.
  102. * @var string
  103. */
  104. public $AltBody = '';
  105. /**
  106. * Sets word wrapping on the body of the message to a given number of
  107. * characters.
  108. * @var int
  109. */
  110. public $WordWrap = 0;
  111. /**
  112. * Method to send mail: ("mail", "sendmail", or "smtp").
  113. * @var string
  114. */
  115. public $Mailer = 'mail';
  116. /**
  117. * Sets the path of the sendmail program.
  118. * @var string
  119. */
  120. public $Sendmail = '/usr/sbin/sendmail';
  121. /**
  122. * Path to PHPMailer plugins. Useful if the SMTP class
  123. * is in a different directory than the PHP include path.
  124. * @var string
  125. */
  126. public $PluginDir = '';
  127. /**
  128. * Sets the email address that a reading confirmation will be sent.
  129. * @var string
  130. */
  131. public $ConfirmReadingTo = '';
  132. /**
  133. * Sets the hostname to use in Message-Id and Received headers
  134. * and as default HELO string. If empty, the value returned
  135. * by SERVER_NAME is used or 'localhost.localdomain'.
  136. * @var string
  137. */
  138. public $Hostname = '';
  139. /**
  140. * Sets the message ID to be used in the Message-Id header.
  141. * If empty, a unique id will be generated.
  142. * @var string
  143. */
  144. public $MessageID = '';
  145. /////////////////////////////////////////////////
  146. // PROPERTIES FOR SMTP
  147. /////////////////////////////////////////////////
  148. /**
  149. * Sets the SMTP hosts. All hosts must be separated by a
  150. * semicolon. You can also specify a different port
  151. * for each host by using this format: [hostname:port]
  152. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  153. * Hosts will be tried in order.
  154. * @var string
  155. */
  156. public $Host = 'localhost';
  157. /**
  158. * Sets the default SMTP server port.
  159. * @var int
  160. */
  161. public $Port = 25;
  162. /**
  163. * Sets the SMTP HELO of the message (Default is $Hostname).
  164. * @var string
  165. */
  166. public $Helo = '';
  167. /**
  168. * Sets connection prefix.
  169. * Options are "", "ssl" or "tls"
  170. * @var string
  171. */
  172. public $SMTPSecure = '';
  173. /**
  174. * Sets SMTP authentication. Utilizes the Username and Password variables.
  175. * @var bool
  176. */
  177. public $SMTPAuth = false;
  178. /**
  179. * Sets SMTP username.
  180. * @var string
  181. */
  182. public $Username = '';
  183. /**
  184. * Sets SMTP password.
  185. * @var string
  186. */
  187. public $Password = '';
  188. /**
  189. * Sets the SMTP server timeout in seconds.
  190. * This function will not work with the win32 version.
  191. * @var int
  192. */
  193. public $Timeout = 10;
  194. /**
  195. * Sets SMTP class debugging on or off.
  196. * @var bool
  197. */
  198. public $SMTPDebug = false;
  199. /**
  200. * Prevents the SMTP connection from being closed after each mail
  201. * sending. If this is set to true then to close the connection
  202. * requires an explicit call to SmtpClose().
  203. * @var bool
  204. */
  205. public $SMTPKeepAlive = false;
  206. /**
  207. * Provides the ability to have the TO field process individual
  208. * emails, instead of sending to entire TO addresses
  209. * @var bool
  210. */
  211. public $SingleTo = false;
  212. /**
  213. * Provides the ability to change the line ending
  214. * @var string
  215. */
  216. public $LE = "\n";
  217. /////////////////////////////////////////////////
  218. // PROPERTIES, PRIVATE AND PROTECTED
  219. /////////////////////////////////////////////////
  220. private $smtp = NULL;
  221. private $to = array();
  222. private $cc = array();
  223. private $bcc = array();
  224. private $ReplyTo = array();
  225. private $all_recipients = array();
  226. private $attachment = array();
  227. private $CustomHeader = array();
  228. private $message_type = '';
  229. private $boundary = array();
  230. protected $language = array();
  231. private $error_count = 0;
  232. private $sign_cert_file = "";
  233. private $sign_key_file = "";
  234. private $sign_key_pass = "";
  235. private $exceptions = false;
  236. /////////////////////////////////////////////////
  237. // CONSTANTS
  238. /////////////////////////////////////////////////
  239. const VERSION = '5.0.0';
  240. const STOP_MESSAGE = 0; // message only, continue processing
  241. const STOP_CONTINUE = 1; // message?, likely ok to continue processing
  242. const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
  243. /////////////////////////////////////////////////
  244. // METHODS, VARIABLES
  245. /////////////////////////////////////////////////
  246. /**
  247. * Constructor
  248. * @param boolean $exceptions Should we throw external exceptions?
  249. */
  250. public function __construct($exceptions = false) {
  251. $this->exceptions = ($exceptions == true);
  252. }
  253. /**
  254. * Sets message type to HTML.
  255. * @param bool $ishtml
  256. * @return void
  257. */
  258. public function IsHTML($ishtml = true) {
  259. if ($ishtml) {
  260. $this->ContentType = 'text/html';
  261. } else {
  262. $this->ContentType = 'text/plain';
  263. }
  264. }
  265. /**
  266. * Sets Mailer to send message using SMTP.
  267. * @return void
  268. */
  269. public function IsSMTP() {
  270. $this->Mailer = 'smtp';
  271. }
  272. /**
  273. * Sets Mailer to send message using PHP mail() function.
  274. * @return void
  275. */
  276. public function IsMail() {
  277. $this->Mailer = 'mail';
  278. }
  279. /**
  280. * Sets Mailer to send message using the $Sendmail program.
  281. * @return void
  282. */
  283. public function IsSendmail() {
  284. if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
  285. $this->Sendmail = '/var/qmail/bin/sendmail';
  286. }
  287. $this->Mailer = 'sendmail';
  288. }
  289. /**
  290. * Sets Mailer to send message using the qmail MTA.
  291. * @return void
  292. */
  293. public function IsQmail() {
  294. if (stristr(ini_get('sendmail_path'), 'qmail')) {
  295. $this->Sendmail = '/var/qmail/bin/sendmail';
  296. }
  297. $this->Mailer = 'sendmail';
  298. }
  299. /////////////////////////////////////////////////
  300. // METHODS, RECIPIENTS
  301. /////////////////////////////////////////////////
  302. /**
  303. * Adds a "To" address.
  304. * @param string $address
  305. * @param string $name
  306. * @return boolean true on success, false if address already used
  307. */
  308. public function AddAddress($address, $name = '') {
  309. return $this->AddAnAddress('to', $address, $name);
  310. }
  311. /**
  312. * Adds a "Cc" address.
  313. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  314. * @param string $address
  315. * @param string $name
  316. * @return boolean true on success, false if address already used
  317. */
  318. public function AddCC($address, $name = '') {
  319. return $this->AddAnAddress('cc', $address, $name);
  320. }
  321. /**
  322. * Adds a "Bcc" address.
  323. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  324. * @param string $address
  325. * @param string $name
  326. * @return boolean true on success, false if address already used
  327. */
  328. public function AddBCC($address, $name = '') {
  329. return $this->AddAnAddress('bcc', $address, $name);
  330. }
  331. /**
  332. * Adds a "Reply-to" address.
  333. * @param string $address
  334. * @param string $name
  335. * @return boolean
  336. */
  337. public function AddReplyTo($address, $name = '') {
  338. return $this->AddAnAddress('ReplyTo', $address, $name);
  339. }
  340. /**
  341. * Adds an address to one of the recipient arrays
  342. * Addresses that have been added already return false, but do not throw exceptions
  343. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  344. * @param string $address The email address to send to
  345. * @param string $name
  346. * @return boolean true on success, false if address already used or invalid in some way
  347. * @access private
  348. */
  349. private function AddAnAddress($kind, $address, $name = '') {
  350. if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) {
  351. echo 'Invalid recipient array: ' . kind;
  352. return false;
  353. }
  354. $address = trim($address);
  355. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  356. if (!self::ValidateAddress($address)) {
  357. $this->SetError($this->Lang('invalid_address').': '. $address);
  358. if ($this->exceptions) {
  359. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  360. }
  361. echo $this->Lang('invalid_address').': '.$address;
  362. return false;
  363. }
  364. if ($kind != 'ReplyTo') {
  365. if (!isset($this->all_recipients[strtolower($address)])) {
  366. array_push($this->$kind, array($address, $name));
  367. $this->all_recipients[strtolower($address)] = true;
  368. return true;
  369. }
  370. } else {
  371. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  372. $this->ReplyTo[strtolower($address)] = array($address, $name);
  373. return true;
  374. }
  375. }
  376. return false;
  377. }
  378. /**
  379. * Set the From and FromName properties
  380. * @param string $address
  381. * @param string $name
  382. * @return boolean
  383. */
  384. public function SetFrom($address, $name = '') {
  385. $address = trim($address);
  386. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  387. if (!self::ValidateAddress($address)) {
  388. $this->SetError($this->Lang('invalid_address').': '. $address);
  389. if ($this->exceptions) {
  390. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  391. }
  392. echo $this->Lang('invalid_address').': '.$address;
  393. return false;
  394. }
  395. $this->From = $address;
  396. $this->FromName = $name;
  397. return true;
  398. }
  399. /**
  400. * Check that a string looks roughly like an email address should
  401. * Static so it can be used without instantiation
  402. * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator
  403. * Conforms approximately to RFC2822
  404. * @link http://www.hexillion.com/samples/#Regex Original pattern found here
  405. * @param string $address The email address to check
  406. * @return boolean
  407. * @static
  408. * @access public
  409. */
  410. public static function ValidateAddress($address) {
  411. if (0 && function_exists('filter_var')) { //Introduced in PHP 5.2
  412. if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {
  413. return false;
  414. } else {
  415. return true;
  416. }
  417. } else {
  418. return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
  419. }
  420. }
  421. /////////////////////////////////////////////////
  422. // METHODS, MAIL SENDING
  423. /////////////////////////////////////////////////
  424. /**
  425. * Creates message and assigns Mailer. If the message is
  426. * not sent successfully then it returns false. Use the ErrorInfo
  427. * variable to view description of the error.
  428. * @return bool
  429. */
  430. public function Send() {
  431. try {
  432. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  433. throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
  434. }
  435. // Set whether the message is multipart/alternative
  436. if(!empty($this->AltBody)) {
  437. $this->ContentType = 'multipart/alternative';
  438. }
  439. $this->error_count = 0; // reset errors
  440. $this->SetMessageType();
  441. $header = $this->CreateHeader();
  442. $body = $this->CreateBody();
  443. if (empty($this->Body)) {
  444. throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
  445. }
  446. // Choose the mailer and send through it
  447. switch($this->Mailer) {
  448. case 'sendmail':
  449. return $this->SendmailSend($header, $body);
  450. case 'smtp':
  451. return $this->SmtpSend($header, $body);
  452. case 'mail':
  453. default:
  454. return $this->MailSend($header, $body);
  455. }
  456. } catch (phpmailerException $e) {
  457. $this->SetError($e->getMessage());
  458. if ($this->exceptions) {
  459. throw $e;
  460. }
  461. echo $e->getMessage()."\n";
  462. return false;
  463. }
  464. }
  465. /**
  466. * Sends mail using the $Sendmail program.
  467. * @param string $header The message headers
  468. * @param string $body The message body
  469. * @access protected
  470. * @return bool
  471. */
  472. protected function SendmailSend($header, $body) {
  473. if ($this->Sender != '') {
  474. $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  475. } else {
  476. $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
  477. }
  478. if(!@$mail = popen($sendmail, 'w')) {
  479. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  480. }
  481. fputs($mail, $header);
  482. fputs($mail, $body);
  483. $result = pclose($mail);
  484. if($result != 0) {
  485. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  486. }
  487. return true;
  488. }
  489. /**
  490. * Sends mail using the PHP mail() function.
  491. * @param string $header The message headers
  492. * @param string $body The message body
  493. * @access protected
  494. * @return bool
  495. */
  496. protected function MailSend($header, $body) {
  497. $toArr = array();
  498. foreach($this->to as $t) {
  499. $toArr[] = $this->AddrFormat($t);
  500. }
  501. $to = implode(', ', $toArr);
  502. $params = sprintf("-oi -f %s", $this->Sender);
  503. if ($this->Sender != '' && strlen(ini_get('safe_mode'))< 1) {
  504. $old_from = ini_get('sendmail_from');
  505. ini_set('sendmail_from', $this->Sender);
  506. if ($this->SingleTo === true && count($toArr) > 1) {
  507. foreach ($toArr as $key => $val) {
  508. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  509. }
  510. } else {
  511. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  512. }
  513. } else {
  514. if ($this->SingleTo === true && count($toArr) > 1) {
  515. foreach ($toArr as $key => $val) {
  516. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  517. }
  518. } else {
  519. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
  520. }
  521. }
  522. if (isset($old_from)) {
  523. ini_set('sendmail_from', $old_from);
  524. }
  525. if(!$rt) {
  526. throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
  527. }
  528. return true;
  529. }
  530. /**
  531. * Sends mail via SMTP using PhpSMTP
  532. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  533. * @param string $header The message headers
  534. * @param string $body The message body
  535. * @uses SMTP
  536. * @access protected
  537. * @return bool
  538. */
  539. protected function SmtpSend($header, $body) {
  540. require_once $this->PluginDir . 'class.smtp.php';
  541. $bad_rcpt = array();
  542. if(!$this->SmtpConnect()) {
  543. throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
  544. }
  545. $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
  546. if(!$this->smtp->Mail($smtp_from)) {
  547. throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
  548. }
  549. // Attempt to send attach all recipients
  550. foreach($this->to as $to) {
  551. if (!$this->smtp->Recipient($to[0])) {
  552. $bad_rcpt[] = $to[0];
  553. }
  554. }
  555. foreach($this->cc as $cc) {
  556. if (!$this->smtp->Recipient($cc[0])) {
  557. $bad_rcpt[] = $cc[0];
  558. }
  559. }
  560. foreach($this->bcc as $bcc) {
  561. if (!$this->smtp->Recipient($bcc[0])) {
  562. $bad_rcpt[] = $bcc[0];
  563. }
  564. }
  565. if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
  566. $badaddresses = implode(', ', $bad_rcpt);
  567. throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
  568. }
  569. if(!$this->smtp->Data($header . $body)) {
  570. throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
  571. }
  572. if($this->SMTPKeepAlive == true) {
  573. $this->smtp->Reset();
  574. }
  575. return true;
  576. }
  577. /**
  578. * Initiates a connection to an SMTP server.
  579. * Returns false if the operation failed.
  580. * @uses SMTP
  581. * @access public
  582. * @return bool
  583. */
  584. public function SmtpConnect() {
  585. if(is_null($this->smtp)) {
  586. $this->smtp = new SMTP();
  587. }
  588. $this->smtp->do_debug = $this->SMTPDebug;
  589. $hosts = explode(';', $this->Host);
  590. $index = 0;
  591. $connection = $this->smtp->Connected();
  592. // Retry while there is no connection
  593. try {
  594. while($index < count($hosts) && !$connection) {
  595. $hostinfo = array();
  596. if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
  597. $host = $hostinfo[1];
  598. $port = $hostinfo[2];
  599. } else {
  600. $host = $hosts[$index];
  601. $port = $this->Port;
  602. }
  603. $tls = ($this->SMTPSecure == 'tls');
  604. $ssl = ($this->SMTPSecure == 'ssl');
  605. if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
  606. $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
  607. $this->smtp->Hello($hello);
  608. if ($tls) {
  609. if (!$this->smtp->StartTLS()) {
  610. throw new phpmailerException($this->Lang('tls'));
  611. }
  612. //We must resend HELO after tls negotiation
  613. $this->smtp->Hello($hello);
  614. }
  615. $connection = true;
  616. if ($this->SMTPAuth) {
  617. if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
  618. throw new phpmailerException($this->Lang('authenticate'));
  619. }
  620. }
  621. }
  622. $index++;
  623. if (!$connection) {
  624. throw new phpmailerException($this->Lang('connect_host'));
  625. }
  626. }
  627. } catch (phpmailerException $e) {
  628. $this->smtp->Reset();
  629. throw $e;
  630. }
  631. return true;
  632. }
  633. /**
  634. * Closes the active SMTP session if one exists.
  635. * @return void
  636. */
  637. public function SmtpClose() {
  638. if(!is_null($this->smtp)) {
  639. if($this->smtp->Connected()) {
  640. $this->smtp->Quit();
  641. $this->smtp->Close();
  642. }
  643. }
  644. }
  645. /**
  646. * Sets the language for all class error messages.
  647. * Returns false if it cannot load the language file. The default language is English.
  648. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
  649. * @param string $lang_path Path to the language file directory
  650. * @access public
  651. */
  652. function SetLanguage($langcode = 'en', $lang_path = 'language/') {
  653. //Define full set of translatable strings
  654. $PHPMAILER_LANG = array(
  655. 'provide_address' => Yii::t('yiiext','You must provide at least one recipient email address.'),
  656. 'mailer_not_supported' => Yii::t('yiiext',' mailer is not supported.'),
  657. 'execute' => Yii::t('yiiext','Could not execute: '),
  658. 'instantiate' => Yii::t('yiiext','Could not instantiate mail function.'),
  659. 'authenticate' => Yii::t('yiiext','SMTP Error: Could not authenticate.'),
  660. 'from_failed' => Yii::t('yiiext','The following From address failed: '),
  661. 'recipients_failed' => Yii::t('yiiext','SMTP Error: The following recipients failed: '),
  662. 'data_not_accepted' => Yii::t('yiiext','SMTP Error: Data not accepted.'),
  663. 'connect_host' => Yii::t('yiiext','SMTP Error: Could not connect to SMTP host.'),
  664. 'file_access' => Yii::t('yiiext','Could not access file: '),
  665. 'file_open' => Yii::t('yiiext','File Error: Could not open file: '),
  666. 'encoding' => Yii::t('yiiext','Unknown encoding: '),
  667. 'signing' => Yii::t('yiiext','Signing Error: '),
  668. 'smtp_error' => Yii::t('yiiext','SMTP server error: '),
  669. 'empty_message' => Yii::t('yiiext','Message body empty'),
  670. 'invalid_address' => Yii::t('yiiext','Invalid address'),
  671. 'variable_set' => Yii::t('yiiext','Cannot set or reset variable: ')
  672. );
  673. //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
  674. $l = true;
  675. if ($langcode != 'en') { //There is no English translation file
  676. $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
  677. }
  678. $this->language = $PHPMAILER_LANG;
  679. return ($l == true); //Returns false if language not found
  680. }
  681. /**
  682. * Return the current array of language strings
  683. * @return array
  684. */
  685. public function GetTranslations() {
  686. return $this->language;
  687. }
  688. /////////////////////////////////////////////////
  689. // METHODS, MESSAGE CREATION
  690. /////////////////////////////////////////////////
  691. /**
  692. * Creates recipient headers.
  693. * @access public
  694. * @return string
  695. */
  696. public function AddrAppend($type, $addr) {
  697. $addr_str = $type . ': ';
  698. $addresses = array();
  699. foreach ($addr as $a) {
  700. $addresses[] = $this->AddrFormat($a);
  701. }
  702. $addr_str .= implode(', ', $addresses);
  703. $addr_str .= $this->LE;
  704. return $addr_str;
  705. }
  706. /**
  707. * Formats an address correctly.
  708. * @access public
  709. * @return string
  710. */
  711. public function AddrFormat($addr) {
  712. if (empty($addr[1])) {
  713. return $this->SecureHeader($addr[0]);
  714. } else {
  715. return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
  716. }
  717. }
  718. /**
  719. * Wraps message for use with mailers that do not
  720. * automatically perform wrapping and for quoted-printable.
  721. * Original written by philippe.
  722. * @param string $message The message to wrap
  723. * @param integer $length The line length to wrap to
  724. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  725. * @access public
  726. * @return string
  727. */
  728. public function WrapText($message, $length, $qp_mode = false) {
  729. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  730. // If utf-8 encoding is used, we will need to make sure we don't
  731. // split multibyte characters when we wrap
  732. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  733. $message = $this->FixEOL($message);
  734. if (substr($message, -1) == $this->LE) {
  735. $message = substr($message, 0, -1);
  736. }
  737. $line = explode($this->LE, $message);
  738. $message = '';
  739. for ($i=0 ;$i < count($line); $i++) {
  740. $line_part = explode(' ', $line[$i]);
  741. $buf = '';
  742. for ($e = 0; $e<count($line_part); $e++) {
  743. $word = $line_part[$e];
  744. if ($qp_mode and (strlen($word) > $length)) {
  745. $space_left = $length - strlen($buf) - 1;
  746. if ($e != 0) {
  747. if ($space_left > 20) {
  748. $len = $space_left;
  749. if ($is_utf8) {
  750. $len = $this->UTF8CharBoundary($word, $len);
  751. } elseif (substr($word, $len - 1, 1) == "=") {
  752. $len--;
  753. } elseif (substr($word, $len - 2, 1) == "=") {
  754. $len -= 2;
  755. }
  756. $part = substr($word, 0, $len);
  757. $word = substr($word, $len);
  758. $buf .= ' ' . $part;
  759. $message .= $buf . sprintf("=%s", $this->LE);
  760. } else {
  761. $message .= $buf . $soft_break;
  762. }
  763. $buf = '';
  764. }
  765. while (strlen($word) > 0) {
  766. $len = $length;
  767. if ($is_utf8) {
  768. $len = $this->UTF8CharBoundary($word, $len);
  769. } elseif (substr($word, $len - 1, 1) == "=") {
  770. $len--;
  771. } elseif (substr($word, $len - 2, 1) == "=") {
  772. $len -= 2;
  773. }
  774. $part = substr($word, 0, $len);
  775. $word = substr($word, $len);
  776. if (strlen($word) > 0) {
  777. $message .= $part . sprintf("=%s", $this->LE);
  778. } else {
  779. $buf = $part;
  780. }
  781. }
  782. } else {
  783. $buf_o = $buf;
  784. $buf .= ($e == 0) ? $word : (' ' . $word);
  785. if (strlen($buf) > $length and $buf_o != '') {
  786. $message .= $buf_o . $soft_break;
  787. $buf = $word;
  788. }
  789. }
  790. }
  791. $message .= $buf . $this->LE;
  792. }
  793. return $message;
  794. }
  795. /**
  796. * Finds last character boundary prior to maxLength in a utf-8
  797. * quoted (printable) encoded string.
  798. * Original written by Colin Brown.
  799. * @access public
  800. * @param string $encodedText utf-8 QP text
  801. * @param int $maxLength find last character boundary prior to this length
  802. * @return int
  803. */
  804. public function UTF8CharBoundary($encodedText, $maxLength) {
  805. $foundSplitPos = false;
  806. $lookBack = 3;
  807. while (!$foundSplitPos) {
  808. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  809. $encodedCharPos = strpos($lastChunk, "=");
  810. if ($encodedCharPos !== false) {
  811. // Found start of encoded character byte within $lookBack block.
  812. // Check the encoded byte value (the 2 chars after the '=')
  813. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  814. $dec = hexdec($hex);
  815. if ($dec < 128) { // Single byte character.
  816. // If the encoded char was found at pos 0, it will fit
  817. // otherwise reduce maxLength to start of the encoded char
  818. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  819. $maxLength - ($lookBack - $encodedCharPos);
  820. $foundSplitPos = true;
  821. } elseif ($dec >= 192) { // First byte of a multi byte character
  822. // Reduce maxLength to split at start of character
  823. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  824. $foundSplitPos = true;
  825. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  826. $lookBack += 3;
  827. }
  828. } else {
  829. // No encoded character found
  830. $foundSplitPos = true;
  831. }
  832. }
  833. return $maxLength;
  834. }
  835. /**
  836. * Set the body wrapping.
  837. * @access public
  838. * @return void
  839. */
  840. public function SetWordWrap() {
  841. if($this->WordWrap < 1) {
  842. return;
  843. }
  844. switch($this->message_type) {
  845. case 'alt':
  846. case 'alt_attachments':
  847. $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
  848. break;
  849. default:
  850. $this->Body = $this->WrapText($this->Body, $this->WordWrap);
  851. break;
  852. }
  853. }
  854. /**
  855. * Assembles message header.
  856. * @access public
  857. * @return string The assembled header
  858. */
  859. public function CreateHeader() {
  860. $result = '';
  861. // Set the boundaries
  862. $uniq_id = md5(uniqid(time()));
  863. $this->boundary[1] = 'b1_' . $uniq_id;
  864. $this->boundary[2] = 'b2_' . $uniq_id;
  865. $result .= $this->HeaderLine('Date', self::RFCDate());
  866. if($this->Sender == '') {
  867. $result .= $this->HeaderLine('Return-Path', trim($this->From));
  868. } else {
  869. $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
  870. }
  871. // To be created automatically by mail()
  872. if($this->Mailer != 'mail') {
  873. if(count($this->to) > 0) {
  874. $result .= $this->AddrAppend('To', $this->to);
  875. } elseif (count($this->cc) == 0) {
  876. $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
  877. }
  878. }
  879. $from = array();
  880. $from[0][0] = trim($this->From);
  881. $from[0][1] = $this->FromName;
  882. $result .= $this->AddrAppend('From', $from);
  883. // sendmail and mail() extract Cc from the header before sending
  884. if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->cc) > 0)) {
  885. $result .= $this->AddrAppend('Cc', $this->cc);
  886. }
  887. // sendmail and mail() extract Bcc from the header before sending
  888. if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
  889. $result .= $this->AddrAppend('Bcc', $this->bcc);
  890. }
  891. if(count($this->ReplyTo) > 0) {
  892. $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
  893. }
  894. // mail() sets the subject itself
  895. if($this->Mailer != 'mail') {
  896. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
  897. }
  898. if($this->MessageID != '') {
  899. $result .= $this->HeaderLine('Message-ID',$this->MessageID);
  900. } else {
  901. $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
  902. }
  903. $result .= $this->HeaderLine('X-Priority', $this->Priority);
  904. $result .= $this->HeaderLine('X-Mailer', 'PHPMailer ' . self::VERSION . ' (phpmailer.codeworxtech.com)');
  905. if($this->ConfirmReadingTo != '') {
  906. $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  907. }
  908. // Add custom headers
  909. for($index = 0; $index < count($this->CustomHeader); $index++) {
  910. $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
  911. }
  912. if (!$this->sign_key_file) {
  913. $result .= $this->HeaderLine('MIME-Version', '1.0');
  914. $result .= $this->GetMailMIME();
  915. }
  916. return $result;
  917. }
  918. /**
  919. * Returns the message MIME.
  920. * @access public
  921. * @return string
  922. */
  923. public function GetMailMIME() {
  924. $result = '';
  925. switch($this->message_type) {
  926. case 'plain':
  927. $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
  928. $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet);
  929. break;
  930. case 'attachments':
  931. case 'alt_attachments':
  932. if($this->InlineImageExists()){
  933. $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE);
  934. } else {
  935. $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
  936. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  937. }
  938. break;
  939. case 'alt':
  940. $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  941. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  942. break;
  943. }
  944. if($this->Mailer != 'mail') {
  945. $result .= $this->LE.$this->LE;
  946. }
  947. return $result;
  948. }
  949. /**
  950. * Assembles the message body. Returns an empty string on failure.
  951. * @access public
  952. * @return string The assembled message body
  953. */
  954. public function CreateBody() {
  955. $body = '';
  956. if ($this->sign_key_file) {
  957. $body .= $this->GetMailMIME();
  958. }
  959. $this->SetWordWrap();
  960. switch($this->message_type) {
  961. case 'alt':
  962. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  963. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  964. $body .= $this->LE.$this->LE;
  965. $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
  966. $body .= $this->EncodeString($this->Body, $this->Encoding);
  967. $body .= $this->LE.$this->LE;
  968. $body .= $this->EndBoundary($this->boundary[1]);
  969. break;
  970. case 'plain':
  971. $body .= $this->EncodeString($this->Body, $this->Encoding);
  972. break;
  973. case 'attachments':
  974. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  975. $body .= $this->EncodeString($this->Body, $this->Encoding);
  976. $body .= $this->LE;
  977. $body .= $this->AttachAll();
  978. break;
  979. case 'alt_attachments':
  980. $body .= sprintf("--%s%s", $this->boundary[1], $this->LE);
  981. $body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE);
  982. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body
  983. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  984. $body .= $this->LE.$this->LE;
  985. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body
  986. $body .= $this->EncodeString($this->Body, $this->Encoding);
  987. $body .= $this->LE.$this->LE;
  988. $body .= $this->EndBoundary($this->boundary[2]);
  989. $body .= $this->AttachAll();
  990. break;
  991. }
  992. if ($this->IsError()) {
  993. $body = '';
  994. } elseif ($this->sign_key_file) {
  995. try {
  996. $file = tempnam('', 'mail');
  997. file_put_contents($file, $body); //TODO check this worked
  998. $signed = tempnam("", "signed");
  999. if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
  1000. @unlink($file);
  1001. @unlink($signed);
  1002. $body = file_get_contents($signed);
  1003. } else {
  1004. @unlink($file);
  1005. @unlink($signed);
  1006. throw new phpmailerException($this->Lang("signing").openssl_error_string());
  1007. }
  1008. } catch (phpmailerException $e) {
  1009. $body = '';
  1010. if ($this->exceptions) {
  1011. throw $e;
  1012. }
  1013. }
  1014. }
  1015. return $body;
  1016. }
  1017. /**
  1018. * Returns the start of a message boundary.
  1019. * @access private
  1020. */
  1021. private function GetBoundary($boundary, $charSet, $contentType, $encoding) {
  1022. $result = '';
  1023. if($charSet == '') {
  1024. $charSet = $this->CharSet;
  1025. }
  1026. if($contentType == '') {
  1027. $contentType = $this->ContentType;
  1028. }
  1029. if($encoding == '') {
  1030. $encoding = $this->Encoding;
  1031. }
  1032. $result .= $this->TextLine('--' . $boundary);
  1033. $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet);
  1034. $result .= $this->LE;
  1035. $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
  1036. $result .= $this->LE;
  1037. return $result;
  1038. }
  1039. /**
  1040. * Returns the end of a message boundary.
  1041. * @access private
  1042. */
  1043. private function EndBoundary($boundary) {
  1044. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1045. }
  1046. /**
  1047. * Sets the message type.
  1048. * @access private
  1049. * @return void
  1050. */
  1051. private function SetMessageType() {
  1052. if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) {
  1053. $this->message_type = 'plain';
  1054. } else {
  1055. if(count($this->attachment) > 0) {
  1056. $this->message_type = 'attachments';
  1057. }
  1058. if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) {
  1059. $this->message_type = 'alt';
  1060. }
  1061. if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) {
  1062. $this->message_type = 'alt_attachments';
  1063. }
  1064. }
  1065. }
  1066. /**
  1067. * Returns a formatted header line.
  1068. * @access public
  1069. * @return string
  1070. */
  1071. public function HeaderLine($name, $value) {
  1072. return $name . ': ' . $value . $this->LE;
  1073. }
  1074. /**
  1075. * Returns a formatted mail line.
  1076. * @access public
  1077. * @return string
  1078. */
  1079. public function TextLine($value) {
  1080. return $value . $this->LE;
  1081. }
  1082. /////////////////////////////////////////////////
  1083. // CLASS METHODS, ATTACHMENTS
  1084. /////////////////////////////////////////////////
  1085. /**
  1086. * Adds an attachment from a path on the filesystem.
  1087. * Returns false if the file could not be found
  1088. * or accessed.
  1089. * @param string $path Path to the attachment.
  1090. * @param string $name Overrides the attachment name.
  1091. * @param string $encoding File encoding (see $Encoding).
  1092. * @param string $type File extension (MIME) type.
  1093. * @return bool
  1094. */
  1095. public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1096. try {
  1097. if ( !@is_file($path) ) {
  1098. throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
  1099. }
  1100. $filename = basename($path);
  1101. if ( $name == '' ) {
  1102. $name = $filename;
  1103. }
  1104. $this->attachment[] = array(
  1105. 0 => $path,
  1106. 1 => $filename,
  1107. 2 => $name,
  1108. 3 => $encoding,
  1109. 4 => $type,
  1110. 5 => false, // isStringAttachment
  1111. 6 => 'attachment',
  1112. 7 => 0
  1113. );
  1114. } catch (phpmailerException $e) {
  1115. $this->SetError($e->getMessage());
  1116. if ($this->exceptions) {
  1117. throw $e;
  1118. }
  1119. echo $e->getMessage()."\n";
  1120. if ( $e->getCode() == self::STOP_CRITICAL ) {
  1121. return false;
  1122. }
  1123. }
  1124. return true;
  1125. }
  1126. /**
  1127. * Return the current array of attachments
  1128. * @return array
  1129. */
  1130. public function GetAttachments() {
  1131. return $this->attachment;
  1132. }
  1133. /**
  1134. * Attaches all fs, string, and binary attachments to the message.
  1135. * Returns an empty string on failure.
  1136. * @access private
  1137. * @return string
  1138. */
  1139. private function AttachAll() {
  1140. // Return text of body
  1141. $mime = array();
  1142. $cidUniq = array();
  1143. $incl = array();
  1144. // Add all attachments
  1145. foreach ($this->attachment as $attachment) {
  1146. // Check for string attachment
  1147. $bString = $attachment[5];
  1148. if ($bString) {
  1149. $string = $attachment[0];
  1150. } else {
  1151. $path = $attachment[0];
  1152. }
  1153. if (in_array($attachment[0], $incl)) { continue; }
  1154. $filename = $attachment[1];
  1155. $name = $attachment[2];
  1156. $encoding = $attachment[3];
  1157. $type = $attachment[4];
  1158. $disposition = $attachment[6];
  1159. $cid = $attachment[7];
  1160. $incl[] = $attachment[0];
  1161. if ( isset($cidUniq[$cid]) ) { continue; }
  1162. $cidUniq[$cid] = true;
  1163. $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
  1164. $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
  1165. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  1166. if($disposition == 'inline') {
  1167. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  1168. }
  1169. $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  1170. // Encode as string attachment
  1171. if($bString) {
  1172. $mime[] = $this->EncodeString($string, $encoding);
  1173. if($this->IsError()) {
  1174. return '';
  1175. }
  1176. $mime[] = $this->LE.$this->LE;
  1177. } else {
  1178. $mime[] = $this->EncodeFile($path, $encoding);
  1179. if($this->IsError()) {
  1180. return '';
  1181. }
  1182. $mime[] = $this->LE.$this->LE;
  1183. }
  1184. }
  1185. $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
  1186. return join('', $mime);
  1187. }
  1188. /**
  1189. * Encodes attachment in requested format.
  1190. * Returns an empty string on failure.
  1191. * @param string $path The full path to the file
  1192. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1193. * @see EncodeFile()
  1194. * @access private
  1195. * @return string
  1196. */
  1197. private function EncodeFile($path, $encoding = 'base64') {
  1198. try {
  1199. if (!is_readable($path)) {
  1200. throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
  1201. }
  1202. if (function_exists('get_magic_quotes')) {
  1203. function get_magic_quotes() {
  1204. return false;
  1205. }
  1206. }
  1207. if (PHP_VERSION < 6) {
  1208. $magic_quotes = get_magic_quotes_runtime();
  1209. set_magic_quotes_runtime(0);
  1210. }
  1211. $file_buffer = file_get_contents($path);
  1212. $file_buffer = $this->EncodeString($file_buffer, $encoding);
  1213. if (PHP_VERSION < 6) { set_magic_quotes_runtime($magic_quotes); }
  1214. return $file_buffer;
  1215. } catch (Exception $e) {
  1216. $this->SetError($e->getMessage());
  1217. return '';
  1218. }
  1219. }
  1220. /**
  1221. * Encodes string to requested format.
  1222. * Returns an empty string on failure.
  1223. * @param string $str The text to encode
  1224. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1225. * @access public
  1226. * @return string
  1227. */
  1228. public function EncodeString ($str, $encoding = 'base64') {
  1229. $encoded = '';
  1230. switch(strtolower($encoding)) {
  1231. case 'base64':
  1232. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1233. break;
  1234. case '7bit':
  1235. case '8bit':
  1236. $encoded = $this->FixEOL($str);
  1237. //Make sure it ends with a line break
  1238. if (substr($encoded, -(strlen($this->LE))) != $this->LE)
  1239. $encoded .= $this->LE;
  1240. break;
  1241. case 'binary':
  1242. $encoded = $str;
  1243. break;
  1244. case 'quoted-printable':
  1245. $encoded = $this->EncodeQP($str);
  1246. break;
  1247. default:
  1248. $this->SetError($this->Lang('encoding') . $encoding);
  1249. break;
  1250. }
  1251. return $encoded;
  1252. }
  1253. /**
  1254. * Encode a header string to best (shortest) of Q, B, quoted or none.
  1255. * @access public
  1256. * @return string
  1257. */
  1258. public function EncodeHeader($str, $position = 'text') {
  1259. $x = 0;
  1260. switch (strtolower($position)) {
  1261. case 'phrase':
  1262. if (!preg_match('/[\200-\377]/', $str)) {
  1263. // Can't use addslashes as we don't know what value has magic_quotes_sybase
  1264. $encoded = addcslashes($str, "\0..\37\177\\\"");
  1265. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  1266. return ($encoded);
  1267. } else {
  1268. return ("\"$encoded\"");
  1269. }
  1270. }
  1271. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1272. break;
  1273. case 'comment':
  1274. $x = preg_match_all('/[()"]/', $str, $matches);
  1275. // Fall-through
  1276. case 'text':
  1277. default:
  1278. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1279. break;
  1280. }
  1281. if ($x == 0) {
  1282. return ($str);
  1283. }
  1284. $maxlen = 75 - 7 - strlen($this->CharSet);
  1285. // Try to select the encoding which should produce the shortest output
  1286. if (strlen($str)/3 < $x) {
  1287. $encoding = 'B';
  1288. if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
  1289. // Use a custom function which correctly encodes and wraps long
  1290. // multibyte strings without breaking lines within a character
  1291. $encoded = $this->Base64EncodeWrapMB($str);
  1292. } else {
  1293. $encoded = base64_encode($str);
  1294. $maxlen -= $maxlen % 4;
  1295. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1296. }
  1297. } else {
  1298. $encoding = 'Q';
  1299. $encoded = $this->EncodeQ($str, $position);
  1300. $encoded = $this->WrapText($encoded, $maxlen, true);
  1301. $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
  1302. }
  1303. $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
  1304. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1305. return $encoded;
  1306. }
  1307. /**
  1308. * Checks if a string contains multibyte characters.
  1309. * @access public
  1310. * @param string $str multi-byte text to wrap encode
  1311. * @return bool
  1312. */
  1313. public function HasMultiBytes($str) {
  1314. if (function_exists('mb_strlen')) {
  1315. return (strlen($str) > mb_strlen($str, $this->CharSet));
  1316. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1317. return false;
  1318. }
  1319. }
  1320. /**
  1321. * Correctly encodes and wraps long multibyte strings for mail headers
  1322. * without breaking lines within a character.
  1323. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
  1324. * @access public
  1325. * @param string $str multi-byte text to wrap encode
  1326. * @return string
  1327. */
  1328. public function Base64EncodeWrapMB($str) {
  1329. $start = "=?".$this->CharSet."?B?";
  1330. $end = "?=";
  1331. $encoded = "";
  1332. $mb_length = mb_strlen($str, $this->CharSet);
  1333. // Each line must have length <= 75, including $start and $end
  1334. $length = 75 - strlen($start) - strlen($end);
  1335. // Average multi-byte ratio
  1336. $ratio = $mb_length / strlen($str);
  1337. // Base64 has a 4:3 ratio
  1338. $offset = $avgLength = floor($length * $ratio * .75);
  1339. for ($i = 0; $i < $mb_length; $i += $offset) {
  1340. $lookBack = 0;
  1341. do {
  1342. $offset = $avgLength - $lookBack;
  1343. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1344. $chunk = base64_encode($chunk);
  1345. $lookBack++;
  1346. }
  1347. while (strlen($chunk) > $length);
  1348. $encoded .= $chunk . $this->LE;
  1349. }
  1350. // Chomp the last linefeed
  1351. $encoded = substr($encoded, 0, -strlen($this->LE));
  1352. return $encoded;
  1353. }
  1354. /**
  1355. * Encode string to quoted-printable.
  1356. * Only uses standard PHP, slow, but will always work
  1357. * @access public
  1358. * @param string $string the text to encode
  1359. * @param integer $line_max Number of chars allowed on a line before wrapping
  1360. * @return string
  1361. */
  1362. public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
  1363. $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
  1364. $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
  1365. $eol = "\r\n";
  1366. $escape = '=';
  1367. $output = '';
  1368. while( list(, $line) = each($lines) ) {
  1369. $linlen = strlen($line);
  1370. $newline = '';

Large files files are truncated, but you can click here to view the full file