Guest User

Untitled

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