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

Revision 1036, 53.9 KB checked in by amuller, 15 years ago (diff)

Ticket #559 - Atualização de segurança

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