source: trunk/phpgwapi/inc/class.phpmailer.inc.php @ 2364

Revision 2364, 46.0 KB checked in by amuller, 14 years ago (diff)

Ticket #1008 - Adicionando licença aos arquivos php

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