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

Revision 426, 46.9 KB checked in by niltonneto, 16 years ago (diff)

http://www.expressolivre.org/dev/ticket/326

Incluir o campo CCo na cópia da mensagem enviada.

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