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

Revision 2316, 55.1 KB checked in by amuller, 14 years ago (diff)

Ticket #535 - Correção de bug do commit anterior neste arquivo

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