source: trunk/expressoMail1_2/inc/class.phpmailer.php @ 19

Revision 19, 46.3 KB checked in by niltonneto, 17 years ago (diff)

* empty log message *

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