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

Revision 27, 46.5 KB checked in by niltonneto, 17 years ago (diff)

* empty log message *

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