source: branches/2.3/phpgwapi/inc/class.phpmailer.inc.php @ 4138

Revision 4138, 45.5 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1792 - Adicionado patch para enviar convites no formato text/calendar

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