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

Revision 504, 47.0 KB checked in by niltonneto, 16 years ago (diff)

Vide no Trac #344 - Melhorar tratamento de erros (parte 1)

  • 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          = "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       
348   
349        $header = "";
350        $body = "";
351        $result = true;
352               
353        if(((count($this->to) + count($this->cc) + count($this->bcc)) < 1) && (!$this->SaveMessageAsDraft))
354        {
355            $this->SetError($this->Lang("provide_address"));           
356            return false;
357        }
358               
359        // Set whether the message is multipart/alternative
360        if(!empty($this->AltBody))
361            $this->ContentType = "multipart/alternative";
362
363        $this->error_count = 0; // reset errors
364        $this->SetMessageType();
365        $header .= $this->CreateHeader();
366        $body = $this->CreateBody();
367               
368        if($body == "") { return false; }
369               
370        // Choose the mailer
371        switch($this->Mailer)
372        {
373            case "sendmail":
374                $result = $this->SendmailSend($header, $body);
375                break;
376            case "mail":
377                $result = $this->MailSend($header, $body);
378                break;
379            case "smtp":
380                $result = $this->SmtpSend($header, $body);
381                break;
382            default:
383                    $this->SetError($this->Mailer . $this->Lang("mailer_not_supported"));
384                $result = false;
385                break;
386        }
387
388        return $result;
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            //Postfix version 2.3.8-2
501            $smtp_code_error = substr($this->smtp->error['smtp_msg'], 0, 5);
502            //Postfix version 2.1.5-9
503            $array_error = explode(":", $this->smtp->error['smtp_msg']);
504           
505            for($i = 0; $i < count($bad_rcpt); $i++)
506            {
507                if($i != 0) { $error .= ", "; }
508                $error .= $bad_rcpt[$i];
509            }
510            if (($smtp_code_error == '5.7.1') || (trim($array_error[2]) == 'Access denied'))
511                $error = $this->Lang("not_allowed") . $error;
512            else
513                $error = $this->Lang("recipients_failed") . $error;
514            $this->SetError($error);
515            $this->smtp->Reset();
516            return false;
517        }
518        $smtpSent = $this->smtp->Data($header . $body);
519        if(!$smtpSent)
520        {
521            $this->SetError($this->Lang("data_not_accepted") .' '. $this->smtp->error['error'] .','. $this->smtp->error['smtp_code'].','. $this->smtp->error['smtp_msg']);
522            $this->smtp->Reset();
523            return false;
524        }
525        if($this->SMTPKeepAlive == true)
526            $this->smtp->Reset();
527        else
528            $this->SmtpClose();
529
530        if ($this->SaveMessageInFolder){
531                        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
532                        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
533                        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
534                        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
535                       
536                        if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
537                        {
538                                $imap_options = '/tls/novalidate-cert';
539                        }
540                        else
541                        {
542                                $imap_options = '/notls/novalidate-cert';
543                        }               
544                        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$this->SaveMessageInFolder, $username, $password);
545
546                        ##
547                        # @AUTHOR Rodrigo Souza dos Santos
548                        # @DATE 2008/09/11
549                        # @BRIEF Adding arbitrarily the BCC field. You may need to
550                        #        check if this field already exists in the header.
551                        ##
552                        if ( count($this->bcc) > 0 )
553                        {
554                                $target = stripos($header, 'subject');
555                                $header = substr($header, 0, $target) . $this->AddrAppend("Bcc", $this->bcc) . substr($header, $target);
556                        }
557               
558                        $new_header = str_replace("\n", "\r\n", $header);
559                        $new_body = str_replace("\n", "\r\n", $body);
560                       
561                        if ($this->SaveMessageAsDraft){
562                                imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$this->SaveMessageInFolder, $new_header . $new_body, "\\Seen \\Draft");
563                                return true;
564                        }
565                        else
566                                imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$this->SaveMessageInFolder, $new_header . $new_body, "\\Seen");
567        }       
568       
569        return $smtpSent;
570    }
571
572    /**
573     * Initiates a connection to an SMTP server.  Returns false if the
574     * operation failed.
575     * @access private
576     * @return bool
577     */
578    function SmtpConnect() {
579        if($this->smtp == NULL) { $this->smtp = new SMTP(); }
580
581        $this->smtp->do_debug = $this->SMTPDebug;
582        $hosts = explode(";", $this->Host);
583        $index = 0;
584        $connection = ($this->smtp->Connected());
585
586        // Retry while there is no connection
587        while($index < count($hosts) && $connection == false)
588        {
589            if(strstr($hosts[$index], ":"))
590                list($host, $port) = explode(":", $hosts[$index]);
591            else
592            {
593                $host = $hosts[$index];
594                $port = $this->Port;
595            }
596
597            if($this->smtp->Connect($host, $port, $this->Timeout))
598            {
599                if ($this->Helo != '')
600                    $this->smtp->Hello($this->Helo);
601                else
602                    $this->smtp->Hello($this->ServerHostname());
603       
604                if($this->SMTPAuth)
605                {
606                    if(!$this->smtp->Authenticate($this->Username,
607                                                  $this->Password))
608                    {
609                        $this->SetError($this->Lang("authenticate"));
610                        $this->smtp->Reset();
611                        $connection = false;
612                    }
613                }
614                $connection = true;
615            }
616            $index++;
617        }
618        if(!$connection)
619            $this->SetError($this->Lang("connect_host"));
620
621        return $connection;
622    }
623
624    /**
625     * Closes the active SMTP session if one exists.
626     * @return void
627     */
628    function SmtpClose() {
629        if($this->smtp != NULL)
630        {
631            if($this->smtp->Connected())
632            {
633                $this->smtp->Quit();
634                $this->smtp->Close();
635            }
636        }
637    }
638
639    /**
640     * Sets the language for all class error messages.  Returns false
641     * if it cannot load the language file.  The default language type
642     * is English.
643     * @param string $lang_type Type of language (e.g. Portuguese: "br")
644     * @param string $lang_path Path to the language file directory
645     * @access public
646     * @return bool
647     */
648    function SetLanguage($lang_type, $lang_path = "setup/") {
649        if(file_exists($lang_path.'phpmailer.lang-'.$lang_type.'.php'))
650            include($lang_path.'phpmailer.lang-'.$lang_type.'.php');
651        else if(file_exists($lang_path.'phpmailer.lang-en.php'))
652            include($lang_path.'phpmailer.lang-en.php');
653        else
654        {
655            $this->SetError("Could not load language file");
656            return false;
657        }
658        $this->language = $PHPMAILER_LANG;
659   
660        return true;
661    }
662
663    /////////////////////////////////////////////////
664    // MESSAGE CREATION METHODS
665    /////////////////////////////////////////////////
666
667    /**
668     * Creates recipient headers. 
669     * @access private
670     * @return string
671     */
672    function AddrAppend($type, $addr) {
673        $addr_str = $type . ": ";
674        $addr_str .= $this->AddrFormat($addr[0]);
675        if(count($addr) > 1)
676        {
677            for($i = 1; $i < count($addr); $i++)
678                $addr_str .= ", " . $this->AddrFormat($addr[$i]);
679        }
680        $addr_str .= $this->LE;
681
682        return $addr_str;
683    }
684   
685    /**
686     * Formats an address correctly.
687     * @access private
688     * @return string
689     */
690    function AddrFormat($addr) {
691        if(empty($addr[1]))
692            $formatted = $addr[0];
693        else
694        {
695            $formatted = $this->EncodeHeader($addr[1], 'phrase') . " <" .
696                         $addr[0] . ">";
697        }
698
699        return $formatted;
700    }
701
702    /**
703     * Wraps message for use with mailers that do not
704     * automatically perform wrapping and for quoted-printable.
705     * Original written by philippe. 
706     * @access private
707     * @return string
708     */
709    function WrapText($message, $length, $qp_mode = false) {
710        $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
711
712        $message = $this->FixEOL($message);
713        if (substr($message, -1) == $this->LE)
714            $message = substr($message, 0, -1);
715
716        $line = explode($this->LE, $message);
717        $message = "";
718        for ($i=0 ;$i < count($line); $i++)
719        {
720          $line_part = explode(" ", $line[$i]);
721          $buf = "";
722          for ($e = 0; $e<count($line_part); $e++)
723          {
724              $word = $line_part[$e];
725              if ($qp_mode and (strlen($word) > $length))
726              {
727                $space_left = $length - strlen($buf) - 1;
728                if ($e != 0)
729                {
730                    if ($space_left > 20)
731                    {
732                        $len = $space_left;
733                        if (substr($word, $len - 1, 1) == "=")
734                          $len--;
735                        elseif (substr($word, $len - 2, 1) == "=")
736                          $len -= 2;
737                        $part = substr($word, 0, $len);
738                        $word = substr($word, $len);
739                        $buf .= " " . $part;
740                        $message .= $buf . sprintf("=%s", $this->LE);
741                    }
742                    else
743                    {
744                        $message .= $buf . $soft_break;
745                    }
746                    $buf = "";
747                }
748                while (strlen($word) > 0)
749                {
750                    $len = $length;
751                    if (substr($word, $len - 1, 1) == "=")
752                        $len--;
753                    elseif (substr($word, $len - 2, 1) == "=")
754                        $len -= 2;
755                    $part = substr($word, 0, $len);
756                    $word = substr($word, $len);
757
758                    if (strlen($word) > 0)
759                        $message .= $part . sprintf("=%s", $this->LE);
760                    else
761                        $buf = $part;
762                }
763              }
764              else
765              {
766                $buf_o = $buf;
767                $buf .= ($e == 0) ? $word : (" " . $word);
768
769                if (strlen($buf) > $length and $buf_o != "")
770                {
771                    $message .= $buf_o . $soft_break;
772                    $buf = $word;
773                }
774              }
775          }
776          $message .= $buf . $this->LE;
777        }
778
779        return $message;
780    }
781   
782    /**
783     * Set the body wrapping.
784     * @access private
785     * @return void
786     */
787    function SetWordWrap() {
788        if($this->WordWrap < 1)
789            return;
790           
791        switch($this->message_type)
792        {
793           case "alt":
794              // fall through
795           case "alt_attachments":
796              $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
797              break;
798           default:
799              $this->Body = $this->WrapText($this->Body, $this->WordWrap);
800              break;
801        }
802    }
803
804    /**
805     * Assembles message header. 
806     * @access private
807     * @return string
808     */
809    function CreateHeader() {
810        $result = "";
811       
812        // Set the boundaries
813        $uniq_id = md5(uniqid(time()));
814        $this->boundary[1] = "b1_" . $uniq_id;
815        $this->boundary[2] = "b2_" . $uniq_id;
816
817        $result .= $this->HeaderLine("Date", $this->RFCDate());
818        if($this->Sender == "")
819            $result .= $this->HeaderLine("Return-Path", trim($this->From));
820        else
821            $result .= $this->HeaderLine("Return-Path", trim($this->Sender));
822       
823        // To be created automatically by mail()
824        if($this->Mailer != "mail")
825        {
826            if(count($this->to) > 0)
827                $result .= $this->AddrAppend("To", $this->to);
828            else if ((count($this->cc) == 0) && (!$this->SaveMessageAsDraft))
829            {
830                $result .= $this->HeaderLine("To", $this->Lang('undisclosed-recipient'));
831            }
832            if(count($this->cc) > 0)
833                $result .= $this->AddrAppend("Cc", $this->cc);
834        }
835
836                if (!$this->SaveMessageAsDraft){
837                $from = array();
838            $from[0][0] = trim($this->From);
839                $from[0][1] = $this->FromName;
840                $result .= $this->AddrAppend("From", $from);
841                }
842                if($this->Sender) {
843                        $sender = array();
844                        $sender[0][0] = trim($this->Sender);
845                $sender[0][1] = $this->SenderName;
846                $result .= $this->AddrAppend("Sender", $sender);
847                }
848
849        // sendmail and mail() extract Bcc from the header before sending
850        if((($this->Mailer == "sendmail") || ($this->Mailer == "mail")) && (count($this->bcc) > 0))
851            $result .= $this->AddrAppend("Bcc", $this->bcc);
852
853        if(count($this->ReplyTo) > 0)
854            $result .= $this->AddrAppend("Reply-to", $this->ReplyTo);
855
856        // mail() sets the subject itself
857        if($this->Mailer != "mail")
858            $result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject)));
859
860        $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
861        $result .= $this->HeaderLine("X-Priority", $this->Priority);
862        $result .= $this->HeaderLine("X-Mailer", "ExpressoMail [version " . $this->Version . "]");
863       
864        if($this->ConfirmReadingTo != "")
865        {
866            $result .= $this->HeaderLine("Disposition-Notification-To",
867                       "<" . trim($this->ConfirmReadingTo) . ">");
868        }
869
870        // Add custom headers
871        for($index = 0; $index < count($this->CustomHeader); $index++)
872        {
873            $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]),
874                       $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
875        }
876        $result .= $this->HeaderLine("MIME-Version", "1.0");
877
878        switch($this->message_type)
879        {
880            case "plain":
881                $result .= $this->HeaderLine("Content-Transfer-Encoding", $this->Encoding);
882                $result .= sprintf("Content-Type: %s; charset=\"%s\"",
883                                    $this->ContentType, $this->CharSet);
884                break;
885            case "attachments":
886                // fall through
887            case "alt_attachments":
888                if($this->InlineImageExists())
889                {
890                    $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s",
891                                    "multipart/related", $this->LE, $this->LE,
892                                    $this->boundary[1], $this->LE);
893                }
894                else
895                {
896                    $result .= $this->HeaderLine("Content-Type", "multipart/mixed;");
897                    $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
898                }
899                break;
900            case "alt":
901                $result .= $this->HeaderLine("Content-Type", "multipart/alternative;");
902                $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
903                break;
904        }
905
906        if($this->Mailer != "mail")
907            $result .= $this->LE.$this->LE;
908
909        return $result;
910    }
911
912    /**
913     * Assembles the message body.  Returns an empty string on failure.
914     * @access private
915     * @return string
916     */
917    function CreateBody() {
918        $result = "";
919
920        $this->SetWordWrap();
921        switch($this->message_type)
922        {
923            case "alt":
924                $result .= $this->GetBoundary($this->boundary[1], "",
925                                              "text/plain", "");
926                $result .= $this->EncodeString($this->AltBody, $this->Encoding);
927                $result .= $this->LE.$this->LE;
928                $result .= $this->GetBoundary($this->boundary[1], "",
929                                              "text/html", "");
930               
931                $result .= $this->EncodeString($this->Body, $this->Encoding);
932                $result .= $this->LE.$this->LE;
933   
934                $result .= $this->EndBoundary($this->boundary[1]);
935                break;
936            case "plain":
937                $result .= $this->EncodeString($this->Body, $this->Encoding);
938                break;
939            case "attachments":
940                $result .= $this->GetBoundary($this->boundary[1], "", "", "");
941                $result .= $this->EncodeString($this->Body, $this->Encoding);
942                $result .= $this->LE;
943     
944                $result .= $this->AttachAll();
945                break;
946            case "alt_attachments":
947                $result .= sprintf("--%s%s", $this->boundary[1], $this->LE);
948                $result .= sprintf("Content-Type: %s;%s" .
949                                   "\tboundary=\"%s\"%s",
950                                   "multipart/alternative", $this->LE,
951                                   $this->boundary[2], $this->LE.$this->LE);
952   
953                // Create text body
954                $result .= $this->GetBoundary($this->boundary[2], "",
955                                              "text/plain", "") . $this->LE;
956
957                $result .= $this->EncodeString($this->AltBody, $this->Encoding);
958                $result .= $this->LE.$this->LE;
959   
960                // Create the HTML body
961                $result .= $this->GetBoundary($this->boundary[2], "",
962                                              "text/html", "") . $this->LE;
963   
964                $result .= $this->EncodeString($this->Body, $this->Encoding);
965                $result .= $this->LE.$this->LE;
966
967                $result .= $this->EndBoundary($this->boundary[2]);
968               
969                $result .= $this->AttachAll();
970                break;
971        }
972        if($this->IsError())
973            $result = "";
974
975        return $result;
976    }
977
978    /**
979     * Returns the start of a message boundary.
980     * @access private
981     */
982    function GetBoundary($boundary, $charSet, $contentType, $encoding) {
983        $result = "";
984        if($charSet == "") { $charSet = $this->CharSet; }
985        if($contentType == "") { $contentType = $this->ContentType; }
986        if($encoding == "") { $encoding = $this->Encoding; }
987
988        $result .= $this->TextLine("--" . $boundary);
989        $result .= sprintf("Content-Type: %s; charset = \"%s\"",
990                            $contentType, $charSet);
991        $result .= $this->LE;
992        $result .= $this->HeaderLine("Content-Transfer-Encoding", $encoding);
993        $result .= $this->LE;
994       
995        return $result;
996    }
997   
998    /**
999     * Returns the end of a message boundary.
1000     * @access private
1001     */
1002    function EndBoundary($boundary) {
1003        return $this->LE . "--" . $boundary . "--" . $this->LE;
1004    }
1005   
1006    /**
1007     * Sets the message type.
1008     * @access private
1009     * @return void
1010     */
1011    function SetMessageType() {
1012        if(count($this->attachment) < 1 && strlen($this->AltBody) < 1)
1013            $this->message_type = "plain";
1014        else
1015        {
1016            if(count($this->attachment) > 0)
1017                $this->message_type = "attachments";
1018            if(strlen($this->AltBody) > 0 && count($this->attachment) < 1)
1019                $this->message_type = "alt";
1020            if(strlen($this->AltBody) > 0 && count($this->attachment) > 0)
1021                $this->message_type = "alt_attachments";
1022        }
1023    }
1024
1025    /**
1026     * Returns a formatted header line.
1027     * @access private
1028     * @return string
1029     */
1030    function HeaderLine($name, $value) {
1031        return $name . ": " . $value . $this->LE;
1032    }
1033
1034    /**
1035     * Returns a formatted mail line.
1036     * @access private
1037     * @return string
1038     */
1039    function TextLine($value) {
1040        return $value . $this->LE;
1041    }
1042
1043    /////////////////////////////////////////////////
1044    // ATTACHMENT METHODS
1045    /////////////////////////////////////////////////
1046
1047    /**
1048     * Adds an attachment from a path on the filesystem.
1049     * Returns false if the file could not be found
1050     * or accessed.
1051     * @param string $path Path to the attachment.
1052     * @param string $name Overrides the attachment name.
1053     * @param string $encoding File encoding (see $Encoding).
1054     * @param string $type File extension (MIME) type.
1055     * @return bool
1056     */
1057    function AddAttachment($path, $name = "", $encoding = "base64",
1058                           $type = "application/octet-stream") {
1059        if(!@is_file($path))
1060        {
1061            $this->SetError($this->Lang("file_access") . $path);
1062            return false;
1063        }
1064
1065        $filename = basename($path);
1066        if($name == "")
1067            $name = $filename;
1068
1069        $cur = count($this->attachment);
1070        $this->attachment[$cur][0] = $path;
1071        $this->attachment[$cur][1] = $filename;
1072        $this->attachment[$cur][2] = $name;
1073        $this->attachment[$cur][3] = $encoding;
1074        $this->attachment[$cur][4] = $type;
1075        $this->attachment[$cur][5] = false; // isStringAttachment
1076        $this->attachment[$cur][6] = "attachment";
1077        $this->attachment[$cur][7] = 0;
1078
1079        return true;
1080    }
1081
1082    /**
1083     * Attaches all fs, string, and binary attachments to the message.
1084     * Returns an empty string on failure.
1085     * @access private
1086     * @return string
1087     */
1088    function AttachAll() {
1089        // Return text of body
1090        $mime = array();
1091
1092        // Add all attachments
1093        for($i = 0; $i < count($this->attachment); $i++)
1094        {
1095            // Check for string attachment
1096            $bString = $this->attachment[$i][5];
1097            if ($bString)
1098                $string = $this->attachment[$i][0];
1099            else
1100                $path = $this->attachment[$i][0];
1101
1102            $filename    = $this->attachment[$i][1];
1103            $name        = $this->attachment[$i][2];
1104            $encoding    = $this->attachment[$i][3];
1105            $type        = $this->attachment[$i][4];
1106            $disposition = $this->attachment[$i][6];
1107            $cid         = $this->attachment[$i][7];
1108           
1109            $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
1110            $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $name, $this->LE);
1111            $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
1112
1113            if($disposition == "inline")
1114                $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
1115
1116            $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s",
1117                              $disposition, $name, $this->LE.$this->LE);
1118
1119            // Encode as string attachment
1120            if($bString)
1121            {
1122                $mime[] = $this->EncodeString($string, $encoding);
1123                if($this->IsError()) { return ""; }
1124                $mime[] = $this->LE.$this->LE;
1125            }
1126            else
1127            {
1128                $mime[] = $this->EncodeFile($path, $encoding);               
1129                if($this->IsError()) { return ""; }
1130                $mime[] = $this->LE.$this->LE;
1131            }
1132        }
1133
1134        $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
1135
1136        return join("", $mime);
1137    }
1138   
1139    /**
1140     * Encodes attachment in requested format.  Returns an
1141     * empty string on failure.
1142     * @access private
1143     * @return string
1144     */
1145    function EncodeFile ($path, $encoding = "base64") {
1146        if(!@$fd = fopen($path, "rb"))
1147        {
1148            $this->SetError($this->Lang("file_open") . $path);
1149            return "";
1150        }
1151        $magic_quotes = get_magic_quotes_runtime();
1152        set_magic_quotes_runtime(0);
1153        $file_buffer = fread($fd, filesize($path));
1154        $file_buffer = $this->EncodeString($file_buffer, $encoding);
1155        fclose($fd);
1156        set_magic_quotes_runtime($magic_quotes);
1157
1158        return $file_buffer;
1159    }
1160
1161    /**
1162     * Encodes string to requested format. Returns an
1163     * empty string on failure.
1164     * @access private
1165     * @return string
1166     */
1167    function EncodeString ($str, $encoding = "base64") {
1168        $encoded = "";
1169        switch(strtolower($encoding)) {
1170          case "base64":
1171              // chunk_split is found in PHP >= 3.0.6
1172              $encoded = @chunk_split(base64_encode($str), 76, $this->LE);
1173              break;
1174          case "7bit":
1175          case "8bit":
1176              $encoded = $this->FixEOL($str);
1177              if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1178                $encoded .= $this->LE;
1179              break;
1180          case "binary":
1181              $encoded = $str;
1182              break;
1183          case "quoted-printable":
1184              $encoded = $this->EncodeQP($str);
1185              break;
1186          default:
1187              $this->SetError($this->Lang("encoding") . $encoding);
1188              break;
1189        }
1190        return $encoded;
1191    }
1192
1193    /**
1194     * Encode a header string to best of Q, B, quoted or none. 
1195     * @access private
1196     * @return string
1197     */
1198    function EncodeHeader ($str, $position = 'text') {
1199      $x = 0;
1200     
1201      switch (strtolower($position)) {
1202        case 'phrase':
1203          if (!preg_match('/[\200-\377]/', $str)) {
1204            // Can't use addslashes as we don't know what value has magic_quotes_sybase.
1205            $encoded = addcslashes($str, "\0..\37\177\\\"");
1206
1207            if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str))
1208              return ($encoded);
1209            else
1210              return ("\"$encoded\"");
1211          }
1212          $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
1213          break;
1214        case 'comment':
1215          $x = preg_match_all('/[()"]/', $str, $matches);
1216          // Fall-through
1217        case 'text':
1218        default:
1219          $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
1220          break;
1221      }
1222
1223      if ($x == 0)
1224        return ($str);
1225
1226      $maxlen = 75 - 7 - strlen($this->CharSet);
1227      // Try to select the encoding which should produce the shortest output
1228      if (strlen($str)/3 < $x) {
1229        $encoding = 'B';
1230        $encoded = base64_encode($str);
1231        $maxlen -= $maxlen % 4;
1232        $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
1233      } else {
1234        $encoding = 'Q';
1235        $encoded = $this->EncodeQ($str, $position);
1236        $encoded = $this->WrapText($encoded, $maxlen, true);
1237        $encoded = str_replace("=".$this->LE, "\n", trim($encoded));
1238      }
1239
1240      $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
1241      $encoded = trim(str_replace("\n", $this->LE, $encoded));
1242     
1243      return $encoded;
1244    }
1245   
1246    /**
1247     * Encode string to quoted-printable. 
1248     * @access private
1249     * @return string
1250     */
1251    function EncodeQP ($str) {
1252        $encoded = $this->FixEOL($str);
1253        if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1254            $encoded .= $this->LE;
1255
1256        // Replace every high ascii, control and = characters
1257        $encoded = preg_replace('/([\000-\010\013\014\016-\037\075\177-\377])/e',
1258                  "'='.sprintf('%02X', ord('\\1'))", $encoded);
1259        // Replace every spaces and tabs when it's the last character on a line
1260        $encoded = preg_replace("/([\011\040])".$this->LE."/e",
1261                  "'='.sprintf('%02X', ord('\\1')).'".$this->LE."'", $encoded);
1262
1263        // Maximum line length of 76 characters before CRLF (74 + space + '=')
1264        $encoded = $this->WrapText($encoded, 74, true);
1265               
1266        return $encoded;
1267    }
1268
1269    /**
1270     * Encode string to q encoding. 
1271     * @access private
1272     * @return string
1273     */
1274    function EncodeQ ($str, $position = "text") {
1275        // There should not be any EOL in the string
1276        $encoded = preg_replace("[\r\n]", "", $str);
1277        switch (strtolower($position)) {
1278          case "phrase":
1279            $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1280            break;
1281          case "comment":
1282            $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1283          case "text":
1284          default:
1285            // Replace every high ascii, control =, ? and _ characters
1286            $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
1287                  "'='.sprintf('%02X', ord('\\1'))", $encoded);
1288            break;
1289        }
1290       
1291        // Replace every spaces to _ (more readable than =20)
1292        $encoded = str_replace(" ", "_", $encoded);
1293
1294        return $encoded;
1295    }
1296
1297    /**
1298     * Adds a string or binary attachment (non-filesystem) to the list.
1299     * This method can be used to attach ascii or binary data,
1300     * such as a BLOB record from a database.
1301     * @param string $string String attachment data.
1302     * @param string $filename Name of the attachment.
1303     * @param string $encoding File encoding (see $Encoding).
1304     * @param string $type File extension (MIME) type.
1305     * @return void
1306     */
1307    function AddStringAttachment($string, $filename, $encoding = "base64",
1308                                 $type = "application/octet-stream") {
1309        // Append to $attachment array
1310        $cur = count($this->attachment);
1311        $this->attachment[$cur][0] = $string;
1312        $this->attachment[$cur][1] = $filename;
1313        $this->attachment[$cur][2] = $filename;
1314        $this->attachment[$cur][3] = $encoding;
1315        $this->attachment[$cur][4] = $type;
1316        $this->attachment[$cur][5] = true; // isString
1317        $this->attachment[$cur][6] = "attachment";
1318        $this->attachment[$cur][7] = 0;
1319    }
1320   
1321    /**
1322     * Adds an embedded attachment.  This can include images, sounds, and
1323     * just about any other document.  Make sure to set the $type to an
1324     * image type.  For JPEG images use "image/jpeg" and for GIF images
1325     * use "image/gif".
1326     * @param string $path Path to the attachment.
1327     * @param string $cid Content ID of the attachment.  Use this to identify
1328     *        the Id for accessing the image in an HTML form.
1329     * @param string $name Overrides the attachment name.
1330     * @param string $encoding File encoding (see $Encoding).
1331     * @param string $type File extension (MIME) type. 
1332     * @return bool
1333     */
1334    function AddEmbeddedImage($path, $cid, $name = "", $encoding = "base64",
1335                              $type = "application/octet-stream") {
1336   
1337        if(!@is_file($path))
1338        {
1339            $this->SetError($this->Lang("file_access") . $path);
1340            return false;
1341        }
1342
1343        $filename = basename($path);
1344        if($name == "")
1345            $name = $filename;
1346
1347        // Append to $attachment array
1348        $cur = count($this->attachment);
1349        $this->attachment[$cur][0] = $path;
1350        $this->attachment[$cur][1] = $filename;
1351        $this->attachment[$cur][2] = $name;
1352        $this->attachment[$cur][3] = $encoding;
1353        $this->attachment[$cur][4] = $type;
1354        $this->attachment[$cur][5] = false; // isStringAttachment
1355        $this->attachment[$cur][6] = "inline";
1356        $this->attachment[$cur][7] = $cid;
1357   
1358        return true;
1359    }
1360   
1361    /**
1362     * Returns true if an inline attachment is present.
1363     * @access private
1364     * @return bool
1365     */
1366    function InlineImageExists() {
1367        $result = false;
1368        for($i = 0; $i < count($this->attachment); $i++)
1369        {
1370            if($this->attachment[$i][6] == "inline")
1371            {
1372                $result = true;
1373                break;
1374            }
1375        }
1376       
1377        return $result;
1378    }
1379
1380    /////////////////////////////////////////////////
1381    // MESSAGE RESET METHODS
1382    /////////////////////////////////////////////////
1383
1384    /**
1385     * Clears all recipients assigned in the TO array.  Returns void.
1386     * @return void
1387     */
1388    function ClearAddresses() {
1389        $this->to = array();
1390    }
1391
1392    /**
1393     * Clears all recipients assigned in the CC array.  Returns void.
1394     * @return void
1395     */
1396    function ClearCCs() {
1397        $this->cc = array();
1398    }
1399
1400    /**
1401     * Clears all recipients assigned in the BCC array.  Returns void.
1402     * @return void
1403     */
1404    function ClearBCCs() {
1405        $this->bcc = array();
1406    }
1407
1408    /**
1409     * Clears all recipients assigned in the ReplyTo array.  Returns void.
1410     * @return void
1411     */
1412    function ClearReplyTos() {
1413        $this->ReplyTo = array();
1414    }
1415
1416    /**
1417     * Clears all recipients assigned in the TO, CC and BCC
1418     * array.  Returns void.
1419     * @return void
1420     */
1421    function ClearAllRecipients() {
1422        $this->to = array();
1423        $this->cc = array();
1424        $this->bcc = array();
1425    }
1426
1427    /**
1428     * Clears all previously set filesystem, string, and binary
1429     * attachments.  Returns void.
1430     * @return void
1431     */
1432    function ClearAttachments() {
1433        $this->attachment = array();
1434    }
1435
1436    /**
1437     * Clears all custom headers.  Returns void.
1438     * @return void
1439     */
1440    function ClearCustomHeaders() {
1441        $this->CustomHeader = array();
1442    }
1443
1444
1445    /////////////////////////////////////////////////
1446    // MISCELLANEOUS METHODS
1447    /////////////////////////////////////////////////
1448
1449    /**
1450     * Adds the error message to the error container.
1451     * Returns void.
1452     * @access private
1453     * @return void
1454     */
1455    function SetError($msg) {
1456        $this->error_count++;
1457        $this->ErrorInfo = $msg;
1458    }
1459
1460    /**
1461     * Returns the proper RFC 822 formatted date.
1462     * @access private
1463     * @return string
1464     */
1465    function RFCDate() {
1466        $tz = date("Z");
1467        $tzs = ($tz < 0) ? "-" : "+";
1468        $tz = abs($tz);
1469        $tz = ($tz/3600)*100 + ($tz%3600)/60;
1470        $result = sprintf("%s %s%04d", date("D, j M Y H:i:s"), $tzs, $tz);
1471
1472        return $result;
1473    }
1474   
1475    /**
1476     * Returns the appropriate server variable.  Should work with both
1477     * PHP 4.1.0+ as well as older versions.  Returns an empty string
1478     * if nothing is found.
1479     * @access private
1480     * @return mixed
1481     */
1482    function ServerVar($varName) {
1483        global $HTTP_SERVER_VARS;
1484        global $HTTP_ENV_VARS;
1485
1486        if(!isset($_SERVER))
1487        {
1488            $_SERVER = $HTTP_SERVER_VARS;
1489            if(!isset($_SERVER["REMOTE_ADDR"]))
1490                $_SERVER = $HTTP_ENV_VARS; // must be Apache
1491        }
1492       
1493        if(isset($_SERVER[$varName]))
1494            return $_SERVER[$varName];
1495        else
1496            return "";
1497    }
1498
1499    /**
1500     * Returns the server hostname or 'localhost.localdomain' if unknown.
1501     * @access private
1502     * @return string
1503     */
1504    function ServerHostname() {
1505        if ($this->Hostname != "")
1506            $result = $this->Hostname;
1507        elseif ($this->ServerVar('SERVER_NAME') != "")
1508            $result = $this->ServerVar('SERVER_NAME');
1509        else
1510            $result = "localhost.localdomain";
1511
1512        return $result;
1513    }
1514
1515    /**
1516     * Returns a message in the appropriate language.
1517     * @access private
1518     * @return string
1519     */
1520    function Lang($key) {
1521        if(count($this->language) < 1)
1522            $this->SetLanguage("br"); // set the default language
1523   
1524        if(isset($this->language[$key]))
1525            return $this->language[$key];
1526        else
1527            return "Language string failed to load: " . $key;
1528    }
1529   
1530    /**
1531     * Returns true if an error occurred.
1532     * @return bool
1533     */
1534    function IsError() {
1535        return ($this->error_count > 0);
1536    }
1537
1538    /**
1539     * Changes every end of line from CR or LF to CRLF. 
1540     * @access private
1541     * @return string
1542     */
1543    function FixEOL($str) {
1544        $str = str_replace("\r\n", "\n", $str);
1545        $str = str_replace("\r", "\n", $str);
1546        $str = str_replace("\n", $this->LE, $str);
1547        return $str;
1548    }
1549
1550    /**
1551     * Adds a custom header.
1552     * @return void
1553     */
1554    function AddCustomHeader($custom_header) {
1555        $this->CustomHeader[] = explode(":", $custom_header, 2);
1556    }
1557}
1558
1559?>
Note: See TracBrowser for help on using the repository browser.