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

Revision 2360, 55.8 KB checked in by amuller, 14 years ago (diff)

Ticket #1008 - Adicionando informações sobre licenças

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