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

Revision 7673, 46.6 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

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