]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-phpmailer.php
Wordpress 2.6.2
[autoinstalls/wordpress.git] / wp-includes / class-phpmailer.php
1 <?php
2 /**
3  * PHPMailer - PHP email class
4  *
5  * Class for sending email using either sendmail, PHP mail(), or SMTP. Methods
6  * are based upon the standard AspEmail(tm) classes.
7  *
8  * @copyright 2001 - 2003 Brent R. Matzelle
9  * @license LGPL
10  * @package PHPMailer
11  */
12
13 /**
14  * PHPMailer - PHP email transport class
15  * @package PHPMailer
16  * @author Brent R. Matzelle
17  * @copyright 2001 - 2003 Brent R. Matzelle
18  */
19 class PHPMailer
20 {
21     /////////////////////////////////////////////////
22     // PUBLIC VARIABLES
23     /////////////////////////////////////////////////
24
25     /**
26      * Email priority (1 = High, 3 = Normal, 5 = low).
27      * @var int
28      */
29     var $Priority          = 3;
30
31     /**
32      * Sets the CharSet of the message.
33      * @var string
34      */
35     var $CharSet           = "UTF-8";
36
37     /**
38      * Sets the Content-type of the message.
39      * @var string
40      */
41     var $ContentType        = "text/plain";
42
43     /**
44      * Sets the Encoding of the message. Options for this are "8bit",
45      * "7bit", "binary", "base64", and "quoted-printable".
46      * @var string
47      */
48     var $Encoding          = "8bit";
49
50     /**
51      * Holds the most recent mailer error message.
52      * @var string
53      */
54     var $ErrorInfo         = "";
55
56     /**
57      * Sets the From email address for the message.
58      * @var string
59      */
60     var $From               = "localhost.localdomain";
61
62     /**
63      * Sets the From name of the message.
64      * @var string
65      */
66     var $FromName           = "Support";
67
68     /**
69      * Sets the Sender email (Return-Path) of the message.  If not empty,
70      * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
71      * @var string
72      */
73     var $Sender            = "";
74
75     /**
76      * Sets the Subject of the message.
77      * @var string
78      */
79     var $Subject           = "";
80
81     /**
82      * Sets the Body of the message.  This can be either an HTML or text body.
83      * If HTML then run IsHTML(true).
84      * @var string
85      */
86     var $Body               = "";
87
88     /**
89      * Sets the text-only body of the message.  This automatically sets the
90      * email to multipart/alternative.  This body can be read by mail
91      * clients that do not have HTML email capability such as mutt. Clients
92      * that can read HTML will view the normal Body.
93      * @var string
94      */
95     var $AltBody           = "";
96
97     /**
98      * Sets word wrapping on the body of the message to a given number of
99      * characters.
100      * @var int
101      */
102     var $WordWrap          = 0;
103
104     /**
105      * Method to send mail: ("mail", "sendmail", or "smtp").
106      * @var string
107      */
108     var $Mailer            = "mail";
109
110     /**
111      * Sets the path of the sendmail program.
112      * @var string
113      */
114     var $Sendmail          = "/usr/sbin/sendmail";
115
116     /**
117      * Path to PHPMailer plugins.  This is now only useful if the SMTP class
118      * is in a different directory than the PHP include path.
119      * @var string
120      */
121     var $PluginDir         = "";
122
123     /**
124      *  Holds PHPMailer version.
125      *  @var string
126      */
127     var $Version           = "1.73";
128
129     /**
130      * Sets the email address that a reading confirmation will be sent.
131      * @var string
132      */
133     var $ConfirmReadingTo  = "";
134
135     /**
136      *  Sets the hostname to use in Message-Id and Received headers
137      *  and as default HELO string. If empty, the value returned
138      *  by SERVER_NAME is used or 'localhost.localdomain'.
139      *  @var string
140      */
141     var $Hostname          = "";
142
143     /////////////////////////////////////////////////
144     // SMTP VARIABLES
145     /////////////////////////////////////////////////
146
147     /**
148      *  Sets the SMTP hosts.  All hosts must be separated by a
149      *  semicolon.  You can also specify a different port
150      *  for each host by using this format: [hostname:port]
151      *  (e.g. "smtp1.example.com:25;smtp2.example.com").
152      *  Hosts will be tried in order.
153      *  @var string
154      */
155     var $Host        = "localhost";
156
157     /**
158      *  Sets the default SMTP server port.
159      *  @var int
160      */
161     var $Port        = 25;
162
163     /**
164      *  Sets the SMTP HELO of the message (Default is $Hostname).
165      *  @var string
166      */
167     var $Helo        = "";
168
169     /**
170      *  Sets SMTP authentication. Utilizes the Username and Password variables.
171      *  @var bool
172      */
173     var $SMTPAuth     = false;
174
175     /**
176      *  Sets SMTP username.
177      *  @var string
178      */
179     var $Username     = "";
180
181     /**
182      *  Sets SMTP password.
183      *  @var string
184      */
185     var $Password     = "";
186
187     /**
188      *  Sets the SMTP server timeout in seconds. This function will not
189      *  work with the win32 version.
190      *  @var int
191      */
192     var $Timeout      = 10;
193
194     /**
195      *  Sets SMTP class debugging on or off.
196      *  @var bool
197      */
198     var $SMTPDebug    = false;
199
200     /**
201      * Prevents the SMTP connection from being closed after each mail
202      * sending.  If this is set to true then to close the connection
203      * requires an explicit call to SmtpClose().
204      * @var bool
205      */
206     var $SMTPKeepAlive = false;
207
208     /**#@+
209      * @access private
210      */
211     var $smtp            = NULL;
212     var $to              = array();
213     var $cc              = array();
214     var $bcc             = array();
215     var $ReplyTo         = array();
216     var $attachment      = array();
217     var $CustomHeader    = array();
218     var $message_type    = "";
219     var $boundary        = array();
220     var $language        = array();
221     var $error_count     = 0;
222     var $LE              = "\n";
223     /**#@-*/
224
225     /////////////////////////////////////////////////
226     // VARIABLE METHODS
227     /////////////////////////////////////////////////
228
229     /**
230      * Sets message type to HTML.
231      * @param bool $bool
232      * @return void
233      */
234     function IsHTML($bool) {
235         if($bool == true)
236             $this->ContentType = "text/html";
237         else
238             $this->ContentType = "text/plain";
239     }
240
241     /**
242      * Sets Mailer to send message using SMTP.
243      * @return void
244      */
245     function IsSMTP() {
246         $this->Mailer = "smtp";
247     }
248
249     /**
250      * Sets Mailer to send message using PHP mail() function.
251      * @return void
252      */
253     function IsMail() {
254         $this->Mailer = "mail";
255     }
256
257     /**
258      * Sets Mailer to send message using the $Sendmail program.
259      * @return void
260      */
261     function IsSendmail() {
262         $this->Mailer = "sendmail";
263     }
264
265     /**
266      * Sets Mailer to send message using the qmail MTA.
267      * @return void
268      */
269     function IsQmail() {
270         $this->Sendmail = "/var/qmail/bin/sendmail";
271         $this->Mailer = "sendmail";
272     }
273
274
275     /////////////////////////////////////////////////
276     // RECIPIENT METHODS
277     /////////////////////////////////////////////////
278
279     /**
280      * Adds a "To" address.
281      * @param string $address
282      * @param string $name
283      * @return void
284      */
285     function AddAddress($address, $name = "") {
286         $cur = count($this->to);
287         $this->to[$cur][0] = trim($address);
288         $this->to[$cur][1] = $name;
289     }
290
291     /**
292      * Adds a "Cc" address. Note: this function works
293      * with the SMTP mailer on win32, not with the "mail"
294      * mailer.
295      * @param string $address
296      * @param string $name
297      * @return void
298     */
299     function AddCC($address, $name = "") {
300         $cur = count($this->cc);
301         $this->cc[$cur][0] = trim($address);
302         $this->cc[$cur][1] = $name;
303     }
304
305     /**
306      * Adds a "Bcc" address. Note: this function works
307      * with the SMTP mailer on win32, not with the "mail"
308      * mailer.
309      * @param string $address
310      * @param string $name
311      * @return void
312      */
313     function AddBCC($address, $name = "") {
314         $cur = count($this->bcc);
315         $this->bcc[$cur][0] = trim($address);
316         $this->bcc[$cur][1] = $name;
317     }
318
319     /**
320      * Adds a "Reply-to" address.
321      * @param string $address
322      * @param string $name
323      * @return void
324      */
325     function AddReplyTo($address, $name = "") {
326         $cur = count($this->ReplyTo);
327         $this->ReplyTo[$cur][0] = trim($address);
328         $this->ReplyTo[$cur][1] = $name;
329     }
330
331
332     /////////////////////////////////////////////////
333     // MAIL SENDING METHODS
334     /////////////////////////////////////////////////
335
336     /**
337      * Creates message and assigns Mailer. If the message is
338      * not sent successfully then it returns false.  Use the ErrorInfo
339      * variable to view description of the error.
340      * @return bool
341      */
342     function Send() {
343         $header = "";
344         $body = "";
345         $result = true;
346
347         if((count($this->to) + count($this->cc) + count($this->bcc)) < 1)
348         {
349             $this->SetError($this->Lang("provide_address"));
350             return false;
351         }
352
353         // Set whether the message is multipart/alternative
354         if(!empty($this->AltBody))
355             $this->ContentType = "multipart/alternative";
356
357         $this->error_count = 0; // reset errors
358         $this->SetMessageType();
359         $header .= $this->CreateHeader();
360         $body = $this->CreateBody();
361
362         if($body == "") { return false; }
363
364         // Choose the mailer
365         switch($this->Mailer)
366         {
367             case "sendmail":
368                 $result = $this->SendmailSend($header, $body);
369                 break;
370             case "mail":
371                 $result = $this->MailSend($header, $body);
372                 break;
373             case "smtp":
374                 $result = $this->SmtpSend($header, $body);
375                 break;
376             default:
377             $this->SetError($this->Mailer . $this->Lang("mailer_not_supported"));
378                 $result = false;
379                 break;
380         }
381
382         return $result;
383     }
384
385     /**
386      * Sends mail using the $Sendmail program.
387      * @access private
388      * @return bool
389      */
390     function SendmailSend($header, $body) {
391         if ($this->Sender != "")
392             $sendmail = sprintf("%s -oi -f %s -t", $this->Sendmail, escapeshellarg($this->Sender));
393         else
394             $sendmail = sprintf("%s -oi -t", $this->Sendmail);
395
396         if(!@$mail = popen($sendmail, "w"))
397         {
398             $this->SetError($this->Lang("execute") . $this->Sendmail);
399             return false;
400         }
401
402         fputs($mail, $header);
403         fputs($mail, $body);
404
405         $result = pclose($mail) >> 8 & 0xFF;
406         if($result != 0)
407         {
408             $this->SetError($this->Lang("execute") . $this->Sendmail);
409             return false;
410         }
411
412         return true;
413     }
414
415     /**
416      * Sends mail using the PHP mail() function.
417      * @access private
418      * @return bool
419      */
420     function MailSend($header, $body) {
421         $to = "";
422         for($i = 0; $i < count($this->to); $i++)
423         {
424             if($i != 0) { $to .= ", "; }
425             $to .= $this->to[$i][0];
426         }
427
428         if ($this->Sender != "" && strlen(ini_get("safe_mode"))< 1)
429         {
430             $old_from = ini_get("sendmail_from");
431             ini_set("sendmail_from", $this->Sender);
432             $params = sprintf("-oi -f %s", $this->Sender);
433             $rt = @mail($to, $this->EncodeHeader($this->Subject), $body,
434                         $header, $params);
435         }
436         else
437             $rt = @mail($to, $this->EncodeHeader($this->Subject), $body, $header);
438
439         if (isset($old_from))
440             ini_set("sendmail_from", $old_from);
441
442         if(!$rt)
443         {
444             $this->SetError($this->Lang("instantiate"));
445             return false;
446         }
447
448         return true;
449     }
450
451     /**
452      * Sends mail via SMTP using PhpSMTP (Author:
453      * Chris Ryan).  Returns bool.  Returns false if there is a
454      * bad MAIL FROM, RCPT, or DATA input.
455      * @access private
456      * @return bool
457      */
458     function SmtpSend($header, $body) {
459         include_once($this->PluginDir . "class-smtp.php");
460         $error = "";
461         $bad_rcpt = array();
462
463         if(!$this->SmtpConnect())
464             return false;
465
466         $smtp_from = ($this->Sender == "") ? $this->From : $this->Sender;
467         if(!$this->smtp->Mail($smtp_from))
468         {
469             $error = $this->Lang("from_failed") . $smtp_from;
470             $this->SetError($error);
471             $this->smtp->Reset();
472             return false;
473         }
474
475         // Attempt to send attach all recipients
476         for($i = 0; $i < count($this->to); $i++)
477         {
478             if(!$this->smtp->Recipient($this->to[$i][0]))
479                 $bad_rcpt[] = $this->to[$i][0];
480         }
481         for($i = 0; $i < count($this->cc); $i++)
482         {
483             if(!$this->smtp->Recipient($this->cc[$i][0]))
484                 $bad_rcpt[] = $this->cc[$i][0];
485         }
486         for($i = 0; $i < count($this->bcc); $i++)
487         {
488             if(!$this->smtp->Recipient($this->bcc[$i][0]))
489                 $bad_rcpt[] = $this->bcc[$i][0];
490         }
491
492         if(count($bad_rcpt) > 0) // Create error message
493         {
494             for($i = 0; $i < count($bad_rcpt); $i++)
495             {
496                 if($i != 0) { $error .= ", "; }
497                 $error .= $bad_rcpt[$i];
498             }
499             $error = $this->Lang("recipients_failed") . $error;
500             $this->SetError($error);
501             $this->smtp->Reset();
502             return false;
503         }
504
505         if(!$this->smtp->Data($header . $body))
506         {
507             $this->SetError($this->Lang("data_not_accepted"));
508             $this->smtp->Reset();
509             return false;
510         }
511         if($this->SMTPKeepAlive == true)
512             $this->smtp->Reset();
513         else
514             $this->SmtpClose();
515
516         return true;
517     }
518
519     /**
520      * Initiates a connection to an SMTP server.  Returns false if the
521      * operation failed.
522      * @access private
523      * @return bool
524      */
525     function SmtpConnect() {
526         if($this->smtp == NULL) { $this->smtp = new SMTP(); }
527
528         $this->smtp->do_debug = $this->SMTPDebug;
529         $hosts = explode(";", $this->Host);
530         $index = 0;
531         $connection = ($this->smtp->Connected());
532
533         // Retry while there is no connection
534         while($index < count($hosts) && $connection == false)
535         {
536             if(strstr($hosts[$index], ":"))
537                 list($host, $port) = explode(":", $hosts[$index]);
538             else
539             {
540                 $host = $hosts[$index];
541                 $port = $this->Port;
542             }
543
544             if($this->smtp->Connect($host, $port, $this->Timeout))
545             {
546                 if ($this->Helo != '')
547                     $this->smtp->Hello($this->Helo);
548                 else
549                     $this->smtp->Hello($this->ServerHostname());
550
551                 if($this->SMTPAuth)
552                 {
553                     if(!$this->smtp->Authenticate($this->Username,
554                                                   $this->Password))
555                     {
556                         $this->SetError($this->Lang("authenticate"));
557                         $this->smtp->Reset();
558                         $connection = false;
559                     }
560                 }
561                 $connection = true;
562             }
563             $index++;
564         }
565         if(!$connection)
566             $this->SetError($this->Lang("connect_host"));
567
568         return $connection;
569     }
570
571     /**
572      * Closes the active SMTP session if one exists.
573      * @return void
574      */
575     function SmtpClose() {
576         if($this->smtp != NULL)
577         {
578             if($this->smtp->Connected())
579             {
580                 $this->smtp->Quit();
581                 $this->smtp->Close();
582             }
583         }
584     }
585
586     /**
587      * Sets the language for all class error messages.  Returns false
588      * if it cannot load the language file.  The default language type
589      * is English.
590      * @param string $lang_type Type of language (e.g. Portuguese: "br")
591      * @param string $lang_path Path to the language file directory
592      * @access public
593      * @return bool
594      */
595     function SetLanguage($lang_type, $lang_path = "language/") {
596         if(file_exists($lang_path.'phpmailer.lang-'.$lang_type.'.php'))
597             include($lang_path.'phpmailer.lang-'.$lang_type.'.php');
598         else if(file_exists($lang_path.'phpmailer.lang-en.php'))
599             include($lang_path.'phpmailer.lang-en.php');
600         else
601         {
602             $this->SetError("Could not load language file");
603             return false;
604         }
605         $this->language = $PHPMAILER_LANG;
606
607         return true;
608     }
609
610     /////////////////////////////////////////////////
611     // MESSAGE CREATION METHODS
612     /////////////////////////////////////////////////
613
614     /**
615      * Creates recipient headers.
616      * @access private
617      * @return string
618      */
619     function AddrAppend($type, $addr) {
620         $addr_str = $type . ": ";
621         $addr_str .= $this->AddrFormat($addr[0]);
622         if(count($addr) > 1)
623         {
624             for($i = 1; $i < count($addr); $i++)
625                 $addr_str .= ", " . $this->AddrFormat($addr[$i]);
626         }
627         $addr_str .= $this->LE;
628
629         return $addr_str;
630     }
631
632     /**
633      * Formats an address correctly.
634      * @access private
635      * @return string
636      */
637     function AddrFormat($addr) {
638         if(empty($addr[1]))
639             $formatted = $addr[0];
640         else
641         {
642             $formatted = $this->EncodeHeader($addr[1], 'phrase') . " <" .
643                          $addr[0] . ">";
644         }
645
646         return $formatted;
647     }
648
649     /**
650      * Wraps message for use with mailers that do not
651      * automatically perform wrapping and for quoted-printable.
652      * Original written by philippe.
653      * @access private
654      * @return string
655      */
656     function WrapText($message, $length, $qp_mode = false) {
657         $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
658
659         $message = $this->FixEOL($message);
660         if (substr($message, -1) == $this->LE)
661             $message = substr($message, 0, -1);
662
663         $line = explode($this->LE, $message);
664         $message = "";
665         for ($i=0 ;$i < count($line); $i++)
666         {
667           $line_part = explode(" ", $line[$i]);
668           $buf = "";
669           for ($e = 0; $e<count($line_part); $e++)
670           {
671               $word = $line_part[$e];
672               if ($qp_mode and (strlen($word) > $length))
673               {
674                 $space_left = $length - strlen($buf) - 1;
675                 if ($e != 0)
676                 {
677                     if ($space_left > 20)
678                     {
679                         $len = $space_left;
680                         if (substr($word, $len - 1, 1) == "=")
681                           $len--;
682                         elseif (substr($word, $len - 2, 1) == "=")
683                           $len -= 2;
684                         $part = substr($word, 0, $len);
685                         $word = substr($word, $len);
686                         $buf .= " " . $part;
687                         $message .= $buf . sprintf("=%s", $this->LE);
688                     }
689                     else
690                     {
691                         $message .= $buf . $soft_break;
692                     }
693                     $buf = "";
694                 }
695                 while (strlen($word) > 0)
696                 {
697                     $len = $length;
698                     if (substr($word, $len - 1, 1) == "=")
699                         $len--;
700                     elseif (substr($word, $len - 2, 1) == "=")
701                         $len -= 2;
702                     $part = substr($word, 0, $len);
703                     $word = substr($word, $len);
704
705                     if (strlen($word) > 0)
706                         $message .= $part . sprintf("=%s", $this->LE);
707                     else
708                         $buf = $part;
709                 }
710               }
711               else
712               {
713                 $buf_o = $buf;
714                 $buf .= ($e == 0) ? $word : (" " . $word);
715
716                 if (strlen($buf) > $length and $buf_o != "")
717                 {
718                     $message .= $buf_o . $soft_break;
719                     $buf = $word;
720                 }
721               }
722           }
723           $message .= $buf . $this->LE;
724         }
725
726         return $message;
727     }
728
729     /**
730      * Set the body wrapping.
731      * @access private
732      * @return void
733      */
734     function SetWordWrap() {
735         if($this->WordWrap < 1)
736             return;
737
738         switch($this->message_type)
739         {
740            case "alt":
741               // fall through
742            case "alt_attachments":
743               $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
744               break;
745            default:
746               $this->Body = $this->WrapText($this->Body, $this->WordWrap);
747               break;
748         }
749     }
750
751     /**
752      * Assembles message header.
753      * @access private
754      * @return string
755      */
756     function CreateHeader() {
757         $result = "";
758
759         // Set the boundaries
760         $uniq_id = md5(uniqid(time()));
761         $this->boundary[1] = "b1_" . $uniq_id;
762         $this->boundary[2] = "b2_" . $uniq_id;
763
764         $result .= $this->HeaderLine("Date", $this->RFCDate());
765         if($this->Sender == "")
766             $result .= $this->HeaderLine("Return-Path", trim($this->From));
767         else
768             $result .= $this->HeaderLine("Return-Path", trim($this->Sender));
769
770         // To be created automatically by mail()
771         if($this->Mailer != "mail")
772         {
773             if(count($this->to) > 0)
774                 $result .= $this->AddrAppend("To", $this->to);
775             else if (count($this->cc) == 0)
776                 $result .= $this->HeaderLine("To", "undisclosed-recipients:;");
777             if(count($this->cc) > 0)
778                 $result .= $this->AddrAppend("Cc", $this->cc);
779         }
780
781         $from = array();
782         $from[0][0] = trim($this->From);
783         $from[0][1] = $this->FromName;
784         $result .= $this->AddrAppend("From", $from);
785
786         // sendmail and mail() extract Bcc from the header before sending
787         if((($this->Mailer == "sendmail") || ($this->Mailer == "mail")) && (count($this->bcc) > 0))
788             $result .= $this->AddrAppend("Bcc", $this->bcc);
789
790         if(count($this->ReplyTo) > 0)
791             $result .= $this->AddrAppend("Reply-to", $this->ReplyTo);
792
793         // mail() sets the subject itself
794         if($this->Mailer != "mail")
795             $result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject)));
796
797         $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
798         $result .= $this->HeaderLine("X-Priority", $this->Priority);
799
800         if($this->ConfirmReadingTo != "")
801         {
802             $result .= $this->HeaderLine("Disposition-Notification-To",
803                        "<" . trim($this->ConfirmReadingTo) . ">");
804         }
805
806         // Add custom headers
807         for($index = 0; $index < count($this->CustomHeader); $index++)
808         {
809             $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]),
810                        $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
811         }
812         $result .= $this->HeaderLine("MIME-Version", "1.0");
813
814         switch($this->message_type)
815         {
816             case "plain":
817                 $result .= $this->HeaderLine("Content-Transfer-Encoding", $this->Encoding);
818                 $result .= sprintf("Content-Type: %s; charset=\"%s\"",
819                                     $this->ContentType, $this->CharSet);
820                 break;
821             case "attachments":
822                 // fall through
823             case "alt_attachments":
824                 if($this->InlineImageExists())
825                 {
826                     $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s",
827                                     "multipart/related", $this->LE, $this->LE,
828                                     $this->boundary[1], $this->LE);
829                 }
830                 else
831                 {
832                     $result .= $this->HeaderLine("Content-Type", "multipart/mixed;");
833                     $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
834                 }
835                 break;
836             case "alt":
837                 $result .= $this->HeaderLine("Content-Type", "multipart/alternative;");
838                 $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
839                 break;
840         }
841
842         if($this->Mailer != "mail")
843             $result .= $this->LE.$this->LE;
844
845         return $result;
846     }
847
848     /**
849      * Assembles the message body.  Returns an empty string on failure.
850      * @access private
851      * @return string
852      */
853     function CreateBody() {
854         $result = "";
855
856         $this->SetWordWrap();
857
858         switch($this->message_type)
859         {
860             case "alt":
861                 $result .= $this->GetBoundary($this->boundary[1], "",
862                                               "text/plain", "");
863                 $result .= $this->EncodeString($this->AltBody, $this->Encoding);
864                 $result .= $this->LE.$this->LE;
865                 $result .= $this->GetBoundary($this->boundary[1], "",
866                                               "text/html", "");
867
868                 $result .= $this->EncodeString($this->Body, $this->Encoding);
869                 $result .= $this->LE.$this->LE;
870
871                 $result .= $this->EndBoundary($this->boundary[1]);
872                 break;
873             case "plain":
874                 $result .= $this->EncodeString($this->Body, $this->Encoding);
875                 break;
876             case "attachments":
877                 $result .= $this->GetBoundary($this->boundary[1], "", "", "");
878                 $result .= $this->EncodeString($this->Body, $this->Encoding);
879                 $result .= $this->LE;
880
881                 $result .= $this->AttachAll();
882                 break;
883             case "alt_attachments":
884                 $result .= sprintf("--%s%s", $this->boundary[1], $this->LE);
885                 $result .= sprintf("Content-Type: %s;%s" .
886                                    "\tboundary=\"%s\"%s",
887                                    "multipart/alternative", $this->LE,
888                                    $this->boundary[2], $this->LE.$this->LE);
889
890                 // Create text body
891                 $result .= $this->GetBoundary($this->boundary[2], "",
892                                               "text/plain", "") . $this->LE;
893
894                 $result .= $this->EncodeString($this->AltBody, $this->Encoding);
895                 $result .= $this->LE.$this->LE;
896
897                 // Create the HTML body
898                 $result .= $this->GetBoundary($this->boundary[2], "",
899                                               "text/html", "") . $this->LE;
900
901                 $result .= $this->EncodeString($this->Body, $this->Encoding);
902                 $result .= $this->LE.$this->LE;
903
904                 $result .= $this->EndBoundary($this->boundary[2]);
905
906                 $result .= $this->AttachAll();
907                 break;
908         }
909         if($this->IsError())
910             $result = "";
911
912         return $result;
913     }
914
915     /**
916      * Returns the start of a message boundary.
917      * @access private
918      */
919     function GetBoundary($boundary, $charSet, $contentType, $encoding) {
920         $result = "";
921         if($charSet == "") { $charSet = $this->CharSet; }
922         if($contentType == "") { $contentType = $this->ContentType; }
923         if($encoding == "") { $encoding = $this->Encoding; }
924
925         $result .= $this->TextLine("--" . $boundary);
926         $result .= sprintf("Content-Type: %s; charset = \"%s\"",
927                             $contentType, $charSet);
928         $result .= $this->LE;
929         $result .= $this->HeaderLine("Content-Transfer-Encoding", $encoding);
930         $result .= $this->LE;
931
932         return $result;
933     }
934
935     /**
936      * Returns the end of a message boundary.
937      * @access private
938      */
939     function EndBoundary($boundary) {
940         return $this->LE . "--" . $boundary . "--" . $this->LE;
941     }
942
943     /**
944      * Sets the message type.
945      * @access private
946      * @return void
947      */
948     function SetMessageType() {
949         if(count($this->attachment) < 1 && strlen($this->AltBody) < 1)
950             $this->message_type = "plain";
951         else
952         {
953             if(count($this->attachment) > 0)
954                 $this->message_type = "attachments";
955             if(strlen($this->AltBody) > 0 && count($this->attachment) < 1)
956                 $this->message_type = "alt";
957             if(strlen($this->AltBody) > 0 && count($this->attachment) > 0)
958                 $this->message_type = "alt_attachments";
959         }
960     }
961
962     /**
963      * Returns a formatted header line.
964      * @access private
965      * @return string
966      */
967     function HeaderLine($name, $value) {
968         return $name . ": " . $value . $this->LE;
969     }
970
971     /**
972      * Returns a formatted mail line.
973      * @access private
974      * @return string
975      */
976     function TextLine($value) {
977         return $value . $this->LE;
978     }
979
980     /////////////////////////////////////////////////
981     // ATTACHMENT METHODS
982     /////////////////////////////////////////////////
983
984     /**
985      * Adds an attachment from a path on the filesystem.
986      * Returns false if the file could not be found
987      * or accessed.
988      * @param string $path Path to the attachment.
989      * @param string $name Overrides the attachment name.
990      * @param string $encoding File encoding (see $Encoding).
991      * @param string $type File extension (MIME) type.
992      * @return bool
993      */
994     function AddAttachment($path, $name = "", $encoding = "base64",
995                            $type = "application/octet-stream") {
996         if(!@is_file($path))
997         {
998             $this->SetError($this->Lang("file_access") . $path);
999             return false;
1000         }
1001
1002         $filename = basename($path);
1003         if($name == "")
1004             $name = $filename;
1005
1006         $cur = count($this->attachment);
1007         $this->attachment[$cur][0] = $path;
1008         $this->attachment[$cur][1] = $filename;
1009         $this->attachment[$cur][2] = $name;
1010         $this->attachment[$cur][3] = $encoding;
1011         $this->attachment[$cur][4] = $type;
1012         $this->attachment[$cur][5] = false; // isStringAttachment
1013         $this->attachment[$cur][6] = "attachment";
1014         $this->attachment[$cur][7] = 0;
1015
1016         return true;
1017     }
1018
1019     /**
1020      * Attaches all fs, string, and binary attachments to the message.
1021      * Returns an empty string on failure.
1022      * @access private
1023      * @return string
1024      */
1025     function AttachAll() {
1026         // Return text of body
1027         $mime = array();
1028
1029         // Add all attachments
1030         for($i = 0; $i < count($this->attachment); $i++)
1031         {
1032             // Check for string attachment
1033             $bString = $this->attachment[$i][5];
1034             if ($bString)
1035                 $string = $this->attachment[$i][0];
1036             else
1037                 $path = $this->attachment[$i][0];
1038
1039             $filename    = $this->attachment[$i][1];
1040             $name        = $this->attachment[$i][2];
1041             $encoding    = $this->attachment[$i][3];
1042             $type        = $this->attachment[$i][4];
1043             $disposition = $this->attachment[$i][6];
1044             $cid         = $this->attachment[$i][7];
1045
1046             $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
1047             $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $name, $this->LE);
1048             $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
1049
1050             if($disposition == "inline")
1051                 $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
1052
1053             $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s",
1054                               $disposition, $name, $this->LE.$this->LE);
1055
1056             // Encode as string attachment
1057             if($bString)
1058             {
1059                 $mime[] = $this->EncodeString($string, $encoding);
1060                 if($this->IsError()) { return ""; }
1061                 $mime[] = $this->LE.$this->LE;
1062             }
1063             else
1064             {
1065                 $mime[] = $this->EncodeFile($path, $encoding);
1066                 if($this->IsError()) { return ""; }
1067                 $mime[] = $this->LE.$this->LE;
1068             }
1069         }
1070
1071         $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
1072
1073         return join("", $mime);
1074     }
1075
1076     /**
1077      * Encodes attachment in requested format.  Returns an
1078      * empty string on failure.
1079      * @access private
1080      * @return string
1081      */
1082     function EncodeFile ($path, $encoding = "base64") {
1083         if(!@$fd = fopen($path, "rb"))
1084         {
1085             $this->SetError($this->Lang("file_open") . $path);
1086             return "";
1087         }
1088         $magic_quotes = get_magic_quotes_runtime();
1089         set_magic_quotes_runtime(0);
1090         $file_buffer = fread($fd, filesize($path));
1091         $file_buffer = $this->EncodeString($file_buffer, $encoding);
1092         fclose($fd);
1093         set_magic_quotes_runtime($magic_quotes);
1094
1095         return $file_buffer;
1096     }
1097
1098     /**
1099      * Encodes string to requested format. Returns an
1100      * empty string on failure.
1101      * @access private
1102      * @return string
1103      */
1104     function EncodeString ($str, $encoding = "base64") {
1105         $encoded = "";
1106         switch(strtolower($encoding)) {
1107           case "base64":
1108               // chunk_split is found in PHP >= 3.0.6
1109               $encoded = chunk_split(base64_encode($str), 76, $this->LE);
1110               break;
1111           case "7bit":
1112           case "8bit":
1113               $encoded = $this->FixEOL($str);
1114               if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1115                 $encoded .= $this->LE;
1116               break;
1117           case "binary":
1118               $encoded = $str;
1119               break;
1120           case "quoted-printable":
1121               $encoded = $this->EncodeQP($str);
1122               break;
1123           default:
1124               $this->SetError($this->Lang("encoding") . $encoding);
1125               break;
1126         }
1127         return $encoded;
1128     }
1129
1130     /**
1131      * Encode a header string to best of Q, B, quoted or none.
1132      * @access private
1133      * @return string
1134      */
1135     function EncodeHeader ($str, $position = 'text') {
1136       $x = 0;
1137
1138       switch (strtolower($position)) {
1139         case 'phrase':
1140           if (!preg_match('/[\200-\377]/', $str)) {
1141             // Can't use addslashes as we don't know what value has magic_quotes_sybase.
1142             $encoded = addcslashes($str, "\0..\37\177\\\"");
1143
1144             if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str))
1145               return ($encoded);
1146             else
1147               return ("\"$encoded\"");
1148           }
1149           $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
1150           break;
1151         case 'comment':
1152           $x = preg_match_all('/[()"]/', $str, $matches);
1153           // Fall-through
1154         case 'text':
1155         default:
1156           $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
1157           break;
1158       }
1159
1160       if ($x == 0)
1161         return ($str);
1162
1163       $maxlen = 75 - 7 - strlen($this->CharSet);
1164       // Try to select the encoding which should produce the shortest output
1165       if (strlen($str)/3 < $x) {
1166         $encoding = 'B';
1167         $encoded = base64_encode($str);
1168         $maxlen -= $maxlen % 4;
1169         $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
1170       } else {
1171         $encoding = 'Q';
1172         $encoded = $this->EncodeQ($str, $position);
1173         $encoded = $this->WrapText($encoded, $maxlen, true);
1174         $encoded = str_replace("=".$this->LE, "\n", trim($encoded));
1175       }
1176
1177       $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
1178       $encoded = trim(str_replace("\n", $this->LE, $encoded));
1179
1180       return $encoded;
1181     }
1182
1183     /**
1184      * Encode string to quoted-printable.
1185      * @access private
1186      * @return string
1187      */
1188     function EncodeQP ($str) {
1189         $encoded = $this->FixEOL($str);
1190         if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1191             $encoded .= $this->LE;
1192
1193         // Replace every high ascii, control and = characters
1194         $encoded = preg_replace('/([\000-\010\013\014\016-\037\075\177-\377])/e',
1195                   "'='.sprintf('%02X', ord('\\1'))", $encoded);
1196         // Replace every spaces and tabs when it's the last character on a line
1197         $encoded = preg_replace("/([\011\040])".$this->LE."/e",
1198                   "'='.sprintf('%02X', ord('\\1')).'".$this->LE."'", $encoded);
1199
1200         // Maximum line length of 76 characters before CRLF (74 + space + '=')
1201         $encoded = $this->WrapText($encoded, 74, true);
1202
1203         return $encoded;
1204     }
1205
1206     /**
1207      * Encode string to q encoding.
1208      * @access private
1209      * @return string
1210      */
1211     function EncodeQ ($str, $position = "text") {
1212         // There should not be any EOL in the string
1213         $encoded = preg_replace("[\r\n]", "", $str);
1214
1215         switch (strtolower($position)) {
1216           case "phrase":
1217             $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1218             break;
1219           case "comment":
1220             $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1221           case "text":
1222           default:
1223             // Replace every high ascii, control =, ? and _ characters
1224             $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
1225                   "'='.sprintf('%02X', ord('\\1'))", $encoded);
1226             break;
1227         }
1228
1229         // Replace every spaces to _ (more readable than =20)
1230         $encoded = str_replace(" ", "_", $encoded);
1231
1232         return $encoded;
1233     }
1234
1235     /**
1236      * Adds a string or binary attachment (non-filesystem) to the list.
1237      * This method can be used to attach ascii or binary data,
1238      * such as a BLOB record from a database.
1239      * @param string $string String attachment data.
1240      * @param string $filename Name of the attachment.
1241      * @param string $encoding File encoding (see $Encoding).
1242      * @param string $type File extension (MIME) type.
1243      * @return void
1244      */
1245     function AddStringAttachment($string, $filename, $encoding = "base64",
1246                                  $type = "application/octet-stream") {
1247         // Append to $attachment array
1248         $cur = count($this->attachment);
1249         $this->attachment[$cur][0] = $string;
1250         $this->attachment[$cur][1] = $filename;
1251         $this->attachment[$cur][2] = $filename;
1252         $this->attachment[$cur][3] = $encoding;
1253         $this->attachment[$cur][4] = $type;
1254         $this->attachment[$cur][5] = true; // isString
1255         $this->attachment[$cur][6] = "attachment";
1256         $this->attachment[$cur][7] = 0;
1257     }
1258
1259     /**
1260      * Adds an embedded attachment.  This can include images, sounds, and
1261      * just about any other document.  Make sure to set the $type to an
1262      * image type.  For JPEG images use "image/jpeg" and for GIF images
1263      * use "image/gif".
1264      * @param string $path Path to the attachment.
1265      * @param string $cid Content ID of the attachment.  Use this to identify
1266      *        the Id for accessing the image in an HTML form.
1267      * @param string $name Overrides the attachment name.
1268      * @param string $encoding File encoding (see $Encoding).
1269      * @param string $type File extension (MIME) type.
1270      * @return bool
1271      */
1272     function AddEmbeddedImage($path, $cid, $name = "", $encoding = "base64",
1273                               $type = "application/octet-stream") {
1274
1275         if(!@is_file($path))
1276         {
1277             $this->SetError($this->Lang("file_access") . $path);
1278             return false;
1279         }
1280
1281         $filename = basename($path);
1282         if($name == "")
1283             $name = $filename;
1284
1285         // Append to $attachment array
1286         $cur = count($this->attachment);
1287         $this->attachment[$cur][0] = $path;
1288         $this->attachment[$cur][1] = $filename;
1289         $this->attachment[$cur][2] = $name;
1290         $this->attachment[$cur][3] = $encoding;
1291         $this->attachment[$cur][4] = $type;
1292         $this->attachment[$cur][5] = false; // isStringAttachment
1293         $this->attachment[$cur][6] = "inline";
1294         $this->attachment[$cur][7] = $cid;
1295
1296         return true;
1297     }
1298
1299     /**
1300      * Returns true if an inline attachment is present.
1301      * @access private
1302      * @return bool
1303      */
1304     function InlineImageExists() {
1305         $result = false;
1306         for($i = 0; $i < count($this->attachment); $i++)
1307         {
1308             if($this->attachment[$i][6] == "inline")
1309             {
1310                 $result = true;
1311                 break;
1312             }
1313         }
1314
1315         return $result;
1316     }
1317
1318     /////////////////////////////////////////////////
1319     // MESSAGE RESET METHODS
1320     /////////////////////////////////////////////////
1321
1322     /**
1323      * Clears all recipients assigned in the TO array.  Returns void.
1324      * @return void
1325      */
1326     function ClearAddresses() {
1327         $this->to = array();
1328     }
1329
1330     /**
1331      * Clears all recipients assigned in the CC array.  Returns void.
1332      * @return void
1333      */
1334     function ClearCCs() {
1335         $this->cc = array();
1336     }
1337
1338     /**
1339      * Clears all recipients assigned in the BCC array.  Returns void.
1340      * @return void
1341      */
1342     function ClearBCCs() {
1343         $this->bcc = array();
1344     }
1345
1346     /**
1347      * Clears all recipients assigned in the ReplyTo array.  Returns void.
1348      * @return void
1349      */
1350     function ClearReplyTos() {
1351         $this->ReplyTo = array();
1352     }
1353
1354     /**
1355      * Clears all recipients assigned in the TO, CC and BCC
1356      * array.  Returns void.
1357      * @return void
1358      */
1359     function ClearAllRecipients() {
1360         $this->to = array();
1361         $this->cc = array();
1362         $this->bcc = array();
1363     }
1364
1365     /**
1366      * Clears all previously set filesystem, string, and binary
1367      * attachments.  Returns void.
1368      * @return void
1369      */
1370     function ClearAttachments() {
1371         $this->attachment = array();
1372     }
1373
1374     /**
1375      * Clears all custom headers.  Returns void.
1376      * @return void
1377      */
1378     function ClearCustomHeaders() {
1379         $this->CustomHeader = array();
1380     }
1381
1382
1383     /////////////////////////////////////////////////
1384     // MISCELLANEOUS METHODS
1385     /////////////////////////////////////////////////
1386
1387     /**
1388      * Adds the error message to the error container.
1389      * Returns void.
1390      * @access private
1391      * @return void
1392      */
1393     function SetError($msg) {
1394         $this->error_count++;
1395         $this->ErrorInfo = $msg;
1396     }
1397
1398     /**
1399      * Returns the proper RFC 822 formatted date.
1400      * @access private
1401      * @return string
1402      */
1403     function RFCDate() {
1404         $tz = date("Z");
1405         $tzs = ($tz < 0) ? "-" : "+";
1406         $tz = abs($tz);
1407         $tz = ($tz/3600)*100 + ($tz%3600)/60;
1408         $result = sprintf("%s %s%04d", date("D, j M Y H:i:s"), $tzs, $tz);
1409
1410         return $result;
1411     }
1412
1413     /**
1414      * Returns the appropriate server variable.  Should work with both
1415      * PHP 4.1.0+ as well as older versions.  Returns an empty string
1416      * if nothing is found.
1417      * @access private
1418      * @return mixed
1419      */
1420     function ServerVar($varName) {
1421         global $HTTP_SERVER_VARS;
1422         global $HTTP_ENV_VARS;
1423
1424         if(!isset($_SERVER))
1425         {
1426             $_SERVER = $HTTP_SERVER_VARS;
1427             if(!isset($_SERVER["REMOTE_ADDR"]))
1428                 $_SERVER = $HTTP_ENV_VARS; // must be Apache
1429         }
1430
1431         if(isset($_SERVER[$varName]))
1432             return $_SERVER[$varName];
1433         else
1434             return "";
1435     }
1436
1437     /**
1438      * Returns the server hostname or 'localhost.localdomain' if unknown.
1439      * @access private
1440      * @return string
1441      */
1442     function ServerHostname() {
1443         if ($this->Hostname != "")
1444             $result = $this->Hostname;
1445         elseif ($this->ServerVar('SERVER_NAME') != "")
1446             $result = $this->ServerVar('SERVER_NAME');
1447         else
1448             $result = "localhost.localdomain";
1449
1450         return $result;
1451     }
1452
1453     /**
1454      * Returns a message in the appropriate language.
1455      * @access private
1456      * @return string
1457      */
1458     function Lang($key) {
1459         if(count($this->language) < 1)
1460             $this->SetLanguage("en"); // set the default language
1461
1462         if(isset($this->language[$key]))
1463             return $this->language[$key];
1464         else
1465             return "Language string failed to load: " . $key;
1466     }
1467
1468     /**
1469      * Returns true if an error occurred.
1470      * @return bool
1471      */
1472     function IsError() {
1473         return ($this->error_count > 0);
1474     }
1475
1476     /**
1477      * Changes every end of line from CR or LF to CRLF.
1478      * @access private
1479      * @return string
1480      */
1481     function FixEOL($str) {
1482         $str = str_replace("\r\n", "\n", $str);
1483         $str = str_replace("\r", "\n", $str);
1484         $str = str_replace("\n", $this->LE, $str);
1485         return $str;
1486     }
1487
1488     /**
1489      * Adds a custom header.
1490      * @return void
1491      */
1492     function AddCustomHeader($custom_header) {
1493         $this->CustomHeader[] = explode(":", $custom_header, 2);
1494     }
1495 }
1496
1497 ?>