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