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

Revision 399, 46.6 KB checked in by niltonneto, 16 years ago (diff)

Tradução do undisclosed recipients

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