PageRenderTime 67ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/phpmailer/class.phpmailer.php

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