source: companies/serpro/expressoMail1_2/inc/class.phpmailer.php @ 903

Revision 903, 52.7 KB checked in by niltonneto, 15 years ago (diff)

Importacao inicial do Expresso do Serpro

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