PageRenderTime 57ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/phpmailer/class.phpmailer.php

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