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

Revision 7655, 46.2 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Melhorias de performance no codigo do Expresso.

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