source: trunk/phpgwapi/inc/class.phpmailer.inc.php @ 2

Revision 2, 45.3 KB checked in by niltonneto, 17 years ago (diff)

Removida todas as tags usadas pelo CVS ($Id, $Source).
Primeira versão no CVS externo.

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