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

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

Ticket #559 - Correção de problema, usando caminho relativo

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