PageRenderTime 70ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/applicationv2/libraries/v2/phpmailer/class.phpmailer.php

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