PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/common/libraries/plugin/phpmailer/class.phpmailer.php

https://bitbucket.org/renaatdemuynck/chamilo
PHP | 2145 lines | 1514 code | 172 blank | 459 comment | 188 complexity | e693dd800b39846867e03f2f7f3e64e6 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1, LGPL-3.0, GPL-3.0, MIT, GPL-2.0
  1. <?php
  2. /*~ class.phpmailer.php
  3. .---------------------------------------------------------------------------.
  4. | Software: PHPMailer - PHP email class |
  5. | Version: 2.3 |
  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. | Author: Andy Prevost (project admininistrator) |
  11. | Author: Brent R. Matzelle (original founder) |
  12. | Copyright (c) 2004-2007, Andy Prevost. All Rights Reserved. |
  13. | Copyright (c) 2001-2003, Brent R. Matzelle |
  14. | ------------------------------------------------------------------------- |
  15. | License: Distributed under the Lesser General Public License (LGPL) |
  16. | http://www.gnu.org/copyleft/lesser.html |
  17. | This program is distributed in the hope that it will be useful - WITHOUT |
  18. | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
  19. | FITNESS FOR A PARTICULAR PURPOSE. |
  20. | ------------------------------------------------------------------------- |
  21. | We offer a number of paid services (www.codeworxtech.com): |
  22. | - Web Hosting on highly optimized fast and secure servers |
  23. | - Technology Consulting |
  24. | - Oursourcing (highly qualified programmers and graphic designers) |
  25. '---------------------------------------------------------------------------'
  26. /**
  27. * PHPMailer - PHP email transport class
  28. * NOTE: Designed for use with PHP version 5 and up
  29. * @package PHPMailer
  30. * @author Andy Prevost
  31. * @copyright 2004 - 2008 Andy Prevost
  32. */
  33. class PHPMailer
  34. {
  35. /////////////////////////////////////////////////
  36. // PROPERTIES, PUBLIC
  37. /////////////////////////////////////////////////
  38. /**
  39. * Email priority (1 = High, 3 = Normal, 5 = low).
  40. * @var int
  41. */
  42. public $Priority = 3;
  43. /**
  44. * Sets the CharSet of the message.
  45. * @var string
  46. */
  47. public $CharSet = 'iso-8859-1';
  48. /**
  49. * Sets the Content-type of the message.
  50. * @var string
  51. */
  52. public $ContentType = 'text/plain';
  53. /**
  54. * Sets the Encoding of the message. Options for this are "8bit",
  55. * "7bit", "binary", "base64", and "quoted-printable".
  56. * @var string
  57. */
  58. public $Encoding = '8bit';
  59. /**
  60. * Holds the most recent mailer error message.
  61. * @var string
  62. */
  63. public $ErrorInfo = '';
  64. /**
  65. * Sets the From email address for the message.
  66. * @var string
  67. */
  68. public $From = 'root@localhost';
  69. /**
  70. * Sets the From name of the message.
  71. * @var string
  72. */
  73. public $FromName = 'Root User';
  74. /**
  75. * Sets the Sender email (Return-Path) of the message. If not empty,
  76. * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  77. * @var string
  78. */
  79. public $Sender = '';
  80. /**
  81. * Sets the Subject of the message.
  82. * @var string
  83. */
  84. public $Subject = '';
  85. /**
  86. * Sets the Body of the message. This can be either an HTML or text body.
  87. * If HTML then run IsHTML(true).
  88. * @var string
  89. */
  90. public $Body = '';
  91. /**
  92. * Sets the text-only body of the message. This automatically sets the
  93. * email to multipart/alternative. This body can be read by mail
  94. * clients that do not have HTML email capability such as mutt. Clients
  95. * that can read HTML will view the normal Body.
  96. * @var string
  97. */
  98. public $AltBody = '';
  99. /**
  100. * Sets word wrapping on the body of the message to a given number of
  101. * characters.
  102. * @var int
  103. */
  104. public $WordWrap = 0;
  105. /**
  106. * Method to send mail: ("mail", "sendmail", or "smtp").
  107. * @var string
  108. */
  109. public $Mailer = 'mail';
  110. /**
  111. * Sets the path of the sendmail program.
  112. * @var string
  113. */
  114. public $Sendmail = '/usr/sbin/sendmail';
  115. /**
  116. * Path to PHPMailer plugins. This is now only useful if the SMTP class
  117. * is in a different directory than the PHP include path.
  118. * @var string
  119. */
  120. public $PluginDir = '';
  121. /**
  122. * Holds PHPMailer version.
  123. * @var string
  124. */
  125. public $Version = "2.3";
  126. /**
  127. * Sets the email address that a reading confirmation will be sent.
  128. * @var string
  129. */
  130. public $ConfirmReadingTo = '';
  131. /**
  132. * Sets the hostname to use in Message-Id and Received headers
  133. * and as default HELO string. If empty, the value returned
  134. * by SERVER_NAME is used or 'localhost.localdomain'.
  135. * @var string
  136. */
  137. public $Hostname = '';
  138. /**
  139. * Sets the message ID to be used in the Message-Id header.
  140. * If empty, a unique id will be generated.
  141. * @var string
  142. */
  143. public $MessageID = '';
  144. /////////////////////////////////////////////////
  145. // PROPERTIES FOR SMTP
  146. /////////////////////////////////////////////////
  147. /**
  148. * Sets the SMTP hosts. All hosts must be separated by a
  149. * semicolon. You can also specify a different port
  150. * for each host by using this format: [hostname:port]
  151. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  152. * Hosts will be tried in order.
  153. * @var string
  154. */
  155. public $Host = 'localhost';
  156. /**
  157. * Sets the default SMTP server port.
  158. * @var int
  159. */
  160. public $Port = 25;
  161. /**
  162. * Sets the SMTP HELO of the message (Default is $Hostname).
  163. * @var string
  164. */
  165. public $Helo = '';
  166. /**
  167. * Sets connection prefix.
  168. * Options are "", "ssl" or "tls"
  169. * @var string
  170. */
  171. public $SMTPSecure = "";
  172. /**
  173. * Sets SMTP authentication. Utilizes the Username and Password variables.
  174. * @var bool
  175. */
  176. public $SMTPAuth = false;
  177. /**
  178. * Sets SMTP username.
  179. * @var string
  180. */
  181. public $Username = '';
  182. /**
  183. * Sets SMTP password.
  184. * @var string
  185. */
  186. public $Password = '';
  187. /**
  188. * Sets the SMTP server timeout in seconds. This function will not
  189. * work with the win32 version.
  190. * @var int
  191. */
  192. public $Timeout = 10;
  193. /**
  194. * Sets SMTP class debugging on or off.
  195. * @var bool
  196. */
  197. public $SMTPDebug = false;
  198. /**
  199. * Prevents the SMTP connection from being closed after each mail
  200. * sending. If this is set to true then to close the connection
  201. * requires an explicit call to SmtpClose().
  202. * @var bool
  203. */
  204. public $SMTPKeepAlive = false;
  205. /**
  206. * Provides the ability to have the TO field process individual
  207. * emails, instead of sending to entire TO addresses
  208. * @var bool
  209. */
  210. public $SingleTo = false;
  211. /**
  212. * Provides the ability to change the line ending
  213. * @var string
  214. */
  215. public $LE = "\r\n";
  216. /////////////////////////////////////////////////
  217. // PROPERTIES, PRIVATE
  218. /////////////////////////////////////////////////
  219. private $smtp = NULL;
  220. private $to = array();
  221. private $cc = array();
  222. private $bcc = array();
  223. private $ReplyTo = array();
  224. private $attachment = array();
  225. private $CustomHeader = array();
  226. private $message_type = '';
  227. private $boundary = array();
  228. private $language = array();
  229. private $error_count = 0;
  230. private $sign_cert_file = "";
  231. private $sign_key_file = "";
  232. private $sign_key_pass = "";
  233. /////////////////////////////////////////////////
  234. // METHODS, VARIABLES
  235. /////////////////////////////////////////////////
  236. /**
  237. * Sets message type to HTML.
  238. * @param bool $bool
  239. * @return void
  240. */
  241. public function IsHTML($bool)
  242. {
  243. if ($bool == true)
  244. {
  245. $this->ContentType = 'text/html';
  246. }
  247. else
  248. {
  249. $this->ContentType = 'text/plain';
  250. }
  251. }
  252. /**
  253. * Sets Mailer to send message using SMTP.
  254. * @return void
  255. */
  256. public function IsSMTP()
  257. {
  258. $this->Mailer = 'smtp';
  259. }
  260. /**
  261. * Sets Mailer to send message using PHP mail() function.
  262. * @return void
  263. */
  264. public function IsMail()
  265. {
  266. $this->Mailer = 'mail';
  267. }
  268. /**
  269. * Sets Mailer to send message using the $Sendmail program.
  270. * @return void
  271. */
  272. public function IsSendmail()
  273. {
  274. $this->Mailer = 'sendmail';
  275. }
  276. /**
  277. * Sets Mailer to send message using the qmail MTA.
  278. * @return void
  279. */
  280. public function IsQmail()
  281. {
  282. $this->Sendmail = '/var/qmail/bin/sendmail';
  283. $this->Mailer = 'sendmail';
  284. }
  285. /////////////////////////////////////////////////
  286. // METHODS, RECIPIENTS
  287. /////////////////////////////////////////////////
  288. /**
  289. * Adds a "To" address.
  290. * @param string $address
  291. * @param string $name
  292. * @return void
  293. */
  294. public function AddAddress($address, $name = '')
  295. {
  296. $cur = count($this->to);
  297. $this->to[$cur][0] = trim($address);
  298. $this->to[$cur][1] = $name;
  299. }
  300. /**
  301. * Adds a "Cc" address. Note: this function works
  302. * with the SMTP mailer on win32, not with the "mail"
  303. * mailer.
  304. * @param string $address
  305. * @param string $name
  306. * @return void
  307. */
  308. public function AddCC($address, $name = '')
  309. {
  310. $cur = count($this->cc);
  311. $this->cc[$cur][0] = trim($address);
  312. $this->cc[$cur][1] = $name;
  313. }
  314. /**
  315. * Adds a "Bcc" address. Note: this function works
  316. * with the SMTP mailer on win32, not with the "mail"
  317. * mailer.
  318. * @param string $address
  319. * @param string $name
  320. * @return void
  321. */
  322. public function AddBCC($address, $name = '')
  323. {
  324. $cur = count($this->bcc);
  325. $this->bcc[$cur][0] = trim($address);
  326. $this->bcc[$cur][1] = $name;
  327. }
  328. /**
  329. * Adds a "Reply-to" address.
  330. * @param string $address
  331. * @param string $name
  332. * @return void
  333. */
  334. public function AddReplyTo($address, $name = '')
  335. {
  336. $cur = count($this->ReplyTo);
  337. $this->ReplyTo[$cur][0] = trim($address);
  338. $this->ReplyTo[$cur][1] = $name;
  339. }
  340. /////////////////////////////////////////////////
  341. // METHODS, MAIL SENDING
  342. /////////////////////////////////////////////////
  343. /**
  344. * Creates message and assigns Mailer. If the message is
  345. * not sent successfully then it returns false. Use the ErrorInfo
  346. * variable to view description of the error.
  347. * @return bool
  348. */
  349. public function Send()
  350. {
  351. $header = '';
  352. $body = '';
  353. $result = true;
  354. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1)
  355. {
  356. $this->SetError($this->Lang('provide_address'));
  357. return false;
  358. }
  359. /* Set whether the message is multipart/alternative */
  360. if (! empty($this->AltBody))
  361. {
  362. $this->ContentType = 'multipart/alternative';
  363. }
  364. $this->error_count = 0; // reset errors
  365. $this->SetMessageType();
  366. $header .= $this->CreateHeader();
  367. $body = $this->CreateBody();
  368. if ($body == '')
  369. {
  370. return false;
  371. }
  372. /* Choose the mailer */
  373. switch ($this->Mailer)
  374. {
  375. case 'sendmail' :
  376. $result = $this->SendmailSend($header, $body);
  377. break;
  378. case 'smtp' :
  379. $result = $this->SmtpSend($header, $body);
  380. break;
  381. case 'mail' :
  382. $result = $this->MailSend($header, $body);
  383. break;
  384. default :
  385. $result = $this->MailSend($header, $body);
  386. break;
  387. //$this->SetError($this->Mailer . $this->Lang('mailer_not_supported'));
  388. //$result = false;
  389. //break;
  390. }
  391. return $result;
  392. }
  393. /**
  394. * Sends mail using the $Sendmail program.
  395. * @access public
  396. * @return bool
  397. */
  398. public function SendmailSend($header, $body)
  399. {
  400. if ($this->Sender != '')
  401. {
  402. $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  403. }
  404. else
  405. {
  406. $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
  407. }
  408. if (! @$mail = popen($sendmail, 'w'))
  409. {
  410. $this->SetError($this->Lang('execute') . $this->Sendmail);
  411. return false;
  412. }
  413. fputs($mail, $header);
  414. fputs($mail, $body);
  415. $result = pclose($mail);
  416. if (version_compare(phpversion(), '4.2.3') == - 1)
  417. {
  418. $result = $result >> 8 & 0xFF;
  419. }
  420. if ($result != 0)
  421. {
  422. $this->SetError($this->Lang('execute') . $this->Sendmail);
  423. return false;
  424. }
  425. return true;
  426. }
  427. /**
  428. * Sends mail using the PHP mail() function.
  429. * @access public
  430. * @return bool
  431. */
  432. public function MailSend($header, $body)
  433. {
  434. $to = '';
  435. for($i = 0; $i < count($this->to); $i ++)
  436. {
  437. if ($i != 0)
  438. {
  439. $to .= ', ';
  440. }
  441. $to .= $this->AddrFormat($this->to[$i]);
  442. }
  443. $toArr = split(',', $to);
  444. $params = sprintf("-oi -f %s", $this->Sender);
  445. if ($this->Sender != '' && strlen(ini_get('safe_mode')) < 1)
  446. {
  447. $old_from = ini_get('sendmail_from');
  448. ini_set('sendmail_from', $this->Sender);
  449. if ($this->SingleTo === true && count($toArr) > 1)
  450. {
  451. foreach ($toArr as $key => $val)
  452. {
  453. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  454. }
  455. }
  456. else
  457. {
  458. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  459. }
  460. }
  461. else
  462. {
  463. if ($this->SingleTo === true && count($toArr) > 1)
  464. {
  465. foreach ($toArr as $key => $val)
  466. {
  467. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  468. }
  469. }
  470. else
  471. {
  472. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
  473. }
  474. }
  475. if (isset($old_from))
  476. {
  477. ini_set('sendmail_from', $old_from);
  478. }
  479. if (! $rt)
  480. {
  481. $this->SetError($this->Lang('instantiate'));
  482. return false;
  483. }
  484. return true;
  485. }
  486. /**
  487. * Sends mail via SMTP using PhpSMTP (Author:
  488. * Chris Ryan). Returns bool. Returns false if there is a
  489. * bad MAIL FROM, RCPT, or DATA input.
  490. * @access public
  491. * @return bool
  492. */
  493. public function SmtpSend($header, $body)
  494. {
  495. include_once ($this->PluginDir . 'class.smtp.php');
  496. $error = '';
  497. $bad_rcpt = array();
  498. if (! $this->SmtpConnect())
  499. {
  500. return false;
  501. }
  502. $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
  503. if (! $this->smtp->Mail($smtp_from))
  504. {
  505. $error = $this->Lang('from_failed') . $smtp_from;
  506. $this->SetError($error);
  507. $this->smtp->Reset();
  508. return false;
  509. }
  510. /* Attempt to send attach all recipients */
  511. for($i = 0; $i < count($this->to); $i ++)
  512. {
  513. if (! $this->smtp->Recipient($this->to[$i][0]))
  514. {
  515. $bad_rcpt[] = $this->to[$i][0];
  516. }
  517. }
  518. for($i = 0; $i < count($this->cc); $i ++)
  519. {
  520. if (! $this->smtp->Recipient($this->cc[$i][0]))
  521. {
  522. $bad_rcpt[] = $this->cc[$i][0];
  523. }
  524. }
  525. for($i = 0; $i < count($this->bcc); $i ++)
  526. {
  527. if (! $this->smtp->Recipient($this->bcc[$i][0]))
  528. {
  529. $bad_rcpt[] = $this->bcc[$i][0];
  530. }
  531. }
  532. if (count($bad_rcpt) > 0)
  533. { // Create error message
  534. for($i = 0; $i < count($bad_rcpt); $i ++)
  535. {
  536. if ($i != 0)
  537. {
  538. $error .= ', ';
  539. }
  540. $error .= $bad_rcpt[$i];
  541. }
  542. $error = $this->Lang('recipients_failed') . $error;
  543. $this->SetError($error);
  544. $this->smtp->Reset();
  545. return false;
  546. }
  547. if (! $this->smtp->Data($header . $body))
  548. {
  549. $this->SetError($this->Lang('data_not_accepted'));
  550. $this->smtp->Reset();
  551. return false;
  552. }
  553. if ($this->SMTPKeepAlive == true)
  554. {
  555. $this->smtp->Reset();
  556. }
  557. else
  558. {
  559. $this->SmtpClose();
  560. }
  561. return true;
  562. }
  563. /**
  564. * Initiates a connection to an SMTP server. Returns false if the
  565. * operation failed.
  566. * @access public
  567. * @return bool
  568. */
  569. public function SmtpConnect()
  570. {
  571. if ($this->smtp == NULL)
  572. {
  573. $this->smtp = new SMTP();
  574. }
  575. $this->smtp->do_debug = $this->SMTPDebug;
  576. $hosts = explode(';', $this->Host);
  577. $index = 0;
  578. $connection = ($this->smtp->Connected());
  579. /* Retry while there is no connection */
  580. while ($index < count($hosts) && $connection == false)
  581. {
  582. $hostinfo = array();
  583. if (eregi('^(.+):([0-9]+)$', $hosts[$index], $hostinfo))
  584. {
  585. $host = $hostinfo[1];
  586. $port = $hostinfo[2];
  587. }
  588. else
  589. {
  590. $host = $hosts[$index];
  591. $port = $this->Port;
  592. }
  593. $tls = ($this->SMTPSecure == 'tls');
  594. $ssl = ($this->SMTPSecure == 'ssl');
  595. if ($this->smtp->Connect(($ssl ? 'ssl://' : '') . $host, $port, $this->Timeout))
  596. {
  597. $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
  598. $this->smtp->Hello($hello);
  599. if ($tls)
  600. {
  601. if (! $this->smtp->StartTLS())
  602. {
  603. $this->SetError($this->Lang("tls"));
  604. $this->smtp->Reset();
  605. $connection = false;
  606. }
  607. //We must resend HELLO after tls negociation
  608. $this->smtp->Hello($hello);
  609. }
  610. $connection = true;
  611. if ($this->SMTPAuth)
  612. {
  613. if (! $this->smtp->Authenticate($this->Username, $this->Password))
  614. {
  615. $this->SetError($this->Lang('authenticate'));
  616. $this->smtp->Reset();
  617. $connection = false;
  618. }
  619. }
  620. }
  621. $index ++;
  622. }
  623. if (! $connection)
  624. {
  625. $this->SetError($this->Lang('connect_host'));
  626. }
  627. return $connection;
  628. }
  629. /**
  630. * Closes the active SMTP session if one exists.
  631. * @return void
  632. */
  633. public function SmtpClose()
  634. {
  635. if ($this->smtp != NULL)
  636. {
  637. if ($this->smtp->Connected())
  638. {
  639. $this->smtp->Quit();
  640. $this->smtp->Close();
  641. }
  642. }
  643. }
  644. /**
  645. * Sets the language for all class error messages. Returns false
  646. * if it cannot load the language file. The default language type
  647. * is English.
  648. * @param string $lang_type Type of language (e.g. Portuguese: "br")
  649. * @param string $lang_path Path to the language file directory
  650. * @access public
  651. * @return bool
  652. */
  653. function SetLanguage($lang_type = 'en', $lang_path = 'language/')
  654. {
  655. if (! (@include $lang_path . 'phpmailer.lang-' . $lang_type . '.php'))
  656. {
  657. $PHPMAILER_LANG = array();
  658. $PHPMAILER_LANG["provide_address"] = 'You must provide at least one ' . $PHPMAILER_LANG["mailer_not_supported"] = ' mailer is not supported.';
  659. $PHPMAILER_LANG["execute"] = 'Could not execute: ';
  660. $PHPMAILER_LANG["instantiate"] = 'Could not instantiate mail function.';
  661. $PHPMAILER_LANG["authenticate"] = 'SMTP Error: Could not authenticate.';
  662. $PHPMAILER_LANG["from_failed"] = 'The following From address failed: ';
  663. $PHPMAILER_LANG["recipients_failed"] = 'SMTP Error: The following ' . $PHPMAILER_LANG["data_not_accepted"] = 'SMTP Error: Data not accepted.';
  664. $PHPMAILER_LANG["connect_host"] = 'SMTP Error: Could not connect to SMTP host.';
  665. $PHPMAILER_LANG["file_access"] = 'Could not access file: ';
  666. $PHPMAILER_LANG["file_open"] = 'File Error: Could not open file: ';
  667. $PHPMAILER_LANG["encoding"] = 'Unknown encoding: ';
  668. $PHPMAILER_LANG["signing"] = 'Signing Error: ';
  669. }
  670. $this->language = $PHPMAILER_LANG;
  671. return true;
  672. }
  673. /////////////////////////////////////////////////
  674. // METHODS, MESSAGE CREATION
  675. /////////////////////////////////////////////////
  676. /**
  677. * Creates recipient headers.
  678. * @access public
  679. * @return string
  680. */
  681. public function AddrAppend($type, $addr)
  682. {
  683. $addr_str = $type . ': ';
  684. $addr_str .= $this->AddrFormat($addr[0]);
  685. if (count($addr) > 1)
  686. {
  687. for($i = 1; $i < count($addr); $i ++)
  688. {
  689. $addr_str .= ', ' . $this->AddrFormat($addr[$i]);
  690. }
  691. }
  692. $addr_str .= $this->LE;
  693. return $addr_str;
  694. }
  695. /**
  696. * Formats an address correctly.
  697. * @access public
  698. * @return string
  699. */
  700. public function AddrFormat($addr)
  701. {
  702. if (empty($addr[1]))
  703. {
  704. $formatted = $this->SecureHeader($addr[0]);
  705. }
  706. else
  707. {
  708. $formatted = $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
  709. }
  710. return $formatted;
  711. }
  712. /**
  713. * Wraps message for use with mailers that do not
  714. * automatically perform wrapping and for quoted-printable.
  715. * Original written by philippe.
  716. * @access public
  717. * @return string
  718. */
  719. public function WrapText($message, $length, $qp_mode = false)
  720. {
  721. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  722. // If utf-8 encoding is used, we will need to make sure we don't
  723. // split multibyte characters when we wrap
  724. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  725. $message = $this->FixEOL($message);
  726. if (substr($message, - 1) == $this->LE)
  727. {
  728. $message = substr($message, 0, - 1);
  729. }
  730. $line = explode($this->LE, $message);
  731. $message = '';
  732. for($i = 0; $i < count($line); $i ++)
  733. {
  734. $line_part = explode(' ', $line[$i]);
  735. $buf = '';
  736. for($e = 0; $e < count($line_part); $e ++)
  737. {
  738. $word = $line_part[$e];
  739. if ($qp_mode and (strlen($word) > $length))
  740. {
  741. $space_left = $length - strlen($buf) - 1;
  742. if ($e != 0)
  743. {
  744. if ($space_left > 20)
  745. {
  746. $len = $space_left;
  747. if ($is_utf8)
  748. {
  749. $len = $this->UTF8CharBoundary($word, $len);
  750. }
  751. elseif (substr($word, $len - 1, 1) == "=")
  752. {
  753. $len --;
  754. }
  755. elseif (substr($word, $len - 2, 1) == "=")
  756. {
  757. $len -= 2;
  758. }
  759. $part = substr($word, 0, $len);
  760. $word = substr($word, $len);
  761. $buf .= ' ' . $part;
  762. $message .= $buf . sprintf("=%s", $this->LE);
  763. }
  764. else
  765. {
  766. $message .= $buf . $soft_break;
  767. }
  768. $buf = '';
  769. }
  770. while (strlen($word) > 0)
  771. {
  772. $len = $length;
  773. if ($is_utf8)
  774. {
  775. $len = $this->UTF8CharBoundary($word, $len);
  776. }
  777. elseif (substr($word, $len - 1, 1) == "=")
  778. {
  779. $len --;
  780. }
  781. elseif (substr($word, $len - 2, 1) == "=")
  782. {
  783. $len -= 2;
  784. }
  785. $part = substr($word, 0, $len);
  786. $word = substr($word, $len);
  787. if (strlen($word) > 0)
  788. {
  789. $message .= $part . sprintf("=%s", $this->LE);
  790. }
  791. else
  792. {
  793. $buf = $part;
  794. }
  795. }
  796. }
  797. else
  798. {
  799. $buf_o = $buf;
  800. $buf .= ($e == 0) ? $word : (' ' . $word);
  801. if (strlen($buf) > $length and $buf_o != '')
  802. {
  803. $message .= $buf_o . $soft_break;
  804. $buf = $word;
  805. }
  806. }
  807. }
  808. $message .= $buf . $this->LE;
  809. }
  810. return $message;
  811. }
  812. /**
  813. * Finds last character boundary prior to maxLength in a utf-8
  814. * quoted (printable) encoded string.
  815. * Original written by Colin Brown.
  816. * @access public
  817. * @param string $encodedText utf-8 QP text
  818. * @param int $maxLength find last character boundary prior to this length
  819. * @return int
  820. */
  821. public function UTF8CharBoundary($encodedText, $maxLength)
  822. {
  823. $foundSplitPos = false;
  824. $lookBack = 3;
  825. while (! $foundSplitPos)
  826. {
  827. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  828. $encodedCharPos = strpos($lastChunk, "=");
  829. if ($encodedCharPos !== false)
  830. {
  831. // Found start of encoded character byte within $lookBack block.
  832. // Check the encoded byte value (the 2 chars after the '=')
  833. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  834. $dec = hexdec($hex);
  835. if ($dec < 128)
  836. { // Single byte character.
  837. // If the encoded char was found at pos 0, it will fit
  838. // otherwise reduce maxLength to start of the encoded char
  839. $maxLength = ($encodedCharPos == 0) ? $maxLength : $maxLength - ($lookBack - $encodedCharPos);
  840. $foundSplitPos = true;
  841. }
  842. elseif ($dec >= 192)
  843. { // First byte of a multi byte character
  844. // Reduce maxLength to split at start of character
  845. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  846. $foundSplitPos = true;
  847. }
  848. elseif ($dec < 192)
  849. { // Middle byte of a multi byte character, look further back
  850. $lookBack += 3;
  851. }
  852. }
  853. else
  854. {
  855. // No encoded character found
  856. $foundSplitPos = true;
  857. }
  858. }
  859. return $maxLength;
  860. }
  861. /**
  862. * Set the body wrapping.
  863. * @access public
  864. * @return void
  865. */
  866. public function SetWordWrap()
  867. {
  868. if ($this->WordWrap < 1)
  869. {
  870. return;
  871. }
  872. switch ($this->message_type)
  873. {
  874. case 'alt' :
  875. /* fall through */
  876. case 'alt_attachments' :
  877. $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
  878. break;
  879. default :
  880. $this->Body = $this->WrapText($this->Body, $this->WordWrap);
  881. break;
  882. }
  883. }
  884. /**
  885. * Assembles message header.
  886. * @access public
  887. * @return string
  888. */
  889. public function CreateHeader()
  890. {
  891. $result = '';
  892. /* Set the boundaries */
  893. $uniq_id = md5(uniqid(time()));
  894. $this->boundary[1] = 'b1_' . $uniq_id;
  895. $this->boundary[2] = 'b2_' . $uniq_id;
  896. $result .= $this->HeaderLine('Date', $this->RFCDate());
  897. if ($this->Sender == '')
  898. {
  899. $result .= $this->HeaderLine('Return-Path', trim($this->From));
  900. }
  901. else
  902. {
  903. $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
  904. }
  905. /* To be created automatically by mail() */
  906. if ($this->Mailer != 'mail')
  907. {
  908. if (count($this->to) > 0)
  909. {
  910. $result .= $this->AddrAppend('To', $this->to);
  911. }
  912. elseif (count($this->cc) == 0)
  913. {
  914. $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
  915. }
  916. }
  917. $from = array();
  918. $from[0][0] = trim($this->From);
  919. $from[0][1] = $this->FromName;
  920. $result .= $this->AddrAppend('From', $from);
  921. /* sendmail and mail() extract Cc from the header before sending */
  922. if ((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->cc) > 0))
  923. {
  924. $result .= $this->AddrAppend('Cc', $this->cc);
  925. }
  926. /* sendmail and mail() extract Bcc from the header before sending */
  927. if ((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0))
  928. {
  929. $result .= $this->AddrAppend('Bcc', $this->bcc);
  930. }
  931. if (count($this->ReplyTo) > 0)
  932. {
  933. $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
  934. }
  935. /* mail() sets the subject itself */
  936. if ($this->Mailer != 'mail')
  937. {
  938. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
  939. }
  940. if ($this->MessageID != '')
  941. {
  942. $result .= $this->HeaderLine('Message-ID', $this->MessageID);
  943. }
  944. else
  945. {
  946. $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
  947. }
  948. $result .= $this->HeaderLine('X-Priority', $this->Priority);
  949. $result .= $this->HeaderLine('X-Mailer', 'PHPMailer (phpmailer.codeworxtech.com) [version ' . $this->Version . ']');
  950. if ($this->ConfirmReadingTo != '')
  951. {
  952. $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  953. }
  954. // Add custom headers
  955. for($index = 0; $index < count($this->CustomHeader); $index ++)
  956. {
  957. $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
  958. }
  959. if (! $this->sign_key_file)
  960. {
  961. $result .= $this->HeaderLine('MIME-Version', '1.0');
  962. $result .= $this->GetMailMIME();
  963. }
  964. return $result;
  965. }
  966. /**
  967. * Returns the message MIME.
  968. * @access public
  969. * @return string
  970. */
  971. public function GetMailMIME()
  972. {
  973. $result = '';
  974. switch ($this->message_type)
  975. {
  976. case 'plain' :
  977. $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
  978. $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet);
  979. break;
  980. case 'attachments' :
  981. /* fall through */
  982. case 'alt_attachments' :
  983. if ($this->InlineImageExists())
  984. {
  985. $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE);
  986. }
  987. else
  988. {
  989. $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
  990. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  991. }
  992. break;
  993. case 'alt' :
  994. $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  995. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  996. break;
  997. }
  998. if ($this->Mailer != 'mail')
  999. {
  1000. $result .= $this->LE . $this->LE;
  1001. }
  1002. return $result;
  1003. }
  1004. /**
  1005. * Assembles the message body. Returns an empty string on failure.
  1006. * @access public
  1007. * @return string
  1008. */
  1009. public function CreateBody()
  1010. {
  1011. $result = '';
  1012. if ($this->sign_key_file)
  1013. {
  1014. $result .= $this->GetMailMIME();
  1015. }
  1016. $this->SetWordWrap();
  1017. switch ($this->message_type)
  1018. {
  1019. case 'alt' :
  1020. $result .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1021. $result .= $this->EncodeString($this->AltBody, $this->Encoding);
  1022. $result .= $this->LE . $this->LE;
  1023. $result .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
  1024. $result .= $this->EncodeString($this->Body, $this->Encoding);
  1025. $result .= $this->LE . $this->LE;
  1026. $result .= $this->EndBoundary($this->boundary[1]);
  1027. break;
  1028. case 'plain' :
  1029. $result .= $this->EncodeString($this->Body, $this->Encoding);
  1030. break;
  1031. case 'attachments' :
  1032. $result .= $this->GetBoundary($this->boundary[1], '', '', '');
  1033. $result .= $this->EncodeString($this->Body, $this->Encoding);
  1034. $result .= $this->LE;
  1035. $result .= $this->AttachAll();
  1036. break;
  1037. case 'alt_attachments' :
  1038. $result .= sprintf("--%s%s", $this->boundary[1], $this->LE);
  1039. $result .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE . $this->LE);
  1040. $result .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body
  1041. $result .= $this->EncodeString($this->AltBody, $this->Encoding);
  1042. $result .= $this->LE . $this->LE;
  1043. $result .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body
  1044. $result .= $this->EncodeString($this->Body, $this->Encoding);
  1045. $result .= $this->LE . $this->LE;
  1046. $result .= $this->EndBoundary($this->boundary[2]);
  1047. $result .= $this->AttachAll();
  1048. break;
  1049. }
  1050. if ($this->IsError())
  1051. {
  1052. $result = '';
  1053. }
  1054. else
  1055. if ($this->sign_key_file)
  1056. {
  1057. $file = tempnam("", "mail");
  1058. $fp = fopen($file, "w");
  1059. fwrite($fp, $result);
  1060. fclose($fp);
  1061. $signed = tempnam("", "signed");
  1062. if (@openssl_pkcs7_sign($file, $signed, "file://" . $this->sign_cert_file, array(
  1063. "file://" . $this->sign_key_file, $this->sign_key_pass), null))
  1064. {
  1065. $fp = fopen($signed, "r");
  1066. $result = '';
  1067. while (! feof($fp))
  1068. {
  1069. $result = $result . fread($fp, 1024);
  1070. }
  1071. fclose($fp);
  1072. }
  1073. else
  1074. {
  1075. $this->SetError($this->Lang("signing") . openssl_error_string());
  1076. $result = '';
  1077. }
  1078. unlink($file);
  1079. unlink($signed);
  1080. }
  1081. return $result;
  1082. }
  1083. /**
  1084. * Returns the start of a message boundary.
  1085. * @access public
  1086. */
  1087. public function GetBoundary($boundary, $charSet, $contentType, $encoding)
  1088. {
  1089. $result = '';
  1090. if ($charSet == '')
  1091. {
  1092. $charSet = $this->CharSet;
  1093. }
  1094. if ($contentType == '')
  1095. {
  1096. $contentType = $this->ContentType;
  1097. }
  1098. if ($encoding == '')
  1099. {
  1100. $encoding = $this->Encoding;
  1101. }
  1102. $result .= $this->TextLine('--' . $boundary);
  1103. $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet);
  1104. $result .= $this->LE;
  1105. $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
  1106. $result .= $this->LE;
  1107. return $result;
  1108. }
  1109. /**
  1110. * Returns the end of a message boundary.
  1111. * @access public
  1112. */
  1113. public function EndBoundary($boundary)
  1114. {
  1115. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1116. }
  1117. /**
  1118. * Sets the message type.
  1119. * @access public
  1120. * @return void
  1121. */
  1122. public function SetMessageType()
  1123. {
  1124. if (count($this->attachment) < 1 && strlen($this->AltBody) < 1)
  1125. {
  1126. $this->message_type = 'plain';
  1127. }
  1128. else
  1129. {
  1130. if (count($this->attachment) > 0)
  1131. {
  1132. $this->message_type = 'attachments';
  1133. }
  1134. if (strlen($this->AltBody) > 0 && count($this->attachment) < 1)
  1135. {
  1136. $this->message_type = 'alt';
  1137. }
  1138. if (strlen($this->AltBody) > 0 && count($this->attachment) > 0)
  1139. {
  1140. $this->message_type = 'alt_attachments';
  1141. }
  1142. }
  1143. }
  1144. /* Returns a formatted header line.
  1145. * @access public
  1146. * @return string
  1147. */
  1148. public function HeaderLine($name, $value)
  1149. {
  1150. return $name . ': ' . $value . $this->LE;
  1151. }
  1152. /**
  1153. * Returns a formatted mail line.
  1154. * @access public
  1155. * @return string
  1156. */
  1157. public function TextLine($value)
  1158. {
  1159. return $value . $this->LE;
  1160. }
  1161. /////////////////////////////////////////////////
  1162. // CLASS METHODS, ATTACHMENTS
  1163. /////////////////////////////////////////////////
  1164. /**
  1165. * Adds an attachment from a path on the filesystem.
  1166. * Returns false if the file could not be found
  1167. * or accessed.
  1168. * @param string $path Path to the attachment.
  1169. * @param string $name Overrides the attachment name.
  1170. * @param string $encoding File encoding (see $Encoding).
  1171. * @param string $type File extension (MIME) type.
  1172. * @return bool
  1173. */
  1174. public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream')
  1175. {
  1176. if (! @is_file($path))
  1177. {
  1178. $this->SetError($this->Lang('file_access') . $path);
  1179. return false;
  1180. }
  1181. $filename = basename($path);
  1182. if ($name == '')
  1183. {
  1184. $name = $filename;
  1185. }
  1186. $cur = count($this->attachment);
  1187. $this->attachment[$cur][0] = $path;
  1188. $this->attachment[$cur][1] = $filename;
  1189. $this->attachment[$cur][2] = $name;
  1190. $this->attachment[$cur][3] = $encoding;
  1191. $this->attachment[$cur][4] = $type;
  1192. $this->attachment[$cur][5] = false; // isStringAttachment
  1193. $this->attachment[$cur][6] = 'attachment';
  1194. $this->attachment[$cur][7] = 0;
  1195. return true;
  1196. }
  1197. /**
  1198. * Attaches all fs, string, and binary attachments to the message.
  1199. * Returns an empty string on failure.
  1200. * @access public
  1201. * @return string
  1202. */
  1203. public function AttachAll()
  1204. {
  1205. /* Return text of body */
  1206. $mime = array();
  1207. /* Add all attachments */
  1208. for($i = 0; $i < count($this->attachment); $i ++)
  1209. {
  1210. /* Check for string attachment */
  1211. $bString = $this->attachment[$i][5];
  1212. if ($bString)
  1213. {
  1214. $string = $this->attachment[$i][0];
  1215. }
  1216. else
  1217. {
  1218. $path = $this->attachment[$i][0];
  1219. }
  1220. $filename = $this->attachment[$i][1];
  1221. $name = $this->attachment[$i][2];
  1222. $encoding = $this->attachment[$i][3];
  1223. $type = $this->attachment[$i][4];
  1224. $disposition = $this->attachment[$i][6];
  1225. $cid = $this->attachment[$i][7];
  1226. $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
  1227. //$mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $name, $this->LE);
  1228. $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
  1229. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  1230. if ($disposition == 'inline')
  1231. {
  1232. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  1233. }
  1234. //$mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $name, $this->LE.$this->LE);
  1235. $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE . $this->LE);
  1236. /* Encode as string attachment */
  1237. if ($bString)
  1238. {
  1239. $mime[] = $this->EncodeString($string, $encoding);
  1240. if ($this->IsError())
  1241. {
  1242. return '';
  1243. }
  1244. $mime[] = $this->LE . $this->LE;
  1245. }
  1246. else
  1247. {
  1248. $mime[] = $this->EncodeFile($path, $encoding);
  1249. if ($this->IsError())
  1250. {
  1251. return '';
  1252. }
  1253. $mime[] = $this->LE . $this->LE;
  1254. }
  1255. }
  1256. $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
  1257. return join('', $mime);
  1258. }
  1259. /**
  1260. * Encodes attachment in requested format. Returns an
  1261. * empty string on failure.
  1262. * @access public
  1263. * @return string
  1264. */
  1265. public function EncodeFile($path, $encoding = 'base64')
  1266. {
  1267. if (! @$fd = fopen($path, 'rb'))
  1268. {
  1269. $this->SetError($this->Lang('file_open') . $path);
  1270. return '';
  1271. }
  1272. if (function_exists('get_magic_quotes'))
  1273. {
  1274. function get_magic_quotes()
  1275. {
  1276. return false;
  1277. }
  1278. }
  1279. if (PHP_VERSION < 6)
  1280. {
  1281. $magic_quotes = get_magic_quotes_runtime();
  1282. set_magic_quotes_runtime(0);
  1283. }
  1284. $file_buffer = file_get_contents($path);
  1285. $file_buffer = $this->EncodeString($file_buffer, $encoding);
  1286. fclose($fd);
  1287. if (PHP_VERSION < 6)
  1288. {
  1289. set_magic_quotes_runtime($magic_quotes);
  1290. }
  1291. return $file_buffer;
  1292. }
  1293. /**
  1294. * Encodes string to requested format. Returns an
  1295. * empty string on failure.
  1296. * @access public
  1297. * @return string
  1298. */
  1299. public function EncodeString($str, $encoding = 'base64')
  1300. {
  1301. $encoded = '';
  1302. switch (strtolower($encoding))
  1303. {
  1304. case 'base64' :
  1305. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1306. break;
  1307. case '7bit' :
  1308. case '8bit' :
  1309. $encoded = $this->FixEOL($str);
  1310. if (substr($encoded, - (strlen($this->LE))) != $this->LE)
  1311. $encoded .= $this->LE;
  1312. break;
  1313. case 'binary' :
  1314. $encoded = $str;
  1315. break;
  1316. case 'quoted-printable' :
  1317. $encoded = $this->EncodeQP($str);
  1318. break;
  1319. default :
  1320. $this->SetError($this->Lang('encoding') . $encoding);
  1321. break;
  1322. }
  1323. return $encoded;
  1324. }
  1325. /**
  1326. * Encode a header string to best of Q, B, quoted or none.
  1327. * @access public
  1328. * @return string
  1329. */
  1330. public function EncodeHeader($str, $position = 'text')
  1331. {
  1332. $x = 0;
  1333. switch (strtolower($position))
  1334. {
  1335. case 'phrase' :
  1336. if (! preg_match('/[\200-\377]/', $str))
  1337. {
  1338. /* Can't use addslashes as we don't know what value has magic_quotes_sybase. */
  1339. $encoded = addcslashes($str, "\0..\37\177\\\"");
  1340. if (($str == $encoded) && ! preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str))
  1341. {
  1342. return ($encoded);
  1343. }
  1344. else
  1345. {
  1346. return ("\"$encoded\"");
  1347. }
  1348. }
  1349. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1350. break;
  1351. case 'comment' :
  1352. $x = preg_match_all('/[()"]/', $str, $matches);
  1353. /* Fall-through */
  1354. case 'text' :
  1355. default :
  1356. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1357. break;
  1358. }
  1359. if ($x == 0)
  1360. {
  1361. return ($str);
  1362. }
  1363. $maxlen = 75 - 7 - strlen($this->CharSet);
  1364. /* Try to select the encoding which should produce the shortest output */
  1365. if (strlen($str) / 3 < $x)
  1366. {
  1367. $encoding = 'B';
  1368. if (function_exists('mb_strlen') && $this->HasMultiBytes($str))
  1369. {
  1370. // Use a custom function which correctly encodes and wraps long
  1371. // multibyte strings without breaking lines within a character
  1372. $encoded = $this->Base64EncodeWrapMB($str);
  1373. }
  1374. else
  1375. {
  1376. $encoded = base64_encode($str);
  1377. $maxlen -= $maxlen % 4;
  1378. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1379. }
  1380. }
  1381. else
  1382. {
  1383. $encoding = 'Q';
  1384. $encoded = $this->EncodeQ($str, $position);
  1385. $encoded = $this->WrapText($encoded, $maxlen, true);
  1386. $encoded = str_replace('=' . $this->LE, "\n", trim($encoded));
  1387. }
  1388. $encoded = preg_replace('/^(.*)$/m', " =?" . $this->CharSet . "?$encoding?\\1?=", $encoded);
  1389. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1390. return $encoded;
  1391. }
  1392. /**
  1393. * Checks if a string contains multibyte characters.
  1394. * @access public
  1395. * @param string $str multi-byte text to wrap encode
  1396. * @return bool
  1397. */
  1398. public function HasMultiBytes($str)
  1399. {
  1400. if (function_exists('mb_strlen'))
  1401. {
  1402. return (strlen($str) > mb_strlen($str, $this->CharSet));
  1403. }
  1404. else
  1405. { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1406. return False;
  1407. }
  1408. }
  1409. /**
  1410. * Correctly encodes and wraps long multibyte strings for mail headers
  1411. * without breaking lines within a character.
  1412. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
  1413. * @access public
  1414. * @param string $str multi-byte text to wrap encode
  1415. * @return string
  1416. */
  1417. public function Base64EncodeWrapMB($str)
  1418. {
  1419. $start = "=?" . $this->CharSet . "?B?";
  1420. $end = "?=";
  1421. $encoded = "";
  1422. $mb_length = mb_strlen($str, $this->CharSet);
  1423. // Each line must have length <= 75, including $start and $end
  1424. $length = 75 - strlen($start) - strlen($end);
  1425. // Average multi-byte ratio
  1426. $ratio = $mb_length / strlen($str);
  1427. // Base64 has a 4:3 ratio
  1428. $offset = $avgLength = floor($length * $ratio * .75);
  1429. for($i = 0; $i < $mb_length; $i += $offset)
  1430. {
  1431. $lookBack = 0;
  1432. do
  1433. {
  1434. $offset = $avgLength - $lookBack;
  1435. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1436. $chunk = base64_encode($chunk);
  1437. $lookBack ++;
  1438. }
  1439. while (strlen($chunk) > $length);
  1440. $encoded .= $chunk . $this->LE;
  1441. }
  1442. // Chomp the last linefeed
  1443. $encoded = substr($encoded, 0, - strlen($this->LE));
  1444. return $encoded;
  1445. }
  1446. /**
  1447. * Encode string to quoted-printable.
  1448. * @access public
  1449. * @param string $string the text to encode
  1450. * @param integer $line_max Number of chars allowed on a line before wrapping
  1451. * @return string
  1452. */
  1453. public function EncodeQP($input = '', $line_max = 76, $space_conv = false)
  1454. {
  1455. $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
  1456. $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
  1457. $eol = "\r\n";
  1458. $escape = '=';
  1459. $output = '';
  1460. while (list(, $line) = each($lines))
  1461. {
  1462. $linlen = strlen($line);
  1463. $newline = '';
  1464. for($i = 0; $i < $linlen; $i ++)
  1465. {
  1466. $c = substr($line, $i, 1);
  1467. $dec = ord($c);
  1468. if (($i == 0) && ($dec == 46))
  1469. { // convert first point in the line into =2E
  1470. $c = '=2E';
  1471. }
  1472. if ($dec == 32)
  1473. {
  1474. if ($i == ($linlen - 1))
  1475. { // convert space at eol only
  1476. $c = '=20';
  1477. }
  1478. else
  1479. if ($space_conv)
  1480. {
  1481. $c = '=20';
  1482. }
  1483. }
  1484. elseif (($dec == 61) || ($dec < 32) || ($dec > 126))
  1485. { // always encode "\t", which is *not* required
  1486. $h2 = floor($dec / 16);
  1487. $h1 = floor($dec % 16);
  1488. $c = $escape . $hex[$h2] . $hex[$h1];
  1489. }
  1490. if ((strlen($newline) + strlen($c)) >= $line_max)
  1491. { // CRLF is not counted
  1492. $output .= $newline . $escape . $eol; // soft line break; " =\r\n" is okay
  1493. $newline = '';
  1494. // check if newline first character will be point or not
  1495. if ($dec == 46)
  1496. {
  1497. $c = '=2E';
  1498. }
  1499. }
  1500. $newline .= $c;
  1501. } // end of for
  1502. $output .= $newline . $eol;
  1503. } // end of while
  1504. return $output;
  1505. }
  1506. /**
  1507. * Encode string to q encoding.
  1508. * @access public
  1509. * @return string
  1510. */
  1511. public function EncodeQ($str, $position = 'text')
  1512. {
  1513. /* There should not be any EOL in the string */
  1514. $encoded = preg_replace("[\r\n]", '', $str);
  1515. switch (strtolower($position))
  1516. {
  1517. case 'phrase' :
  1518. $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1519. break;
  1520. case 'comment' :
  1521. $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1522. case 'text' :
  1523. default:
  1524. /* Replace every high ascii, control =, ? and _ characters */
  1525. $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e', "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1526. break;
  1527. }
  1528. /* Replace every spaces to _ (more readable than =20) */
  1529. $encoded = str_replace(' ', '_', $encoded);
  1530. return $encoded;
  1531. }
  1532. /**
  1533. * Adds a string or binary attachment (non-filesystem) to the list.
  1534. * This method can be used to attach ascii or binary data,
  1535. * such as a BLOB record from a database.
  1536. * @param string $string String attachment data.
  1537. * @param string $filename Name of the attachment.
  1538. * @param string $encoding File encoding (see $Encoding).
  1539. * @param string $type File extension (MIME) type.
  1540. * @return void
  1541. */
  1542. public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream')
  1543. {
  1544. /* Append to $attachment array */
  1545. $cur = count($this->attachment);
  1546. $this->attachment[$cur][0] = $string;
  1547. $this->attachment[$cur][1] = $filename;
  1548. $this->attachment[$cur][2] = $filename;
  1549. $this->attachment[$cur][3] = $encoding;
  1550. $this->attachment[$cur][4] = $type;
  1551. $this->attachment[$cur][5] = true; // isString
  1552. $this->attachment[$cur][6] = 'attachment';
  1553. $this->attachment[$cur][7] = 0;
  1554. }
  1555. /**
  1556. * Adds an embedded attachment. This can include images, sounds, and
  1557. * just about any other document. Make sure to set the $type to an
  1558. * image type. For JPEG images use "image/jpeg" and for GIF images
  1559. * use "image/gif".
  1560. * @param string $path Path to the attachment.
  1561. * @param string $cid Content ID of the attachment. Use this to identify
  1562. * the Id for accessing the image in an HTML form.
  1563. * @param string $name Overrides the attachment name.
  1564. * @param string $encoding File encoding (see $Encoding).
  1565. * @param string $type File extension (MIME) type.
  1566. * @return bool
  1567. */
  1568. public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream')
  1569. {
  1570. if (! @is_file($path))
  1571. {
  1572. $this->SetError($this->Lang('file_access') . $path);
  1573. return false;
  1574. }
  1575. $filename = basename($path);
  1576. if ($name == '')
  1577. {
  1578. $name = $filename;
  1579. }
  1580. /* Append to $attachment array */
  1581. $cur = count($this->attachment);
  1582. $this->attachment[$cur][0] = $path;
  1583. $this->attachment[$cur][1] = $filename;
  1584. $this->attachment[$cur][2] = $name;
  1585. $this->attachment[$cur][3] = $encoding;
  1586. $this->attachment[$cur][4] = $type;
  1587. $this->attachment[$cur][5] = false;
  1588. $this->attachment[$cur][6] = 'inline';
  1589. $this->attachment[$cur][7] = $cid;
  1590. return true;
  1591. }
  1592. /**
  1593. * Returns true if an inline attachment is present.
  1594. * @access public
  1595. * @return bool
  1596. */
  1597. public function InlineImageExists()
  1598. {
  1599. $result = false;
  1600. for($i = 0; $i < count($this->attachment); $i ++)
  1601. {
  1602. if ($this->attachment[$i][6] == 'inline')
  1603. {
  1604. $result = true;
  1605. break;
  1606. }
  1607. }
  1608. return $result;
  1609. }
  1610. /////////////////////////////////////////////////
  1611. // CLASS METHODS, MESSAGE RESET
  1612. /////////////////////////////////////////////////
  1613. /**
  1614. * Clears all recipients assigned in the TO array. Returns void.
  1615. * @return void
  1616. */
  1617. public function ClearAddresses()
  1618. {
  1619. $this->to = array();
  1620. }
  1621. /**
  1622. * Clears all recipients assigned in the CC array. Returns void.
  1623. * @return void
  1624. */
  1625. public function ClearCCs()
  1626. {
  1627. $this->cc = array();
  1628. }
  1629. /**
  1630. * Clears all recipients assigned in the BCC array. Returns void.
  1631. * @return void
  1632. */
  1633. public function ClearBCCs()
  1634. {
  1635. $this->bcc = array();
  1636. }
  1637. /**
  1638. * Clears all recipients assigned in the ReplyTo array. Returns void.
  1639. * @return void
  1640. */
  1641. public function ClearReplyTos()
  1642. {
  1643. $this->ReplyTo = array();
  1644. }
  1645. /**
  1646. * Clears all recipients assigned in the TO, CC and BCC
  1647. * array. Returns void.
  1648. * @return void
  1649. */
  1650. public function ClearAllRecipients()
  1651. {
  1652. $this->to = array();
  1653. $this->cc = array();
  1654. $this->bcc = array();
  1655. }
  1656. /**
  1657. * Clears all previously set filesystem, string, and binary
  1658. * attachments. Returns void.
  1659. * @return void
  1660. */
  1661. public function ClearAttachments()
  1662. {
  1663. $this->attachment = array();
  1664. }
  1665. /**
  1666. * Clears all custom headers. Returns void.
  1667. * @return void
  1668. */
  1669. public function ClearCustomHeaders()
  1670. {
  1671. $this->CustomHeader = array();
  1672. }
  1673. /////////////////////////////////////////////////
  1674. // CLASS METHODS, MISCELLANEOUS
  1675. /////////////////////////////////////////////////
  1676. /**
  1677. * Adds the error message to the error container.
  1678. * Returns void.
  1679. * @access private
  1680. * @return void
  1681. */
  1682. private function SetError($msg)
  1683. {
  1684. $this->error_count ++;
  1685. $this->ErrorInfo = $msg;
  1686. }
  1687. /**
  1688. * Returns the proper RFC 822 formatted date.
  1689. * @access private
  1690. * @return string
  1691. */
  1692. private static function RFCDate()
  1693. {
  1694. $tz = date('Z');
  1695. $tzs = ($tz < 0) ? '-' : '+';
  1696. $tz = abs($tz);
  1697. $tz = (int) ($tz / 3600) * 100 + ($tz % 3600) / 60;
  1698. $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
  1699. return $result;
  1700. }
  1701. /**
  1702. * Returns the server hostname or 'localhost.localdomain' if unknown.
  1703. * @access private
  1704. * @return string
  1705. */
  1706. private function ServerHostname()
  1707. {
  1708. if (! empty($this->Hostname))
  1709. {
  1710. $result = $this->Hostname;
  1711. }
  1712. elseif (isset($_SERVER['SERVER_NAME']))
  1713. {
  1714. $result = $_SERVER['SERVER_NAME'];
  1715. }
  1716. else
  1717. {
  1718. $result = "localhost.localdomain";
  1719. }
  1720. return $result;
  1721. }
  1722. /**
  1723. * Returns a message in the appropriate language.
  1724. * @access private
  1725. * @return string
  1726. */
  1727. private function Lang($key)
  1728. {
  1729. if (count($this->language) < 1)
  1730. {
  1731. $this->SetLanguage('en'); // set the default language
  1732. }
  1733. if (isset($this->language[$key]))
  1734. {
  1735. return $this->language[$key];
  1736. }
  1737. else
  1738. {
  1739. return 'Language string failed to load: ' . $key;
  1740. }
  1741. }
  1742. /**
  1743. * Returns true if an error occurred.
  1744. * @access public
  1745. * @return bool
  1746. */
  1747. public function IsError()
  1748. {
  1749. return ($this->error_count > 0);
  1750. }
  1751. /**
  1752. * Changes every end of line from CR or LF to CRLF.
  1753. * @access private
  1754. * @return string
  1755. */
  1756. private function FixEOL($str)
  1757. {
  1758. $str = str_replace("\r\n", "\n", $str);
  1759. $str = str_replace("\r", "\n", $str);
  1760. $str = str_replace("\n", $this->LE, $str);
  1761. return $str;
  1762. }
  1763. /**
  1764. * Adds a custom header.
  1765. * @access public
  1766. * @return void
  1767. */
  1768. public function AddCustomHeader($custom_header)
  1769. {
  1770. $this->CustomHeader[] = explode(':', $custom_header, 2);
  1771. }
  1772. /**
  1773. * Evaluates the message and returns modifications for inline images and backgrounds
  1774. * @access public
  1775. * @return $message
  1776. */
  1777. public function MsgHTML($message, $basedir = '')
  1778. {
  1779. preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
  1780. if (isset($images[2]))
  1781. {
  1782. foreach ($images[2] as $i => $url)
  1783. {
  1784. // do not change urls for absolute images (thanks to corvuscorax)
  1785. if (! preg_match('/^[A-z][A-z]*:\/\//', $url))
  1786. {
  1787. $filename = basename($url);
  1788. $directory = dirname($url);
  1789. ($directory == '.') ? $directory = '' : '';
  1790. $cid = 'cid:' . md5($filename);
  1791. $fileParts = split("\.", $filename);
  1792. $ext = $fileParts[1];
  1793. $mimeType = $this->_mime_types($ext);
  1794. if (strlen($basedir) > 1 && substr($basedir, - 1) != '/')
  1795. {
  1796. $basedir .= '/';
  1797. }
  1798. if (strlen($directory) > 1 && substr($directory, - 1) != '/')
  1799. {
  1800. $directory .= '/';
  1801. }
  1802. if ($this->AddEmbeddedImage($basedir . $directory . $filename, md5($filename), $filename, 'base64', $mimeType))
  1803. {
  1804. $message = preg_replace("/" . $images[1][$i] . "=\"" . preg_quote($url, '/') . "\"/Ui", $images[1][$i] . "=\"" . $cid . "\"", $message);
  1805. }
  1806. }
  1807. }
  1808. }
  1809. $this->IsHTML(true);
  1810. $this->Body = $message;
  1811. $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
  1812. if (! empty($textMsg) && empty($this->AltBody))
  1813. {
  1814. $this->AltBody = html_entity_decode($textMsg);
  1815. }
  1816. if (empty($this->AltBody))
  1817. {
  1818. $this->AltBody = 'To view this email message, open the email in with HTML compatibility!' . "\n\n";
  1819. }
  1820. }
  1821. /**
  1822. * Gets the mime type of the embedded or inline image
  1823. * @access public
  1824. * @return mime type of ext
  1825. */
  1826. public function _mime_types($ext = '')
  1827. {
  1828. $mimes = array('hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro',
  1829. 'doc' => 'application/msword', 'bin' => 'application/macbinary', 'dms' => 'application/octet-stream',
  1830. 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream',
  1831. 'exe' => 'application/octet-stream', 'class' => 'application/octet-stream',
  1832. 'psd' => 'application/octet-stream', 'so' => 'application/octet-stream',
  1833. 'sea' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'oda' => 'application/oda',
  1834. 'pdf' => 'application/pdf', 'ai' => 'application/postscript', 'eps' => 'application/postscript',
  1835. 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil',
  1836. 'mif' => 'application/vnd.mif', 'xls' => 'application/vnd.ms-excel',
  1837. 'ppt' => 'application/vnd.ms-powerpoint', 'wbxml' => 'application/vnd.wap.wbxml',
  1838. 'wmlc' => 'application/vnd.wap.wmlc', 'dcr' => 'application/x-director',
  1839. 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi',
  1840. 'gtar' => 'application/x-gtar', 'php' => 'application/x-httpd-php',
  1841. 'php4' => 'application/x-httpd-php', 'php3' => 'application/x-httpd-php',
  1842. 'phtml' => 'application/x-httpd-php', 'phps' => 'application/x-httpd-php-source',
  1843. 'js' => 'application/x-javascript', 'swf' => 'application/x-shockwave-flash',
  1844. 'sit' => 'application/x-stuffit', 'tar' => 'application/x-tar', 'tgz' => 'application/x-tar',
  1845. 'xhtml' => 'application/xhtml+xml', 'xht' => 'application/xhtml+xml', 'zip' => 'application/zip',
  1846. 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mpga' => 'audio/mpeg', 'mp2' => 'audio/mpeg',
  1847. 'mp3' => 'audio/mpeg', 'aif' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff',
  1848. 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio',
  1849. 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio',
  1850. 'rv' => 'video/vnd.rn-realvideo', 'wav' => 'audio/x-wav', 'bmp' => 'image/bmp', 'gif' => 'image/gif',
  1851. 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png',
  1852. 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'css' => 'text/css', 'html' => 'text/html',
  1853. 'htm' => 'text/html', 'shtml' => 'text/html', 'txt' => 'text/plain', 'text' => 'text/plain',
  1854. 'log' => 'text/plain', 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', 'xml' => 'text/xml',
  1855. 'xsl' => 'text/xml', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpe' => 'video/mpeg',
  1856. 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  1857. 'movie' => 'video/x-sgi-movie', 'doc' => 'application/msword', 'word' => 'application/msword',
  1858. 'xl' => 'application/excel', 'eml' => 'message/rfc822');
  1859. return (! isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
  1860. }
  1861. /**
  1862. * Set (or reset) Class Objects (variables)
  1863. *
  1864. * Usage Example:
  1865. * $page->set('X-Priority', '3');
  1866. *
  1867. * @access public
  1868. * @param string $name Parameter Name
  1869. * @param mixed $value Parameter Value
  1870. * NOTE: will not work with arrays, there are no arrays to set/reset
  1871. */
  1872. public function set($name, $value = '')
  1873. {
  1874. if (isset($this->$name))
  1875. {
  1876. $this->$name = $value;
  1877. }
  1878. else
  1879. {
  1880. $this->SetError('Cannot set or reset variable ' . $name);
  1881. return false;
  1882. }
  1883. }
  1884. /**
  1885. * Read a file from a supplied filename and return it.
  1886. *
  1887. * @access public
  1888. * @param string $filename Parameter File Name
  1889. */
  1890. public function getFile($filename)
  1891. {
  1892. $return = '';
  1893. if ($fp = fopen($filename, 'rb'))
  1894. {
  1895. while (! feof($fp))
  1896. {
  1897. $return .= fread($fp, 1024);
  1898. }
  1899. fclose($fp);
  1900. return $return;
  1901. }
  1902. else
  1903. {
  1904. return false;
  1905. }
  1906. }
  1907. /**
  1908. * Strips newlines to prevent header injection.
  1909. * @access public
  1910. * @param string $str String
  1911. * @return string
  1912. */
  1913. public function SecureHeader($str)
  1914. {
  1915. $str = trim($str);
  1916. $str = str_replace("\r", "", $str);
  1917. $str = str_replace("\n", "", $str);
  1918. return $str;
  1919. }
  1920. /**
  1921. * Set the private key file and password to sign the message.
  1922. *
  1923. * @access public
  1924. * @param string $key_filename Parameter File Name
  1925. * @param string $key_pass Password for private key
  1926. */
  1927. public function Sign($cert_filename, $key_filename, $key_pass)
  1928. {
  1929. $this->sign_cert_file = $cert_filename;
  1930. $this->sign_key_file = $key_filename;
  1931. $this->sign_key_pass = $key_pass;
  1932. }
  1933. }
  1934. ?>