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

/greenhouse/wp-includes/class-phpmailer.php

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