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

Revision 1040, 54.0 KB checked in by amuller, 15 years ago (diff)

Ticket #559 - Atualização de download de arquivos e sessão

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