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

Revision 2, 45.9 KB checked in by niltonneto, 17 years ago (diff)

Removida todas as tags usadas pelo CVS ($Id, $Source).
Primeira versão no CVS externo.

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