source: companies/celepar/expressoMail1_2/inc/class.phpmailer.php @ 763

Revision 763, 47.1 KB checked in by niltonneto, 15 years ago (diff)

Importação inicial do Expresso da Celepar

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