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

Revision 2795, 55.7 KB checked in by amuller, 14 years ago (diff)

Ticket #1059 - mudando a chamada do arquivo messages.js

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