PageRenderTime 103ms CodeModel.GetById 25ms RepoModel.GetById 2ms app.codeStats 0ms

/vendor/PHPMailer/class.phpmailer.php

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