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

Revision 1035, 53.7 KB checked in by rafaelraymundo, 15 years ago (diff)

Ticket #558 - Adicionada funcionalidade de assinatura e criptografia de e-mails.

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