PageRenderTime 82ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

/_app/vendor/PHPMailer/class.phpmailer.php

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