PageRenderTime 65ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/class.phpmailer.php

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