PageRenderTime 53ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/phpmailer/phpmailer.php

http://github.com/joomla/joomla-platform
PHP | 2830 lines | 1650 code | 214 blank | 966 comment | 290 complexity | 07173fe1b25492dab033c11c3c3bf87a MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /*~ class.phpmailer.php
  3. .---------------------------------------------------------------------------.
  4. | Software: PHPMailer - PHP email class |
  5. | Version: 5.2.2 |
  6. | Site: https://code.google.com/a/apache-extras.org/p/phpmailer/ |
  7. | ------------------------------------------------------------------------- |
  8. | Admin: Jim Jagielski (project admininistrator) |
  9. | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
  10. | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
  11. | : Jim Jagielski (jimjag) jimjag@gmail.com |
  12. | Founder: Brent R. Matzelle (original founder) |
  13. | Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved. |
  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. */
  24. /**
  25. * PHPMailer - PHP email creation and transport class
  26. * NOTE: Requires PHP version 5 or later
  27. * @package PHPMailer
  28. * @author Andy Prevost
  29. * @author Marcus Bointon
  30. * @author Jim Jagielski
  31. * @copyright 2010 - 2012 Jim Jagielski
  32. * @copyright 2004 - 2009 Andy Prevost
  33. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  34. */
  35. if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
  36. /**
  37. * PHP email creation and transport class
  38. * @package PHPMailer
  39. */
  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 Return-Path of the message. If empty, it will
  88. * be set to either From or Sender.
  89. * @var string
  90. */
  91. public $ReturnPath = '';
  92. /**
  93. * Sets the Subject of the message.
  94. * @var string
  95. */
  96. public $Subject = '';
  97. /**
  98. * Sets the Body of the message. This can be either an HTML or text body.
  99. * If HTML then run IsHTML(true).
  100. * @var string
  101. */
  102. public $Body = '';
  103. /**
  104. * Sets the text-only body of the message. This automatically sets the
  105. * email to multipart/alternative. This body can be read by mail
  106. * clients that do not have HTML email capability such as mutt. Clients
  107. * that can read HTML will view the normal Body.
  108. * @var string
  109. */
  110. public $AltBody = '';
  111. /**
  112. * Stores the complete compiled MIME message body.
  113. * @var string
  114. * @access protected
  115. */
  116. protected $MIMEBody = '';
  117. /**
  118. * Stores the complete compiled MIME message headers.
  119. * @var string
  120. * @access protected
  121. */
  122. protected $MIMEHeader = '';
  123. /**
  124. * Stores the extra header list which CreateHeader() doesn't fold in
  125. * @var string
  126. * @access protected
  127. */
  128. protected $mailHeader = '';
  129. /**
  130. * Sets word wrapping on the body of the message to a given number of
  131. * characters.
  132. * @var int
  133. */
  134. public $WordWrap = 0;
  135. /**
  136. * Method to send mail: ("mail", "sendmail", or "smtp").
  137. * @var string
  138. */
  139. public $Mailer = 'mail';
  140. /**
  141. * Sets the path of the sendmail program.
  142. * @var string
  143. */
  144. public $Sendmail = '/usr/sbin/sendmail';
  145. /**
  146. * Determine if mail() uses a fully sendmail compatible MTA that
  147. * supports sendmail's "-oi -f" options
  148. * @var boolean
  149. */
  150. public $UseSendmailOptions = true;
  151. /**
  152. * Path to PHPMailer plugins. Useful if the SMTP class
  153. * is in a different directory than the PHP include path.
  154. * @var string
  155. */
  156. public $PluginDir = '';
  157. /**
  158. * Sets the email address that a reading confirmation will be sent.
  159. * @var string
  160. */
  161. public $ConfirmReadingTo = '';
  162. /**
  163. * Sets the hostname to use in Message-Id and Received headers
  164. * and as default HELO string. If empty, the value returned
  165. * by SERVER_NAME is used or 'localhost.localdomain'.
  166. * @var string
  167. */
  168. public $Hostname = '';
  169. /**
  170. * Sets the message ID to be used in the Message-Id header.
  171. * If empty, a unique id will be generated.
  172. * @var string
  173. */
  174. public $MessageID = '';
  175. /**
  176. * Sets the message Date to be used in the Date header.
  177. * If empty, the current date will be added.
  178. * @var string
  179. */
  180. public $MessageDate = '';
  181. /////////////////////////////////////////////////
  182. // PROPERTIES FOR SMTP
  183. /////////////////////////////////////////////////
  184. /**
  185. * Sets the SMTP hosts.
  186. *
  187. * All hosts must be separated by a
  188. * semicolon. You can also specify a different port
  189. * for each host by using this format: [hostname:port]
  190. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  191. * Hosts will be tried in order.
  192. * @var string
  193. */
  194. public $Host = 'localhost';
  195. /**
  196. * Sets the default SMTP server port.
  197. * @var int
  198. */
  199. public $Port = 25;
  200. /**
  201. * Sets the SMTP HELO of the message (Default is $Hostname).
  202. * @var string
  203. */
  204. public $Helo = '';
  205. /**
  206. * Sets connection prefix. Options are "", "ssl" or "tls"
  207. * @var string
  208. */
  209. public $SMTPSecure = '';
  210. /**
  211. * Sets SMTP authentication. Utilizes the Username and Password variables.
  212. * @var bool
  213. */
  214. public $SMTPAuth = false;
  215. /**
  216. * Sets SMTP username.
  217. * @var string
  218. */
  219. public $Username = '';
  220. /**
  221. * Sets SMTP password.
  222. * @var string
  223. */
  224. public $Password = '';
  225. /**
  226. * Sets SMTP auth type. Options are LOGIN | PLAIN | NTLM (default LOGIN)
  227. * @var string
  228. */
  229. public $AuthType = '';
  230. /**
  231. * Sets SMTP realm.
  232. * @var string
  233. */
  234. public $Realm = '';
  235. /**
  236. * Sets SMTP workstation.
  237. * @var string
  238. */
  239. public $Workstation = '';
  240. /**
  241. * Sets the SMTP server timeout in seconds.
  242. * This function will not work with the win32 version.
  243. * @var int
  244. */
  245. public $Timeout = 10;
  246. /**
  247. * Sets SMTP class debugging on or off.
  248. * @var bool
  249. */
  250. public $SMTPDebug = false;
  251. /**
  252. * Sets the function/method to use for debugging output.
  253. * Right now we only honor "echo" or "error_log"
  254. * @var string
  255. */
  256. public $Debugoutput = "echo";
  257. /**
  258. * Prevents the SMTP connection from being closed after each mail
  259. * sending. If this is set to true then to close the connection
  260. * requires an explicit call to SmtpClose().
  261. * @var bool
  262. */
  263. public $SMTPKeepAlive = false;
  264. /**
  265. * Provides the ability to have the TO field process individual
  266. * emails, instead of sending to entire TO addresses
  267. * @var bool
  268. */
  269. public $SingleTo = false;
  270. /**
  271. * If SingleTo is true, this provides the array to hold the email addresses
  272. * @var bool
  273. */
  274. public $SingleToArray = array();
  275. /**
  276. * Provides the ability to change the generic line ending
  277. * NOTE: The default remains '\n'. We force CRLF where we KNOW
  278. * it must be used via self::CRLF
  279. * @var string
  280. */
  281. public $LE = "\n";
  282. /**
  283. * Used with DKIM Signing
  284. * required parameter if DKIM is enabled
  285. *
  286. * domain selector example domainkey
  287. * @var string
  288. */
  289. public $DKIM_selector = '';
  290. /**
  291. * Used with DKIM Signing
  292. * required if DKIM is enabled, in format of email address 'you@yourdomain.com' typically used as the source of the email
  293. * @var string
  294. */
  295. public $DKIM_identity = '';
  296. /**
  297. * Used with DKIM Signing
  298. * optional parameter if your private key requires a passphras
  299. * @var string
  300. */
  301. public $DKIM_passphrase = '';
  302. /**
  303. * Used with DKIM Singing
  304. * required if DKIM is enabled, in format of email address 'domain.com'
  305. * @var string
  306. */
  307. public $DKIM_domain = '';
  308. /**
  309. * Used with DKIM Signing
  310. * required if DKIM is enabled, path to private key file
  311. * @var string
  312. */
  313. public $DKIM_private = '';
  314. /**
  315. * Callback Action function name.
  316. * The function that handles the result of the send email action.
  317. * It is called out by Send() for each email sent.
  318. *
  319. * Value can be:
  320. * - 'function_name' for function names
  321. * - 'Class::Method' for static method calls
  322. * - array($object, 'Method') for calling methods on $object
  323. * See http://php.net/is_callable manual page for more details.
  324. *
  325. * Parameters:
  326. * bool $result result of the send action
  327. * string $to email address of the recipient
  328. * string $cc cc email addresses
  329. * string $bcc bcc email addresses
  330. * string $subject the subject
  331. * string $body the email body
  332. * string $from email address of sender
  333. * @var string
  334. */
  335. public $action_function = ''; //'callbackAction';
  336. /**
  337. * Sets the PHPMailer Version number
  338. * @var string
  339. */
  340. public $Version = '5.2.2';
  341. /**
  342. * What to use in the X-Mailer header
  343. * @var string NULL for default, whitespace for None, or actual string to use
  344. */
  345. public $XMailer = '';
  346. /////////////////////////////////////////////////
  347. // PROPERTIES, PRIVATE AND PROTECTED
  348. /////////////////////////////////////////////////
  349. /**
  350. * @var SMTP An instance of the SMTP sender class
  351. * @access protected
  352. */
  353. protected $smtp = null;
  354. /**
  355. * @var array An array of 'to' addresses
  356. * @access protected
  357. */
  358. protected $to = array();
  359. /**
  360. * @var array An array of 'cc' addresses
  361. * @access protected
  362. */
  363. protected $cc = array();
  364. /**
  365. * @var array An array of 'bcc' addresses
  366. * @access protected
  367. */
  368. protected $bcc = array();
  369. /**
  370. * @var array An array of reply-to name and address
  371. * @access protected
  372. */
  373. protected $ReplyTo = array();
  374. /**
  375. * @var array An array of all kinds of addresses: to, cc, bcc, replyto
  376. * @access protected
  377. */
  378. protected $all_recipients = array();
  379. /**
  380. * @var array An array of attachments
  381. * @access protected
  382. */
  383. protected $attachment = array();
  384. /**
  385. * @var array An array of custom headers
  386. * @access protected
  387. */
  388. protected $CustomHeader = array();
  389. /**
  390. * @var string The message's MIME type
  391. * @access protected
  392. */
  393. protected $message_type = '';
  394. /**
  395. * @var array An array of MIME boundary strings
  396. * @access protected
  397. */
  398. protected $boundary = array();
  399. /**
  400. * @var array An array of available languages
  401. * @access protected
  402. */
  403. protected $language = array();
  404. /**
  405. * @var integer The number of errors encountered
  406. * @access protected
  407. */
  408. protected $error_count = 0;
  409. /**
  410. * @var string The filename of a DKIM certificate file
  411. * @access protected
  412. */
  413. protected $sign_cert_file = '';
  414. /**
  415. * @var string The filename of a DKIM key file
  416. * @access protected
  417. */
  418. protected $sign_key_file = '';
  419. /**
  420. * @var string The password of a DKIM key
  421. * @access protected
  422. */
  423. protected $sign_key_pass = '';
  424. /**
  425. * @var boolean Whether to throw exceptions for errors
  426. * @access protected
  427. */
  428. protected $exceptions = false;
  429. /////////////////////////////////////////////////
  430. // CONSTANTS
  431. /////////////////////////////////////////////////
  432. const STOP_MESSAGE = 0; // message only, continue processing
  433. const STOP_CONTINUE = 1; // message?, likely ok to continue processing
  434. const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
  435. const CRLF = "\r\n"; // SMTP RFC specified EOL
  436. /////////////////////////////////////////////////
  437. // METHODS, VARIABLES
  438. /////////////////////////////////////////////////
  439. /**
  440. * Calls actual mail() function, but in a safe_mode aware fashion
  441. * Also, unless sendmail_path points to sendmail (or something that
  442. * claims to be sendmail), don't pass params (not a perfect fix,
  443. * but it will do)
  444. * @param string $to To
  445. * @param string $subject Subject
  446. * @param string $body Message Body
  447. * @param string $header Additional Header(s)
  448. * @param string $params Params
  449. * @access private
  450. * @return bool
  451. */
  452. private function mail_passthru($to, $subject, $body, $header, $params) {
  453. if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {
  454. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
  455. } else {
  456. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
  457. }
  458. return $rt;
  459. }
  460. /**
  461. * Outputs debugging info via user-defined method
  462. * @param string $str
  463. */
  464. private function edebug($str) {
  465. if ($this->Debugoutput == "error_log") {
  466. error_log($str);
  467. } else {
  468. echo $str;
  469. }
  470. }
  471. /**
  472. * Constructor
  473. * @param boolean $exceptions Should we throw external exceptions?
  474. */
  475. public function __construct($exceptions = false) {
  476. $this->exceptions = ($exceptions == true);
  477. }
  478. /**
  479. * Sets message type to HTML.
  480. * @param bool $ishtml
  481. * @return void
  482. */
  483. public function IsHTML($ishtml = true) {
  484. if ($ishtml) {
  485. $this->ContentType = 'text/html';
  486. } else {
  487. $this->ContentType = 'text/plain';
  488. }
  489. }
  490. /**
  491. * Sets Mailer to send message using SMTP.
  492. * @return void
  493. * @deprecated
  494. */
  495. public function IsSMTP() {
  496. $this->Mailer = 'smtp';
  497. }
  498. /**
  499. * Sets Mailer to send message using PHP mail() function.
  500. * @return void
  501. * @deprecated
  502. */
  503. public function IsMail() {
  504. $this->Mailer = 'mail';
  505. }
  506. /**
  507. * Sets Mailer to send message using the $Sendmail program.
  508. * @return void
  509. * @deprecated
  510. */
  511. public function IsSendmail() {
  512. if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
  513. $this->Sendmail = '/var/qmail/bin/sendmail';
  514. }
  515. $this->Mailer = 'sendmail';
  516. }
  517. /**
  518. * Sets Mailer to send message using the qmail MTA.
  519. * @return void
  520. * @deprecated
  521. */
  522. public function IsQmail() {
  523. if (stristr(ini_get('sendmail_path'), 'qmail')) {
  524. $this->Sendmail = '/var/qmail/bin/sendmail';
  525. }
  526. $this->Mailer = 'sendmail';
  527. }
  528. /////////////////////////////////////////////////
  529. // METHODS, RECIPIENTS
  530. /////////////////////////////////////////////////
  531. /**
  532. * Adds a "To" address.
  533. * @param string $address
  534. * @param string $name
  535. * @return boolean true on success, false if address already used
  536. */
  537. public function AddAddress($address, $name = '') {
  538. return $this->AddAnAddress('to', $address, $name);
  539. }
  540. /**
  541. * Adds a "Cc" address.
  542. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  543. * @param string $address
  544. * @param string $name
  545. * @return boolean true on success, false if address already used
  546. */
  547. public function AddCC($address, $name = '') {
  548. return $this->AddAnAddress('cc', $address, $name);
  549. }
  550. /**
  551. * Adds a "Bcc" address.
  552. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  553. * @param string $address
  554. * @param string $name
  555. * @return boolean true on success, false if address already used
  556. */
  557. public function AddBCC($address, $name = '') {
  558. return $this->AddAnAddress('bcc', $address, $name);
  559. }
  560. /**
  561. * Adds a "Reply-to" address.
  562. * @param string $address
  563. * @param string $name
  564. * @return boolean
  565. */
  566. public function AddReplyTo($address, $name = '') {
  567. return $this->AddAnAddress('Reply-To', $address, $name);
  568. }
  569. /**
  570. * Adds an address to one of the recipient arrays
  571. * Addresses that have been added already return false, but do not throw exceptions
  572. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  573. * @param string $address The email address to send to
  574. * @param string $name
  575. * @throws phpmailerException
  576. * @return boolean true on success, false if address already used or invalid in some way
  577. * @access protected
  578. */
  579. protected function AddAnAddress($kind, $address, $name = '') {
  580. if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
  581. $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
  582. if ($this->exceptions) {
  583. throw new phpmailerException('Invalid recipient array: ' . $kind);
  584. }
  585. if ($this->SMTPDebug) {
  586. $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
  587. }
  588. return false;
  589. }
  590. $address = trim($address);
  591. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  592. if (!$this->ValidateAddress($address)) {
  593. $this->SetError($this->Lang('invalid_address').': '. $address);
  594. if ($this->exceptions) {
  595. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  596. }
  597. if ($this->SMTPDebug) {
  598. $this->edebug($this->Lang('invalid_address').': '.$address);
  599. }
  600. return false;
  601. }
  602. if ($kind != 'Reply-To') {
  603. if (!isset($this->all_recipients[strtolower($address)])) {
  604. array_push($this->$kind, array($address, $name));
  605. $this->all_recipients[strtolower($address)] = true;
  606. return true;
  607. }
  608. } else {
  609. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  610. $this->ReplyTo[strtolower($address)] = array($address, $name);
  611. return true;
  612. }
  613. }
  614. return false;
  615. }
  616. /**
  617. * Set the From and FromName properties
  618. * @param string $address
  619. * @param string $name
  620. * @param int $auto Also set Reply-To and Sender
  621. * @throws phpmailerException
  622. * @return boolean
  623. */
  624. public function SetFrom($address, $name = '', $auto = 1) {
  625. $address = trim($address);
  626. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  627. if (!$this->ValidateAddress($address)) {
  628. $this->SetError($this->Lang('invalid_address').': '. $address);
  629. if ($this->exceptions) {
  630. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  631. }
  632. if ($this->SMTPDebug) {
  633. $this->edebug($this->Lang('invalid_address').': '.$address);
  634. }
  635. return false;
  636. }
  637. $this->From = $address;
  638. $this->FromName = $name;
  639. if ($auto) {
  640. if (empty($this->ReplyTo)) {
  641. $this->AddAnAddress('Reply-To', $address, $name);
  642. }
  643. if (empty($this->Sender)) {
  644. $this->Sender = $address;
  645. }
  646. }
  647. return true;
  648. }
  649. /**
  650. * Check that a string looks roughly like an email address should
  651. * Static so it can be used without instantiation, public so people can overload
  652. * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
  653. * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
  654. * not allow a@b type valid addresses :(
  655. * Some Versions of PHP break on the regex though, likely due to PCRE, so use
  656. * the older validation method for those users. (http://php.net/manual/en/pcre.installation.php)
  657. * @link http://squiloople.com/2009/12/20/email-address-validation/
  658. * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice.
  659. * @param string $address The email address to check
  660. * @return boolean
  661. * @static
  662. * @access public
  663. */
  664. public static function ValidateAddress($address) {
  665. if ((defined('PCRE_VERSION')) && (version_compare(PCRE_VERSION, '8.0') >= 0)) {
  666. return preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[ ])+|(?>[ ]*\x0D\x0A)?[ ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){7,})((?6)(?>:(?6)){0,5})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){5,})(?8)?::(?>((?6)(?>:(?6)){0,3}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address);
  667. } elseif (function_exists('filter_var')) { //Introduced in PHP 5.2
  668. if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {
  669. return false;
  670. } else {
  671. return true;
  672. }
  673. } else {
  674. 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);
  675. }
  676. }
  677. /////////////////////////////////////////////////
  678. // METHODS, MAIL SENDING
  679. /////////////////////////////////////////////////
  680. /**
  681. * Creates message and assigns Mailer. If the message is
  682. * not sent successfully then it returns false. Use the ErrorInfo
  683. * variable to view description of the error.
  684. * @throws phpmailerException
  685. * @return bool
  686. */
  687. public function Send() {
  688. try {
  689. if(!$this->PreSend()) return false;
  690. return $this->PostSend();
  691. } catch (phpmailerException $e) {
  692. $this->mailHeader = '';
  693. $this->SetError($e->getMessage());
  694. if ($this->exceptions) {
  695. throw $e;
  696. }
  697. return false;
  698. }
  699. }
  700. /**
  701. * Prep mail by constructing all message entities
  702. * @throws phpmailerException
  703. * @return bool
  704. */
  705. public function PreSend() {
  706. try {
  707. $this->mailHeader = "";
  708. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  709. throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
  710. }
  711. // Set whether the message is multipart/alternative
  712. if(!empty($this->AltBody)) {
  713. $this->ContentType = 'multipart/alternative';
  714. }
  715. $this->error_count = 0; // reset errors
  716. $this->SetMessageType();
  717. //Refuse to send an empty message
  718. if (empty($this->Body)) {
  719. throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
  720. }
  721. $this->MIMEHeader = $this->CreateHeader();
  722. $this->MIMEBody = $this->CreateBody();
  723. // To capture the complete message when using mail(), create
  724. // an extra header list which CreateHeader() doesn't fold in
  725. if ($this->Mailer == 'mail') {
  726. if (count($this->to) > 0) {
  727. $this->mailHeader .= $this->AddrAppend("To", $this->to);
  728. } else {
  729. $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
  730. }
  731. $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
  732. // if(count($this->cc) > 0) {
  733. // $this->mailHeader .= $this->AddrAppend("Cc", $this->cc);
  734. // }
  735. }
  736. // digitally sign with DKIM if enabled
  737. if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) {
  738. $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
  739. $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
  740. }
  741. return true;
  742. } catch (phpmailerException $e) {
  743. $this->SetError($e->getMessage());
  744. if ($this->exceptions) {
  745. throw $e;
  746. }
  747. return false;
  748. }
  749. }
  750. /**
  751. * Actual Email transport function
  752. * Send the email via the selected mechanism
  753. * @throws phpmailerException
  754. * @return bool
  755. */
  756. public function PostSend() {
  757. try {
  758. // Choose the mailer and send through it
  759. switch($this->Mailer) {
  760. case 'sendmail':
  761. return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
  762. case 'smtp':
  763. return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
  764. case 'mail':
  765. return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
  766. default:
  767. return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
  768. }
  769. } catch (phpmailerException $e) {
  770. $this->SetError($e->getMessage());
  771. if ($this->exceptions) {
  772. throw $e;
  773. }
  774. if ($this->SMTPDebug) {
  775. $this->edebug($e->getMessage()."\n");
  776. }
  777. }
  778. return false;
  779. }
  780. /**
  781. * Sends mail using the $Sendmail program.
  782. * @param string $header The message headers
  783. * @param string $body The message body
  784. * @throws phpmailerException
  785. * @access protected
  786. * @return bool
  787. */
  788. protected function SendmailSend($header, $body) {
  789. if ($this->Sender != '') {
  790. $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  791. } else {
  792. $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
  793. }
  794. if ($this->SingleTo === true) {
  795. foreach ($this->SingleToArray as $val) {
  796. if(!@$mail = popen($sendmail, 'w')) {
  797. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  798. }
  799. fputs($mail, "To: " . $val . "\n");
  800. fputs($mail, $header);
  801. fputs($mail, $body);
  802. $result = pclose($mail);
  803. // implement call back function if it exists
  804. $isSent = ($result == 0) ? 1 : 0;
  805. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  806. if($result != 0) {
  807. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  808. }
  809. }
  810. } else {
  811. if(!@$mail = popen($sendmail, 'w')) {
  812. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  813. }
  814. fputs($mail, $header);
  815. fputs($mail, $body);
  816. $result = pclose($mail);
  817. // implement call back function if it exists
  818. $isSent = ($result == 0) ? 1 : 0;
  819. $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
  820. if($result != 0) {
  821. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  822. }
  823. }
  824. return true;
  825. }
  826. /**
  827. * Sends mail using the PHP mail() function.
  828. * @param string $header The message headers
  829. * @param string $body The message body
  830. * @throws phpmailerException
  831. * @access protected
  832. * @return bool
  833. */
  834. protected function MailSend($header, $body) {
  835. $toArr = array();
  836. foreach($this->to as $t) {
  837. $toArr[] = $this->AddrFormat($t);
  838. }
  839. $to = implode(', ', $toArr);
  840. if (empty($this->Sender)) {
  841. $params = "-oi ";
  842. } else {
  843. $params = sprintf("-oi -f%s", $this->Sender);
  844. }
  845. if ($this->Sender != '' and !ini_get('safe_mode')) {
  846. $old_from = ini_get('sendmail_from');
  847. ini_set('sendmail_from', $this->Sender);
  848. }
  849. $rt = false;
  850. if ($this->SingleTo === true && count($toArr) > 1) {
  851. foreach ($toArr as $val) {
  852. $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params);
  853. // implement call back function if it exists
  854. $isSent = ($rt == 1) ? 1 : 0;
  855. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  856. }
  857. } else {
  858. $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params);
  859. // implement call back function if it exists
  860. $isSent = ($rt == 1) ? 1 : 0;
  861. $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
  862. }
  863. if (isset($old_from)) {
  864. ini_set('sendmail_from', $old_from);
  865. }
  866. if(!$rt) {
  867. throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
  868. }
  869. return true;
  870. }
  871. /**
  872. * Sends mail via SMTP using PhpSMTP
  873. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  874. * @param string $header The message headers
  875. * @param string $body The message body
  876. * @throws phpmailerException
  877. * @uses SMTP
  878. * @access protected
  879. * @return bool
  880. */
  881. protected function SmtpSend($header, $body) {
  882. require_once $this->PluginDir . 'smtp.php';
  883. $bad_rcpt = array();
  884. if(!$this->SmtpConnect()) {
  885. throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
  886. }
  887. $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
  888. if(!$this->smtp->Mail($smtp_from)) {
  889. $this->SetError($this->Lang('from_failed') . $smtp_from . " : " . implode(",",$this->smtp->getError())) ;
  890. throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  891. }
  892. // Attempt to send attach all recipients
  893. foreach($this->to as $to) {
  894. if (!$this->smtp->Recipient($to[0])) {
  895. $bad_rcpt[] = $to[0];
  896. // implement call back function if it exists
  897. $isSent = 0;
  898. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  899. } else {
  900. // implement call back function if it exists
  901. $isSent = 1;
  902. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  903. }
  904. }
  905. foreach($this->cc as $cc) {
  906. if (!$this->smtp->Recipient($cc[0])) {
  907. $bad_rcpt[] = $cc[0];
  908. // implement call back function if it exists
  909. $isSent = 0;
  910. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  911. } else {
  912. // implement call back function if it exists
  913. $isSent = 1;
  914. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  915. }
  916. }
  917. foreach($this->bcc as $bcc) {
  918. if (!$this->smtp->Recipient($bcc[0])) {
  919. $bad_rcpt[] = $bcc[0];
  920. // implement call back function if it exists
  921. $isSent = 0;
  922. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  923. } else {
  924. // implement call back function if it exists
  925. $isSent = 1;
  926. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  927. }
  928. }
  929. if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
  930. $badaddresses = implode(', ', $bad_rcpt);
  931. throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
  932. }
  933. if(!$this->smtp->Data($header . $body)) {
  934. throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
  935. }
  936. if($this->SMTPKeepAlive == true) {
  937. $this->smtp->Reset();
  938. } else {
  939. $this->smtp->Quit();
  940. $this->smtp->Close();
  941. }
  942. return true;
  943. }
  944. /**
  945. * Initiates a connection to an SMTP server.
  946. * Returns false if the operation failed.
  947. * @uses SMTP
  948. * @access public
  949. * @throws phpmailerException
  950. * @return bool
  951. */
  952. public function SmtpConnect() {
  953. if(is_null($this->smtp)) {
  954. $this->smtp = new SMTP;
  955. }
  956. $this->smtp->Timeout = $this->Timeout;
  957. $this->smtp->do_debug = $this->SMTPDebug;
  958. $hosts = explode(';', $this->Host);
  959. $index = 0;
  960. $connection = $this->smtp->Connected();
  961. // Retry while there is no connection
  962. try {
  963. while($index < count($hosts) && !$connection) {
  964. $hostinfo = array();
  965. if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
  966. $host = $hostinfo[1];
  967. $port = $hostinfo[2];
  968. } else {
  969. $host = $hosts[$index];
  970. $port = $this->Port;
  971. }
  972. $tls = ($this->SMTPSecure == 'tls');
  973. $ssl = ($this->SMTPSecure == 'ssl');
  974. if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
  975. $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
  976. $this->smtp->Hello($hello);
  977. if ($tls) {
  978. if (!$this->smtp->StartTLS()) {
  979. throw new phpmailerException($this->Lang('connect_host'));
  980. }
  981. //We must resend HELO after tls negotiation
  982. $this->smtp->Hello($hello);
  983. }
  984. $connection = true;
  985. if ($this->SMTPAuth) {
  986. if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType,
  987. $this->Realm, $this->Workstation)) {
  988. throw new phpmailerException($this->Lang('authenticate'));
  989. }
  990. }
  991. }
  992. $index++;
  993. if (!$connection) {
  994. throw new phpmailerException($this->Lang('connect_host'));
  995. }
  996. }
  997. } catch (phpmailerException $e) {
  998. $this->smtp->Reset();
  999. if ($this->exceptions) {
  1000. throw $e;
  1001. }
  1002. }
  1003. return true;
  1004. }
  1005. /**
  1006. * Closes the active SMTP session if one exists.
  1007. * @return void
  1008. */
  1009. public function SmtpClose() {
  1010. if ($this->smtp !== null) {
  1011. if($this->smtp->Connected()) {
  1012. $this->smtp->Quit();
  1013. $this->smtp->Close();
  1014. }
  1015. }
  1016. }
  1017. /**
  1018. * Sets the language for all class error messages.
  1019. * Returns false if it cannot load the language file. The default language is English.
  1020. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
  1021. * @param string $lang_path Path to the language file directory
  1022. * @return bool
  1023. * @access public
  1024. */
  1025. function SetLanguage($langcode = 'en', $lang_path = 'language/') {
  1026. //Define full set of translatable strings
  1027. $PHPMAILER_LANG = array(
  1028. 'authenticate' => 'SMTP Error: Could not authenticate.',
  1029. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  1030. 'data_not_accepted' => 'SMTP Error: Data not accepted.',
  1031. 'empty_message' => 'Message body empty',
  1032. 'encoding' => 'Unknown encoding: ',
  1033. 'execute' => 'Could not execute: ',
  1034. 'file_access' => 'Could not access file: ',
  1035. 'file_open' => 'File Error: Could not open file: ',
  1036. 'from_failed' => 'The following From address failed: ',
  1037. 'instantiate' => 'Could not instantiate mail function.',
  1038. 'invalid_address' => 'Invalid address',
  1039. 'mailer_not_supported' => ' mailer is not supported.',
  1040. 'provide_address' => 'You must provide at least one recipient email address.',
  1041. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  1042. 'signing' => 'Signing Error: ',
  1043. 'smtp_connect_failed' => 'SMTP Connect() failed.',
  1044. 'smtp_error' => 'SMTP server error: ',
  1045. 'variable_set' => 'Cannot set or reset variable: '
  1046. );
  1047. //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
  1048. $l = true;
  1049. if ($langcode != 'en') { //There is no English translation file
  1050. $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
  1051. }
  1052. $this->language = $PHPMAILER_LANG;
  1053. return ($l == true); //Returns false if language not found
  1054. }
  1055. /**
  1056. * Return the current array of language strings
  1057. * @return array
  1058. */
  1059. public function GetTranslations() {
  1060. return $this->language;
  1061. }
  1062. /////////////////////////////////////////////////
  1063. // METHODS, MESSAGE CREATION
  1064. /////////////////////////////////////////////////
  1065. /**
  1066. * Creates recipient headers.
  1067. * @access public
  1068. * @param string $type
  1069. * @param array $addr
  1070. * @return string
  1071. */
  1072. public function AddrAppend($type, $addr) {
  1073. $addr_str = $type . ': ';
  1074. $addresses = array();
  1075. foreach ($addr as $a) {
  1076. $addresses[] = $this->AddrFormat($a);
  1077. }
  1078. $addr_str .= implode(', ', $addresses);
  1079. $addr_str .= $this->LE;
  1080. return $addr_str;
  1081. }
  1082. /**
  1083. * Formats an address correctly.
  1084. * @access public
  1085. * @param string $addr
  1086. * @return string
  1087. */
  1088. public function AddrFormat($addr) {
  1089. if (empty($addr[1])) {
  1090. return $this->SecureHeader($addr[0]);
  1091. } else {
  1092. return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
  1093. }
  1094. }
  1095. /**
  1096. * Wraps message for use with mailers that do not
  1097. * automatically perform wrapping and for quoted-printable.
  1098. * Original written by philippe.
  1099. * @param string $message The message to wrap
  1100. * @param integer $length The line length to wrap to
  1101. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  1102. * @access public
  1103. * @return string
  1104. */
  1105. public function WrapText($message, $length, $qp_mode = false) {
  1106. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  1107. // If utf-8 encoding is used, we will need to make sure we don't
  1108. // split multibyte characters when we wrap
  1109. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  1110. $lelen = strlen($this->LE);
  1111. $crlflen = strlen(self::CRLF);
  1112. $message = $this->FixEOL($message);
  1113. if (substr($message, -$lelen) == $this->LE) {
  1114. $message = substr($message, 0, -$lelen);
  1115. }
  1116. $line = explode($this->LE, $message); // Magic. We know FixEOL uses $LE
  1117. $message = '';
  1118. for ($i = 0 ;$i < count($line); $i++) {
  1119. $line_part = explode(' ', $line[$i]);
  1120. $buf = '';
  1121. for ($e = 0; $e<count($line_part); $e++) {
  1122. $word = $line_part[$e];
  1123. if ($qp_mode and (strlen($word) > $length)) {
  1124. $space_left = $length - strlen($buf) - $crlflen;
  1125. if ($e != 0) {
  1126. if ($space_left > 20) {
  1127. $len = $space_left;
  1128. if ($is_utf8) {
  1129. $len = $this->UTF8CharBoundary($word, $len);
  1130. } elseif (substr($word, $len - 1, 1) == "=") {
  1131. $len--;
  1132. } elseif (substr($word, $len - 2, 1) == "=") {
  1133. $len -= 2;
  1134. }
  1135. $part = substr($word, 0, $len);
  1136. $word = substr($word, $len);
  1137. $buf .= ' ' . $part;
  1138. $message .= $buf . sprintf("=%s", self::CRLF);
  1139. } else {
  1140. $message .= $buf . $soft_break;
  1141. }
  1142. $buf = '';
  1143. }
  1144. while (strlen($word) > 0) {
  1145. $len = $length;
  1146. if ($is_utf8) {
  1147. $len = $this->UTF8CharBoundary($word, $len);
  1148. } elseif (substr($word, $len - 1, 1) == "=") {
  1149. $len--;
  1150. } elseif (substr($word, $len - 2, 1) == "=") {
  1151. $len -= 2;
  1152. }
  1153. $part = substr($word, 0, $len);
  1154. $word = substr($word, $len);
  1155. if (strlen($word) > 0) {
  1156. $message .= $part . sprintf("=%s", self::CRLF);
  1157. } else {
  1158. $buf = $part;
  1159. }
  1160. }
  1161. } else {
  1162. $buf_o = $buf;
  1163. $buf .= ($e == 0) ? $word : (' ' . $word);
  1164. if (strlen($buf) > $length and $buf_o != '') {
  1165. $message .= $buf_o . $soft_break;
  1166. $buf = $word;
  1167. }
  1168. }
  1169. }
  1170. $message .= $buf . self::CRLF;
  1171. }
  1172. return $message;
  1173. }
  1174. /**
  1175. * Finds last character boundary prior to maxLength in a utf-8
  1176. * quoted (printable) encoded string.
  1177. * Original written by Colin Brown.
  1178. * @access public
  1179. * @param string $encodedText utf-8 QP text
  1180. * @param int $maxLength find last character boundary prior to this length
  1181. * @return int
  1182. */
  1183. public function UTF8CharBoundary($encodedText, $maxLength) {
  1184. $foundSplitPos = false;
  1185. $lookBack = 3;
  1186. while (!$foundSplitPos) {
  1187. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  1188. $encodedCharPos = strpos($lastChunk, "=");
  1189. if ($encodedCharPos !== false) {
  1190. // Found start of encoded character byte within $lookBack block.
  1191. // Check the encoded byte value (the 2 chars after the '=')
  1192. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  1193. $dec = hexdec($hex);
  1194. if ($dec < 128) { // Single byte character.
  1195. // If the encoded char was found at pos 0, it will fit
  1196. // otherwise reduce maxLength to start of the encoded char
  1197. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  1198. $maxLength - ($lookBack - $encodedCharPos);
  1199. $foundSplitPos = true;
  1200. } elseif ($dec >= 192) { // First byte of a multi byte character
  1201. // Reduce maxLength to split at start of character
  1202. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1203. $foundSplitPos = true;
  1204. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  1205. $lookBack += 3;
  1206. }
  1207. } else {
  1208. // No encoded character found
  1209. $foundSplitPos = true;
  1210. }
  1211. }
  1212. return $maxLength;
  1213. }
  1214. /**
  1215. * Set the body wrapping.
  1216. * @access public
  1217. * @return void
  1218. */
  1219. public function SetWordWrap() {
  1220. if($this->WordWrap < 1) {
  1221. return;
  1222. }
  1223. switch($this->message_type) {
  1224. case 'alt':
  1225. case 'alt_inline':
  1226. case 'alt_attach':
  1227. case 'alt_inline_attach':
  1228. $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
  1229. break;
  1230. default:
  1231. $this->Body = $this->WrapText($this->Body, $this->WordWrap);
  1232. break;
  1233. }
  1234. }
  1235. /**
  1236. * Assembles message header.
  1237. * @access public
  1238. * @return string The assembled header
  1239. */
  1240. public function CreateHeader() {
  1241. $result = '';
  1242. // Set the boundaries
  1243. $uniq_id = md5(uniqid(time()));
  1244. $this->boundary[1] = 'b1_' . $uniq_id;
  1245. $this->boundary[2] = 'b2_' . $uniq_id;
  1246. $this->boundary[3] = 'b3_' . $uniq_id;
  1247. if ($this->MessageDate == '') {
  1248. $result .= $this->HeaderLine('Date', self::RFCDate());
  1249. } else {
  1250. $result .= $this->HeaderLine('Date', $this->MessageDate);
  1251. }
  1252. if ($this->ReturnPath) {
  1253. $result .= $this->HeaderLine('Return-Path', trim($this->ReturnPath));
  1254. } elseif ($this->Sender == '') {
  1255. $result .= $this->HeaderLine('Return-Path', trim($this->From));
  1256. } else {
  1257. $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
  1258. }
  1259. // To be created automatically by mail()
  1260. if($this->Mailer != 'mail') {
  1261. if ($this->SingleTo === true) {
  1262. foreach($this->to as $t) {
  1263. $this->SingleToArray[] = $this->AddrFormat($t);
  1264. }
  1265. } else {
  1266. if(count($this->to) > 0) {
  1267. $result .= $this->AddrAppend('To', $this->to);
  1268. } elseif (count($this->cc) == 0) {
  1269. $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
  1270. }
  1271. }
  1272. }
  1273. $from = array();
  1274. $from[0][0] = trim($this->From);
  1275. $from[0][1] = $this->FromName;
  1276. $result .= $this->AddrAppend('From', $from);
  1277. // sendmail and mail() extract Cc from the header before sending
  1278. if(count($this->cc) > 0) {
  1279. $result .= $this->AddrAppend('Cc', $this->cc);
  1280. }
  1281. // sendmail and mail() extract Bcc from the header before sending
  1282. if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
  1283. $result .= $this->AddrAppend('Bcc', $this->bcc);
  1284. }
  1285. if(count($this->ReplyTo) > 0) {
  1286. $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
  1287. }
  1288. // mail() sets the subject itself
  1289. if($this->Mailer != 'mail') {
  1290. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
  1291. }
  1292. if($this->MessageID != '') {
  1293. $result .= $this->HeaderLine('Message-ID', $this->MessageID);
  1294. } else {
  1295. $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
  1296. }
  1297. $result .= $this->HeaderLine('X-Priority', $this->Priority);
  1298. if ($this->XMailer == '') {
  1299. $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)');
  1300. } else {
  1301. $myXmailer = trim($this->XMailer);
  1302. if ($myXmailer) {
  1303. $result .= $this->HeaderLine('X-Mailer', $myXmailer);
  1304. }
  1305. }
  1306. if($this->ConfirmReadingTo != '') {
  1307. $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  1308. }
  1309. // Add custom headers
  1310. for($index = 0; $index < count($this->CustomHeader); $index++) {
  1311. $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
  1312. }
  1313. if (!$this->sign_key_file) {
  1314. $result .= $this->HeaderLine('MIME-Version', '1.0');
  1315. $result .= $this->GetMailMIME();
  1316. }
  1317. return $result;
  1318. }
  1319. /**
  1320. * Returns the message MIME.
  1321. * @access public
  1322. * @return string
  1323. */
  1324. public function GetMailMIME() {
  1325. $result = '';
  1326. switch($this->message_type) {
  1327. case 'inline':
  1328. $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1329. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1330. break;
  1331. case 'attach':
  1332. case 'inline_attach':
  1333. case 'alt_attach':
  1334. case 'alt_inline_attach':
  1335. $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
  1336. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1337. break;
  1338. case 'alt':
  1339. case 'alt_inline':
  1340. $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1341. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1342. break;
  1343. default:
  1344. // Catches case 'plain': and case '':
  1345. $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
  1346. $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet);
  1347. break;
  1348. }
  1349. if($this->Mailer != 'mail') {
  1350. $result .= $this->LE;
  1351. }
  1352. return $result;
  1353. }
  1354. /**
  1355. * Returns the MIME message (headers and body). Only really valid post PreSend().
  1356. * @access public
  1357. * @return string
  1358. */
  1359. public function GetSentMIMEMessage() {
  1360. return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
  1361. }
  1362. /**
  1363. * Assembles the message body. Returns an empty string on failure.
  1364. * @access public
  1365. * @throws phpmailerException
  1366. * @return string The assembled message body
  1367. */
  1368. public function CreateBody() {
  1369. $body = '';
  1370. if ($this->sign_key_file) {
  1371. $body .= $this->GetMailMIME().$this->LE;
  1372. }
  1373. $this->SetWordWrap();
  1374. switch($this->message_type) {
  1375. case 'inline':
  1376. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  1377. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1378. $body .= $this->LE.$this->LE;
  1379. $body .= $this->AttachAll("inline", $this->boundary[1]);
  1380. break;
  1381. case 'attach':
  1382. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  1383. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1384. $body .= $this->LE.$this->LE;
  1385. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1386. break;
  1387. case 'inline_attach':
  1388. $body .= $this->TextLine("--" . $this->boundary[1]);
  1389. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1390. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1391. $body .= $this->LE;
  1392. $body .= $this->GetBoundary($this->boundary[2], '', '', '');
  1393. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1394. $body .= $this->LE.$this->LE;
  1395. $body .= $this->AttachAll("inline", $this->boundary[2]);
  1396. $body .= $this->LE;
  1397. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1398. break;
  1399. case 'alt':
  1400. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1401. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1402. $body .= $this->LE.$this->LE;
  1403. $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
  1404. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1405. $body .= $this->LE.$this->LE;
  1406. $body .= $this->EndBoundary($this->boundary[1]);
  1407. break;
  1408. case 'alt_inline':
  1409. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1410. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1411. $body .= $this->LE.$this->LE;
  1412. $body .= $this->TextLine("--" . $this->boundary[1]);
  1413. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1414. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1415. $body .= $this->LE;
  1416. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  1417. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1418. $body .= $this->LE.$this->LE;
  1419. $body .= $this->AttachAll("inline", $this->boundary[2]);
  1420. $body .= $this->LE;
  1421. $body .= $this->EndBoundary($this->boundary[1]);
  1422. break;
  1423. case 'alt_attach':
  1424. $body .= $this->TextLine("--" . $this->boundary[1]);
  1425. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1426. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1427. $body .= $this->LE;
  1428. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  1429. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1430. $body .= $this->LE.$this->LE;
  1431. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  1432. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1433. $body .= $this->LE.$this->LE;
  1434. $body .= $this->EndBoundary($this->boundary[2]);
  1435. $body .= $this->LE;
  1436. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1437. break;
  1438. case 'alt_inline_attach':
  1439. $body .= $this->TextLine("--" . $this->boundary[1]);
  1440. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1441. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1442. $body .= $this->LE;
  1443. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  1444. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1445. $body .= $this->LE.$this->LE;
  1446. $body .= $this->TextLine("--" . $this->boundary[2]);
  1447. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1448. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"');
  1449. $body .= $this->LE;
  1450. $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
  1451. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1452. $body .= $this->LE.$this->LE;
  1453. $body .= $this->AttachAll("inline", $this->boundary[3]);
  1454. $body .= $this->LE;
  1455. $body .= $this->EndBoundary($this->boundary[2]);
  1456. $body .= $this->LE;
  1457. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1458. break;
  1459. default:
  1460. // catch case 'plain' and case ''
  1461. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1462. break;
  1463. }
  1464. if ($this->IsError()) {
  1465. $body = '';
  1466. } elseif ($this->sign_key_file) {
  1467. try {
  1468. $file = tempnam('', 'mail');
  1469. file_put_contents($file, $body); //TODO check this worked
  1470. $signed = tempnam("", "signed");
  1471. if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
  1472. @unlink($file);
  1473. $body = file_get_contents($signed);
  1474. @unlink($signed);
  1475. } else {
  1476. @unlink($file);
  1477. @unlink($signed);
  1478. throw new phpmailerException($this->Lang("signing").openssl_error_string());
  1479. }
  1480. } catch (phpmailerException $e) {
  1481. $body = '';
  1482. if ($this->exceptions) {
  1483. throw $e;
  1484. }
  1485. }
  1486. }
  1487. return $body;
  1488. }
  1489. /**
  1490. * Returns the start of a message boundary.
  1491. * @access protected
  1492. * @param string $boundary
  1493. * @param string $charSet
  1494. * @param string $contentType
  1495. * @param string $encoding
  1496. * @return string
  1497. */
  1498. protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
  1499. $result = '';
  1500. if($charSet == '') {
  1501. $charSet = $this->CharSet;
  1502. }
  1503. if($contentType == '') {
  1504. $contentType = $this->ContentType;
  1505. }
  1506. if($encoding == '') {
  1507. $encoding = $this->Encoding;
  1508. }
  1509. $result .= $this->TextLine('--' . $boundary);
  1510. $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
  1511. $result .= $this->LE;
  1512. $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
  1513. $result .= $this->LE;
  1514. return $result;
  1515. }
  1516. /**
  1517. * Returns the end of a message boundary.
  1518. * @access protected
  1519. * @param string $boundary
  1520. * @return string
  1521. */
  1522. protected function EndBoundary($boundary) {
  1523. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1524. }
  1525. /**
  1526. * Sets the message type.
  1527. * @access protected
  1528. * @return void
  1529. */
  1530. protected function SetMessageType() {
  1531. $this->message_type = array();
  1532. if($this->AlternativeExists()) $this->message_type[] = "alt";
  1533. if($this->InlineImageExists()) $this->message_type[] = "inline";
  1534. if($this->AttachmentExists()) $this->message_type[] = "attach";
  1535. $this->message_type = implode("_", $this->message_type);
  1536. if($this->message_type == "") $this->message_type = "plain";
  1537. }
  1538. /**
  1539. * Returns a formatted header line.
  1540. * @access public
  1541. * @param string $name
  1542. * @param string $value
  1543. * @return string
  1544. */
  1545. public function HeaderLine($name, $value) {
  1546. return $name . ': ' . $value . $this->LE;
  1547. }
  1548. /**
  1549. * Returns a formatted mail line.
  1550. * @access public
  1551. * @param string $value
  1552. * @return string
  1553. */
  1554. public function TextLine($value) {
  1555. return $value . $this->LE;
  1556. }
  1557. /////////////////////////////////////////////////
  1558. // CLASS METHODS, ATTACHMENTS
  1559. /////////////////////////////////////////////////
  1560. /**
  1561. * Adds an attachment from a path on the filesystem.
  1562. * Returns false if the file could not be found
  1563. * or accessed.
  1564. * @param string $path Path to the attachment.
  1565. * @param string $name Overrides the attachment name.
  1566. * @param string $encoding File encoding (see $Encoding).
  1567. * @param string $type File extension (MIME) type.
  1568. * @throws phpmailerException
  1569. * @return bool
  1570. */
  1571. public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1572. try {
  1573. if ( !@is_file($path) ) {
  1574. throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
  1575. }
  1576. $filename = basename($path);
  1577. if ( $name == '' ) {
  1578. $name = $filename;
  1579. }
  1580. $this->attachment[] = array(
  1581. 0 => $path,
  1582. 1 => $filename,
  1583. 2 => $name,
  1584. 3 => $encoding,
  1585. 4 => $type,
  1586. 5 => false, // isStringAttachment
  1587. 6 => 'attachment',
  1588. 7 => 0
  1589. );
  1590. } catch (phpmailerException $e) {
  1591. $this->SetError($e->getMessage());
  1592. if ($this->exceptions) {
  1593. throw $e;
  1594. }
  1595. if ($this->SMTPDebug) {
  1596. $this->edebug($e->getMessage()."\n");
  1597. }
  1598. if ( $e->getCode() == self::STOP_CRITICAL ) {
  1599. return false;
  1600. }
  1601. }
  1602. return true;
  1603. }
  1604. /**
  1605. * Return the current array of attachments
  1606. * @return array
  1607. */
  1608. public function GetAttachments() {
  1609. return $this->attachment;
  1610. }
  1611. /**
  1612. * Attaches all fs, string, and binary attachments to the message.
  1613. * Returns an empty string on failure.
  1614. * @access protected
  1615. * @param string $disposition_type
  1616. * @param string $boundary
  1617. * @return string
  1618. */
  1619. protected function AttachAll($disposition_type, $boundary) {
  1620. // Return text of body
  1621. $mime = array();
  1622. $cidUniq = array();
  1623. $incl = array();
  1624. // Add all attachments
  1625. foreach ($this->attachment as $attachment) {
  1626. // CHECK IF IT IS A VALID DISPOSITION_FILTER
  1627. if($attachment[6] == $disposition_type) {
  1628. // Check for string attachment
  1629. $string = '';
  1630. $path = '';
  1631. $bString = $attachment[5];
  1632. if ($bString) {
  1633. $string = $attachment[0];
  1634. } else {
  1635. $path = $attachment[0];
  1636. }
  1637. $inclhash = md5(serialize($attachment));
  1638. if (in_array($inclhash, $incl)) { continue; }
  1639. $incl[] = $inclhash;
  1640. $filename = $attachment[1];
  1641. $name = $attachment[2];
  1642. $encoding = $attachment[3];
  1643. $type = $attachment[4];
  1644. $disposition = $attachment[6];
  1645. $cid = $attachment[7];
  1646. if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
  1647. $cidUniq[$cid] = true;
  1648. $mime[] = sprintf("--%s%s", $boundary, $this->LE);
  1649. $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
  1650. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  1651. if($disposition == 'inline') {
  1652. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  1653. }
  1654. $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  1655. // Encode as string attachment
  1656. if($bString) {
  1657. $mime[] = $this->EncodeString($string, $encoding);
  1658. if($this->IsError()) {
  1659. return '';
  1660. }
  1661. $mime[] = $this->LE.$this->LE;
  1662. } else {
  1663. $mime[] = $this->EncodeFile($path, $encoding);
  1664. if($this->IsError()) {
  1665. return '';
  1666. }
  1667. $mime[] = $this->LE.$this->LE;
  1668. }
  1669. }
  1670. }
  1671. $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
  1672. return implode("", $mime);
  1673. }
  1674. /**
  1675. * Encodes attachment in requested format.
  1676. * Returns an empty string on failure.
  1677. * @param string $path The full path to the file
  1678. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1679. * @throws phpmailerException
  1680. * @see EncodeFile()
  1681. * @access protected
  1682. * @return string
  1683. */
  1684. protected function EncodeFile($path, $encoding = 'base64') {
  1685. try {
  1686. if (!is_readable($path)) {
  1687. throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
  1688. }
  1689. // if (!function_exists('get_magic_quotes')) {
  1690. // function get_magic_quotes() {
  1691. // return false;
  1692. // }
  1693. // }
  1694. $magic_quotes = get_magic_quotes_runtime();
  1695. if ($magic_quotes) {
  1696. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1697. set_magic_quotes_runtime(0);
  1698. } else {
  1699. ini_set('magic_quotes_runtime', 0);
  1700. }
  1701. }
  1702. $file_buffer = file_get_contents($path);
  1703. $file_buffer = $this->EncodeString($file_buffer, $encoding);
  1704. if ($magic_quotes) {
  1705. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1706. set_magic_quotes_runtime($magic_quotes);
  1707. } else {
  1708. ini_set('magic_quotes_runtime', $magic_quotes);
  1709. }
  1710. }
  1711. return $file_buffer;
  1712. } catch (Exception $e) {
  1713. $this->SetError($e->getMessage());
  1714. return '';
  1715. }
  1716. }
  1717. /**
  1718. * Encodes string to requested format.
  1719. * Returns an empty string on failure.
  1720. * @param string $str The text to encode
  1721. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1722. * @access public
  1723. * @return string
  1724. */
  1725. public function EncodeString($str, $encoding = 'base64') {
  1726. $encoded = '';
  1727. switch(strtolower($encoding)) {
  1728. case 'base64':
  1729. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1730. break;
  1731. case '7bit':
  1732. case '8bit':
  1733. $encoded = $this->FixEOL($str);
  1734. //Make sure it ends with a line break
  1735. if (substr($encoded, -(strlen($this->LE))) != $this->LE)
  1736. $encoded .= $this->LE;
  1737. break;
  1738. case 'binary':
  1739. $encoded = $str;
  1740. break;
  1741. case 'quoted-printable':
  1742. $encoded = $this->EncodeQP($str);
  1743. break;
  1744. default:
  1745. $this->SetError($this->Lang('encoding') . $encoding);
  1746. break;
  1747. }
  1748. return $encoded;
  1749. }
  1750. /**
  1751. * Encode a header string to best (shortest) of Q, B, quoted or none.
  1752. * @access public
  1753. * @param string $str
  1754. * @param string $position
  1755. * @return string
  1756. */
  1757. public function EncodeHeader($str, $position = 'text') {
  1758. $x = 0;
  1759. switch (strtolower($position)) {
  1760. case 'phrase':
  1761. if (!preg_match('/[\200-\377]/', $str)) {
  1762. // Can't use addslashes as we don't know what value has magic_quotes_sybase
  1763. $encoded = addcslashes($str, "\0..\37\177\\\"");
  1764. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  1765. return ($encoded);
  1766. } else {
  1767. return ("\"$encoded\"");
  1768. }
  1769. }
  1770. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1771. break;
  1772. case 'comment':
  1773. $x = preg_match_all('/[()"]/', $str, $matches);
  1774. // Fall-through
  1775. case 'text':
  1776. default:
  1777. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1778. break;
  1779. }
  1780. if ($x == 0) {
  1781. return ($str);
  1782. }
  1783. $maxlen = 75 - 7 - strlen($this->CharSet);
  1784. // Try to select the encoding which should produce the shortest output
  1785. if (strlen($str)/3 < $x) {
  1786. $encoding = 'B';
  1787. if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
  1788. // Use a custom function which correctly encodes and wraps long
  1789. // multibyte strings without breaking lines within a character
  1790. $encoded = $this->Base64EncodeWrapMB($str, "\n");
  1791. } else {
  1792. $encoded = base64_encode($str);
  1793. $maxlen -= $maxlen % 4;
  1794. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1795. }
  1796. } else {
  1797. $encoding = 'Q';
  1798. $encoded = $this->EncodeQ($str, $position);
  1799. $encoded = $this->WrapText($encoded, $maxlen, true);
  1800. $encoded = str_replace('='.self::CRLF, "\n", trim($encoded));
  1801. }
  1802. $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
  1803. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1804. return $encoded;
  1805. }
  1806. /**
  1807. * Checks if a string contains multibyte characters.
  1808. * @access public
  1809. * @param string $str multi-byte text to wrap encode
  1810. * @return bool
  1811. */
  1812. public function HasMultiBytes($str) {
  1813. if (function_exists('mb_strlen')) {
  1814. return (strlen($str) > mb_strlen($str, $this->CharSet));
  1815. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1816. return false;
  1817. }
  1818. }
  1819. /**
  1820. * Correctly encodes and wraps long multibyte strings for mail headers
  1821. * without breaking lines within a character.
  1822. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
  1823. * @access public
  1824. * @param string $str multi-byte text to wrap encode
  1825. * @param string $lf string to use as linefeed/end-of-line
  1826. * @return string
  1827. */
  1828. public function Base64EncodeWrapMB($str, $lf=null) {
  1829. $start = "=?".$this->CharSet."?B?";
  1830. $end = "?=";
  1831. $encoded = "";
  1832. if ($lf === null) {
  1833. $lf = $this->LE;
  1834. }
  1835. $mb_length = mb_strlen($str, $this->CharSet);
  1836. // Each line must have length <= 75, including $start and $end
  1837. $length = 75 - strlen($start) - strlen($end);
  1838. // Average multi-byte ratio
  1839. $ratio = $mb_length / strlen($str);
  1840. // Base64 has a 4:3 ratio
  1841. $offset = $avgLength = floor($length * $ratio * .75);
  1842. for ($i = 0; $i < $mb_length; $i += $offset) {
  1843. $lookBack = 0;
  1844. do {
  1845. $offset = $avgLength - $lookBack;
  1846. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1847. $chunk = base64_encode($chunk);
  1848. $lookBack++;
  1849. }
  1850. while (strlen($chunk) > $length);
  1851. $encoded .= $chunk . $lf;
  1852. }
  1853. // Chomp the last linefeed
  1854. $encoded = substr($encoded, 0, -strlen($lf));
  1855. return $encoded;
  1856. }
  1857. /**
  1858. * Encode string to quoted-printable.
  1859. * Only uses standard PHP, slow, but will always work
  1860. * @access public
  1861. * @param string $input
  1862. * @param integer $line_max Number of chars allowed on a line before wrapping
  1863. * @param bool $space_conv
  1864. * @internal param string $string the text to encode
  1865. * @return string
  1866. */
  1867. public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
  1868. $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
  1869. $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
  1870. $eol = "\r\n";
  1871. $escape = '=';
  1872. $output = '';
  1873. while( list(, $line) = each($lines) ) {
  1874. $linlen = strlen($line);
  1875. $newline = '';
  1876. for($i = 0; $i < $linlen; $i++) {
  1877. $c = substr( $line, $i, 1 );
  1878. $dec = ord( $c );
  1879. if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
  1880. $c = '=2E';
  1881. }
  1882. if ( $dec == 32 ) {
  1883. if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
  1884. $c = '=20';
  1885. } else if ( $space_conv ) {
  1886. $c = '=20';
  1887. }
  1888. } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
  1889. $h2 = (integer)floor($dec/16);
  1890. $h1 = (integer)floor($dec%16);
  1891. $c = $escape.$hex[$h2].$hex[$h1];
  1892. }
  1893. if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
  1894. $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
  1895. $newline = '';
  1896. // check if newline first character will be point or not
  1897. if ( $dec == 46 ) {
  1898. $c = '=2E';
  1899. }
  1900. }
  1901. $newline .= $c;
  1902. } // end of for
  1903. $output .= $newline.$eol;
  1904. } // end of while
  1905. return $output;
  1906. }
  1907. /**
  1908. * Encode string to RFC2045 (6.7) quoted-printable format
  1909. * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
  1910. * Also results in same content as you started with after decoding
  1911. * @see EncodeQPphp()
  1912. * @access public
  1913. * @param string $string the text to encode
  1914. * @param integer $line_max Number of chars allowed on a line before wrapping
  1915. * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
  1916. * @return string
  1917. * @author Marcus Bointon
  1918. */
  1919. public function EncodeQP($string, $line_max = 76, $space_conv = false) {
  1920. if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
  1921. return quoted_printable_encode($string);
  1922. }
  1923. $filters = stream_get_filters();
  1924. if (!in_array('convert.*', $filters)) { //Got convert stream filter?
  1925. return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
  1926. }
  1927. $fp = fopen('php://temp/', 'r+');
  1928. $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
  1929. $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE);
  1930. $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
  1931. fputs($fp, $string);
  1932. rewind($fp);
  1933. $out = stream_get_contents($fp);
  1934. stream_filter_remove($s);
  1935. $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
  1936. fclose($fp);
  1937. return $out;
  1938. }
  1939. /**
  1940. * Encode string to q encoding.
  1941. * @link http://tools.ietf.org/html/rfc2047
  1942. * @param string $str the text to encode
  1943. * @param string $position Where the text is going to be used, see the RFC for what that means
  1944. * @access public
  1945. * @return string
  1946. */
  1947. public function EncodeQ($str, $position = 'text') {
  1948. //There should not be any EOL in the string
  1949. $pattern="";
  1950. $encoded = str_replace(array("\r", "\n"), '', $str);
  1951. switch (strtolower($position)) {
  1952. case 'phrase':
  1953. $pattern = '^A-Za-z0-9!*+\/ -';
  1954. break;
  1955. case 'comment':
  1956. $pattern = '\(\)"';
  1957. //note that we dont break here!
  1958. //for this reason we build the $pattern withoud including delimiters and []
  1959. case 'text':
  1960. default:
  1961. //Replace every high ascii, control =, ? and _ characters
  1962. //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode
  1963. $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern;
  1964. break;
  1965. }
  1966. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  1967. foreach (array_unique($matches[0]) as $char) {
  1968. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  1969. }
  1970. }
  1971. //Replace every spaces to _ (more readable than =20)
  1972. return str_replace(' ', '_', $encoded);
  1973. }
  1974. /**
  1975. * Adds a string or binary attachment (non-filesystem) to the list.
  1976. * This method can be used to attach ascii or binary data,
  1977. * such as a BLOB record from a database.
  1978. * @param string $string String attachment data.
  1979. * @param string $filename Name of the attachment.
  1980. * @param string $encoding File encoding (see $Encoding).
  1981. * @param string $type File extension (MIME) type.
  1982. * @return void
  1983. */
  1984. public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
  1985. // Append to $attachment array
  1986. $this->attachment[] = array(
  1987. 0 => $string,
  1988. 1 => $filename,
  1989. 2 => basename($filename),
  1990. 3 => $encoding,
  1991. 4 => $type,
  1992. 5 => true, // isStringAttachment
  1993. 6 => 'attachment',
  1994. 7 => 0
  1995. );
  1996. }
  1997. /**
  1998. * Adds an embedded attachment. This can include images, sounds, and
  1999. * just about any other document. Make sure to set the $type to an
  2000. * image type. For JPEG images use "image/jpeg" and for GIF images
  2001. * use "image/gif".
  2002. * @param string $path Path to the attachment.
  2003. * @param string $cid Content ID of the attachment. Use this to identify
  2004. * the Id for accessing the image in an HTML form.
  2005. * @param string $name Overrides the attachment name.
  2006. * @param string $encoding File encoding (see $Encoding).
  2007. * @param string $type File extension (MIME) type.
  2008. * @return bool
  2009. */
  2010. public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  2011. if ( !@is_file($path) ) {
  2012. $this->SetError($this->Lang('file_access') . $path);
  2013. return false;
  2014. }
  2015. $filename = basename($path);
  2016. if ( $name == '' ) {
  2017. $name = $filename;
  2018. }
  2019. // Append to $attachment array
  2020. $this->attachment[] = array(
  2021. 0 => $path,
  2022. 1 => $filename,
  2023. 2 => $name,
  2024. 3 => $encoding,
  2025. 4 => $type,
  2026. 5 => false, // isStringAttachment
  2027. 6 => 'inline',
  2028. 7 => $cid
  2029. );
  2030. return true;
  2031. }
  2032. /**
  2033. * Adds an embedded stringified attachment. This can include images, sounds, and
  2034. * just about any other document. Make sure to set the $type to an
  2035. * image type. For JPEG images use "image/jpeg" and for GIF images
  2036. * use "image/gif".
  2037. * @param string $string The attachment.
  2038. * @param string $cid Content ID of the attachment. Use this to identify
  2039. * the Id for accessing the image in an HTML form.
  2040. * @param string $name Overrides the attachment name.
  2041. * @param string $encoding File encoding (see $Encoding).
  2042. * @param string $type File extension (MIME) type.
  2043. * @return bool
  2044. */
  2045. public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  2046. // Append to $attachment array
  2047. $this->attachment[] = array(
  2048. 0 => $string,
  2049. 1 => $name,
  2050. 2 => $name,
  2051. 3 => $encoding,
  2052. 4 => $type,
  2053. 5 => true, // isStringAttachment
  2054. 6 => 'inline',
  2055. 7 => $cid
  2056. );
  2057. }
  2058. /**
  2059. * Returns true if an inline attachment is present.
  2060. * @access public
  2061. * @return bool
  2062. */
  2063. public function InlineImageExists() {
  2064. foreach($this->attachment as $attachment) {
  2065. if ($attachment[6] == 'inline') {
  2066. return true;
  2067. }
  2068. }
  2069. return false;
  2070. }
  2071. /**
  2072. * Returns true if an attachment (non-inline) is present.
  2073. * @return bool
  2074. */
  2075. public function AttachmentExists() {
  2076. foreach($this->attachment as $attachment) {
  2077. if ($attachment[6] == 'attachment') {
  2078. return true;
  2079. }
  2080. }
  2081. return false;
  2082. }
  2083. /**
  2084. * Does this message have an alternative body set?
  2085. * @return bool
  2086. */
  2087. public function AlternativeExists() {
  2088. return !empty($this->AltBody);
  2089. }
  2090. /////////////////////////////////////////////////
  2091. // CLASS METHODS, MESSAGE RESET
  2092. /////////////////////////////////////////////////
  2093. /**
  2094. * Clears all recipients assigned in the TO array. Returns void.
  2095. * @return void
  2096. */
  2097. public function ClearAddresses() {
  2098. foreach($this->to as $to) {
  2099. unset($this->all_recipients[strtolower($to[0])]);
  2100. }
  2101. $this->to = array();
  2102. }
  2103. /**
  2104. * Clears all recipients assigned in the CC array. Returns void.
  2105. * @return void
  2106. */
  2107. public function ClearCCs() {
  2108. foreach($this->cc as $cc) {
  2109. unset($this->all_recipients[strtolower($cc[0])]);
  2110. }
  2111. $this->cc = array();
  2112. }
  2113. /**
  2114. * Clears all recipients assigned in the BCC array. Returns void.
  2115. * @return void
  2116. */
  2117. public function ClearBCCs() {
  2118. foreach($this->bcc as $bcc) {
  2119. unset($this->all_recipients[strtolower($bcc[0])]);
  2120. }
  2121. $this->bcc = array();
  2122. }
  2123. /**
  2124. * Clears all recipients assigned in the ReplyTo array. Returns void.
  2125. * @return void
  2126. */
  2127. public function ClearReplyTos() {
  2128. $this->ReplyTo = array();
  2129. }
  2130. /**
  2131. * Clears all recipients assigned in the TO, CC and BCC
  2132. * array. Returns void.
  2133. * @return void
  2134. */
  2135. public function ClearAllRecipients() {
  2136. $this->to = array();
  2137. $this->cc = array();
  2138. $this->bcc = array();
  2139. $this->all_recipients = array();
  2140. }
  2141. /**
  2142. * Clears all previously set filesystem, string, and binary
  2143. * attachments. Returns void.
  2144. * @return void
  2145. */
  2146. public function ClearAttachments() {
  2147. $this->attachment = array();
  2148. }
  2149. /**
  2150. * Clears all custom headers. Returns void.
  2151. * @return void
  2152. */
  2153. public function ClearCustomHeaders() {
  2154. $this->CustomHeader = array();
  2155. }
  2156. /////////////////////////////////////////////////
  2157. // CLASS METHODS, MISCELLANEOUS
  2158. /////////////////////////////////////////////////
  2159. /**
  2160. * Adds the error message to the error container.
  2161. * @access protected
  2162. * @param string $msg
  2163. * @return void
  2164. */
  2165. protected function SetError($msg) {
  2166. $this->error_count++;
  2167. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  2168. $lasterror = $this->smtp->getError();
  2169. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  2170. $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
  2171. }
  2172. }
  2173. $this->ErrorInfo = $msg;
  2174. }
  2175. /**
  2176. * Returns the proper RFC 822 formatted date.
  2177. * @access public
  2178. * @return string
  2179. * @static
  2180. */
  2181. public static function RFCDate() {
  2182. $tz = date('Z');
  2183. $tzs = ($tz < 0) ? '-' : '+';
  2184. $tz = abs($tz);
  2185. $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
  2186. $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
  2187. return $result;
  2188. }
  2189. /**
  2190. * Returns the server hostname or 'localhost.localdomain' if unknown.
  2191. * @access protected
  2192. * @return string
  2193. */
  2194. protected function ServerHostname() {
  2195. if (!empty($this->Hostname)) {
  2196. $result = $this->Hostname;
  2197. } elseif (isset($_SERVER['SERVER_NAME'])) {
  2198. $result = $_SERVER['SERVER_NAME'];
  2199. } else {
  2200. $result = 'localhost.localdomain';
  2201. }
  2202. return $result;
  2203. }
  2204. /**
  2205. * Returns a message in the appropriate language.
  2206. * @access protected
  2207. * @param string $key
  2208. * @return string
  2209. */
  2210. protected function Lang($key) {
  2211. if(count($this->language) < 1) {
  2212. $this->SetLanguage('en'); // set the default language
  2213. }
  2214. if(isset($this->language[$key])) {
  2215. return $this->language[$key];
  2216. } else {
  2217. return 'Language string failed to load: ' . $key;
  2218. }
  2219. }
  2220. /**
  2221. * Returns true if an error occurred.
  2222. * @access public
  2223. * @return bool
  2224. */
  2225. public function IsError() {
  2226. return ($this->error_count > 0);
  2227. }
  2228. /**
  2229. * Changes every end of line from CRLF, CR or LF to $this->LE.
  2230. * @access public
  2231. * @param string $str String to FixEOL
  2232. * @return string
  2233. */
  2234. public function FixEOL($str) {
  2235. // condense down to \n
  2236. $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  2237. // Now convert LE as needed
  2238. if ($this->LE !== "\n") {
  2239. $nstr = str_replace("\n", $this->LE, $nstr);
  2240. }
  2241. return $nstr;
  2242. }
  2243. /**
  2244. * Adds a custom header. $name value can be overloaded to contain
  2245. * both header name and value (name:value)
  2246. * @access public
  2247. * @param string $name custom header name
  2248. * @param string $value header value
  2249. * @return void
  2250. */
  2251. public function AddCustomHeader($name, $value=null) {
  2252. if ($value === null) {
  2253. // Value passed in as name:value
  2254. $this->CustomHeader[] = explode(':', $name, 2);
  2255. } else {
  2256. $this->CustomHeader[] = array($name, $value);
  2257. }
  2258. }
  2259. /**
  2260. * Evaluates the message and returns modifications for inline images and backgrounds
  2261. * @access public
  2262. * @param string $message Text to be HTML modified
  2263. * @param string $basedir baseline directory for path
  2264. * @return string $message
  2265. */
  2266. public function MsgHTML($message, $basedir = '') {
  2267. preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images);
  2268. if(isset($images[2])) {
  2269. foreach($images[2] as $i => $url) {
  2270. // do not change urls for absolute images (thanks to corvuscorax)
  2271. if (!preg_match('#^[A-z]+://#', $url)) {
  2272. $filename = basename($url);
  2273. $directory = dirname($url);
  2274. if ($directory == '.') {
  2275. $directory = '';
  2276. }
  2277. $cid = 'cid:' . md5($url);
  2278. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  2279. $mimeType = self::_mime_types($ext);
  2280. if ( strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; }
  2281. if ( strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; }
  2282. if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($url), $filename, 'base64', $mimeType) ) {
  2283. $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"".$cid."\"", $message);
  2284. }
  2285. }
  2286. }
  2287. }
  2288. $this->IsHTML(true);
  2289. $this->Body = $message;
  2290. if (empty($this->AltBody)) {
  2291. $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
  2292. if (!empty($textMsg)) {
  2293. $this->AltBody = html_entity_decode($textMsg, ENT_QUOTES, $this->CharSet);
  2294. }
  2295. }
  2296. if (empty($this->AltBody)) {
  2297. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
  2298. }
  2299. return $message;
  2300. }
  2301. /**
  2302. * Gets the MIME type of the embedded or inline image
  2303. * @param string $ext File extension
  2304. * @access public
  2305. * @return string MIME type of ext
  2306. * @static
  2307. */
  2308. public static function _mime_types($ext = '') {
  2309. $mimes = array(
  2310. 'xl' => 'application/excel',
  2311. 'hqx' => 'application/mac-binhex40',
  2312. 'cpt' => 'application/mac-compactpro',
  2313. 'bin' => 'application/macbinary',
  2314. 'doc' => 'application/msword',
  2315. 'word' => 'application/msword',
  2316. 'class' => 'application/octet-stream',
  2317. 'dll' => 'application/octet-stream',
  2318. 'dms' => 'application/octet-stream',
  2319. 'exe' => 'application/octet-stream',
  2320. 'lha' => 'application/octet-stream',
  2321. 'lzh' => 'application/octet-stream',
  2322. 'psd' => 'application/octet-stream',
  2323. 'sea' => 'application/octet-stream',
  2324. 'so' => 'application/octet-stream',
  2325. 'oda' => 'application/oda',
  2326. 'pdf' => 'application/pdf',
  2327. 'ai' => 'application/postscript',
  2328. 'eps' => 'application/postscript',
  2329. 'ps' => 'application/postscript',
  2330. 'smi' => 'application/smil',
  2331. 'smil' => 'application/smil',
  2332. 'mif' => 'application/vnd.mif',
  2333. 'xls' => 'application/vnd.ms-excel',
  2334. 'ppt' => 'application/vnd.ms-powerpoint',
  2335. 'wbxml' => 'application/vnd.wap.wbxml',
  2336. 'wmlc' => 'application/vnd.wap.wmlc',
  2337. 'dcr' => 'application/x-director',
  2338. 'dir' => 'application/x-director',
  2339. 'dxr' => 'application/x-director',
  2340. 'dvi' => 'application/x-dvi',
  2341. 'gtar' => 'application/x-gtar',
  2342. 'php3' => 'application/x-httpd-php',
  2343. 'php4' => 'application/x-httpd-php',
  2344. 'php' => 'application/x-httpd-php',
  2345. 'phtml' => 'application/x-httpd-php',
  2346. 'phps' => 'application/x-httpd-php-source',
  2347. 'js' => 'application/x-javascript',
  2348. 'swf' => 'application/x-shockwave-flash',
  2349. 'sit' => 'application/x-stuffit',
  2350. 'tar' => 'application/x-tar',
  2351. 'tgz' => 'application/x-tar',
  2352. 'xht' => 'application/xhtml+xml',
  2353. 'xhtml' => 'application/xhtml+xml',
  2354. 'zip' => 'application/zip',
  2355. 'mid' => 'audio/midi',
  2356. 'midi' => 'audio/midi',
  2357. 'mp2' => 'audio/mpeg',
  2358. 'mp3' => 'audio/mpeg',
  2359. 'mpga' => 'audio/mpeg',
  2360. 'aif' => 'audio/x-aiff',
  2361. 'aifc' => 'audio/x-aiff',
  2362. 'aiff' => 'audio/x-aiff',
  2363. 'ram' => 'audio/x-pn-realaudio',
  2364. 'rm' => 'audio/x-pn-realaudio',
  2365. 'rpm' => 'audio/x-pn-realaudio-plugin',
  2366. 'ra' => 'audio/x-realaudio',
  2367. 'wav' => 'audio/x-wav',
  2368. 'bmp' => 'image/bmp',
  2369. 'gif' => 'image/gif',
  2370. 'jpeg' => 'image/jpeg',
  2371. 'jpe' => 'image/jpeg',
  2372. 'jpg' => 'image/jpeg',
  2373. 'png' => 'image/png',
  2374. 'tiff' => 'image/tiff',
  2375. 'tif' => 'image/tiff',
  2376. 'eml' => 'message/rfc822',
  2377. 'css' => 'text/css',
  2378. 'html' => 'text/html',
  2379. 'htm' => 'text/html',
  2380. 'shtml' => 'text/html',
  2381. 'log' => 'text/plain',
  2382. 'text' => 'text/plain',
  2383. 'txt' => 'text/plain',
  2384. 'rtx' => 'text/richtext',
  2385. 'rtf' => 'text/rtf',
  2386. 'xml' => 'text/xml',
  2387. 'xsl' => 'text/xml',
  2388. 'mpeg' => 'video/mpeg',
  2389. 'mpe' => 'video/mpeg',
  2390. 'mpg' => 'video/mpeg',
  2391. 'mov' => 'video/quicktime',
  2392. 'qt' => 'video/quicktime',
  2393. 'rv' => 'video/vnd.rn-realvideo',
  2394. 'avi' => 'video/x-msvideo',
  2395. 'movie' => 'video/x-sgi-movie'
  2396. );
  2397. return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
  2398. }
  2399. /**
  2400. * Set (or reset) Class Objects (variables)
  2401. *
  2402. * Usage Example:
  2403. * $page->set('X-Priority', '3');
  2404. *
  2405. * @access public
  2406. * @param string $name Parameter Name
  2407. * @param mixed $value Parameter Value
  2408. * NOTE: will not work with arrays, there are no arrays to set/reset
  2409. * @throws phpmailerException
  2410. * @return bool
  2411. * @todo Should this not be using __set() magic function?
  2412. */
  2413. public function set($name, $value = '') {
  2414. try {
  2415. if (isset($this->$name) ) {
  2416. $this->$name = $value;
  2417. } else {
  2418. throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
  2419. }
  2420. } catch (Exception $e) {
  2421. $this->SetError($e->getMessage());
  2422. if ($e->getCode() == self::STOP_CRITICAL) {
  2423. return false;
  2424. }
  2425. }
  2426. return true;
  2427. }
  2428. /**
  2429. * Strips newlines to prevent header injection.
  2430. * @access public
  2431. * @param string $str String
  2432. * @return string
  2433. */
  2434. public function SecureHeader($str) {
  2435. return trim(str_replace(array("\r", "\n"), '', $str));
  2436. }
  2437. /**
  2438. * Set the private key file and password to sign the message.
  2439. *
  2440. * @access public
  2441. * @param $cert_filename
  2442. * @param string $key_filename Parameter File Name
  2443. * @param string $key_pass Password for private key
  2444. */
  2445. public function Sign($cert_filename, $key_filename, $key_pass) {
  2446. $this->sign_cert_file = $cert_filename;
  2447. $this->sign_key_file = $key_filename;
  2448. $this->sign_key_pass = $key_pass;
  2449. }
  2450. /**
  2451. * Set the private key file and password to sign the message.
  2452. *
  2453. * @access public
  2454. * @param string $txt
  2455. * @return string
  2456. */
  2457. public function DKIM_QP($txt) {
  2458. $line = '';
  2459. for ($i = 0; $i < strlen($txt); $i++) {
  2460. $ord = ord($txt[$i]);
  2461. if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
  2462. $line .= $txt[$i];
  2463. } else {
  2464. $line .= "=".sprintf("%02X", $ord);
  2465. }
  2466. }
  2467. return $line;
  2468. }
  2469. /**
  2470. * Generate DKIM signature
  2471. *
  2472. * @access public
  2473. * @param string $s Header
  2474. * @return string
  2475. */
  2476. public function DKIM_Sign($s) {
  2477. $privKeyStr = file_get_contents($this->DKIM_private);
  2478. if ($this->DKIM_passphrase != '') {
  2479. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  2480. } else {
  2481. $privKey = $privKeyStr;
  2482. }
  2483. if (openssl_sign($s, $signature, $privKey)) {
  2484. return base64_encode($signature);
  2485. }
  2486. return '';
  2487. }
  2488. /**
  2489. * Generate DKIM Canonicalization Header
  2490. *
  2491. * @access public
  2492. * @param string $s Header
  2493. * @return string
  2494. */
  2495. public function DKIM_HeaderC($s) {
  2496. $s = preg_replace("/\r\n\s+/", " ", $s);
  2497. $lines = explode("\r\n", $s);
  2498. foreach ($lines as $key => $line) {
  2499. list($heading, $value) = explode(":", $line, 2);
  2500. $heading = strtolower($heading);
  2501. $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces
  2502. $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value
  2503. }
  2504. $s = implode("\r\n", $lines);
  2505. return $s;
  2506. }
  2507. /**
  2508. * Generate DKIM Canonicalization Body
  2509. *
  2510. * @access public
  2511. * @param string $body Message Body
  2512. * @return string
  2513. */
  2514. public function DKIM_BodyC($body) {
  2515. if ($body == '') return "\r\n";
  2516. // stabilize line endings
  2517. $body = str_replace("\r\n", "\n", $body);
  2518. $body = str_replace("\n", "\r\n", $body);
  2519. // END stabilize line endings
  2520. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  2521. $body = substr($body, 0, strlen($body) - 2);
  2522. }
  2523. return $body;
  2524. }
  2525. /**
  2526. * Create the DKIM header, body, as new header
  2527. *
  2528. * @access public
  2529. * @param string $headers_line Header lines
  2530. * @param string $subject Subject
  2531. * @param string $body Body
  2532. * @return string
  2533. */
  2534. public function DKIM_Add($headers_line, $subject, $body) {
  2535. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  2536. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  2537. $DKIMquery = 'dns/txt'; // Query method
  2538. $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  2539. $subject_header = "Subject: $subject";
  2540. $headers = explode($this->LE, $headers_line);
  2541. $from_header = "";
  2542. $to_header = "";
  2543. foreach($headers as $header) {
  2544. if (strpos($header, 'From:') === 0) {
  2545. $from_header = $header;
  2546. } elseif (strpos($header, 'To:') === 0) {
  2547. $to_header = $header;
  2548. }
  2549. }
  2550. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  2551. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  2552. $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
  2553. $body = $this->DKIM_BodyC($body);
  2554. $DKIMlen = strlen($body) ; // Length of body
  2555. $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
  2556. $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
  2557. $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
  2558. "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
  2559. "\th=From:To:Subject;\r\n".
  2560. "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
  2561. "\tz=$from\r\n".
  2562. "\t|$to\r\n".
  2563. "\t|$subject;\r\n".
  2564. "\tbh=" . $DKIMb64 . ";\r\n".
  2565. "\tb=";
  2566. $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
  2567. $signed = $this->DKIM_Sign($toSign);
  2568. return "X-PHPMAILER-DKIM: code.google.com/a/apache-extras.org/p/phpmailer/\r\n".$dkimhdrs.$signed."\r\n";
  2569. }
  2570. /**
  2571. * Perform callback
  2572. * @param boolean $isSent
  2573. * @param string $to
  2574. * @param string $cc
  2575. * @param string $bcc
  2576. * @param string $subject
  2577. * @param string $body
  2578. * @param string $from
  2579. */
  2580. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from=null) {
  2581. if (!empty($this->action_function) && is_callable($this->action_function)) {
  2582. $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  2583. call_user_func_array($this->action_function, $params);
  2584. }
  2585. }
  2586. }
  2587. /**
  2588. * Exception handler for PHPMailer
  2589. * @package PHPMailer
  2590. */
  2591. class phpmailerException extends Exception {
  2592. /**
  2593. * Prettify error message output
  2594. * @return string
  2595. */
  2596. public function errorMessage() {
  2597. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  2598. return $errorMsg;
  2599. }
  2600. }
  2601. ?>