PageRenderTime 28ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/public_html/lists/admin/PHPMailer-5.2.5/class.phpmailer.php

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