Ticket #535: class.phpmailer.php

File class.phpmailer.php, 55.1 KB (added by amuller, 14 years ago)

Classe php mailer sem cópia do body

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