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

Revision 7655, 53.3 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Melhorias de performance no codigo do Expresso.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2                /***************************************************************************
3                * Expresso Livre                                                           *
4                * http://www.expressolivre.org                                             *
5                * --------------------------------------------                             *
6                *  This program is free software; you can redistribute it and/or modify it *
7                *  under the terms of the GNU General Public License as published by the   *
8                *  Free Software Foundation; either version 2 of the License, or (at your  *
9                *  option) any later version.                                              *
10                \**************************************************************************/
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->smtp->Recipient($this->to[$i][0]))
538                        $bad_rcpt[] = $this->to[$i][0];
539        }
540        for($i = 0; $i < count($this->cc); ++$i)
541        {
542                if(!$this->smtp->Recipient($this->cc[$i][0]))
543                        $bad_rcpt[] = $this->cc[$i][0];
544        }
545        for($i = 0; $i < count($this->bcc); ++$i)
546        {
547                if(!$this->smtp->Recipient($this->bcc[$i][0]))
548                        $bad_rcpt[] = $this->bcc[$i][0];     
549        }
550        if($errorx != '')
551                {
552                        $error = $errorx;
553                        $error = $this->Lang("recipients_failed")  . '  ' . $errorx;
554                        $this->SetError($error);
555                        $this->smtp->Reset();
556                        return false;
557                }
558
559        if(count($bad_rcpt) > 0) // Create error message
560        {
561            //Postfix version 2.3.8-2
562            $smtp_code_error = substr($this->smtp->error['smtp_msg'], 0, 5);
563            //Postfix version 2.1.5-9
564            $array_error = explode(":", $this->smtp->error['smtp_msg']);
565           
566            for($i = 0; $i < count($bad_rcpt); ++$i)
567            {
568                if($i != 0) { $error .= ", "; }
569                $error .= $bad_rcpt[$i];
570            }
571            if (($smtp_code_error == '5.7.1') || (trim($array_error[2]) == 'Access denied'))
572                $error = $this->Lang("not_allowed") . $error;
573            else
574                $error = $this->Lang("recipients_failed") . $error;
575            $this->SetError($error);
576            $this->smtp->Reset();
577            return false;
578        }
579
580        // Vai verificar se deve cifrar a msg ......
581        if(count($this->Certs_crypt) > 0)
582                {
583            // Vai cifrar a msg antes de enviar ......
584                        include_once("../security/classes/CertificadoB.php");
585
586            $teste1 = array();
587            $aux_cifra1 = $header . $body;
588
589            // Início relocação dos headers
590            // Esta relocação dos headers podem causar problemas.
591
592            $match = 0;
593            $pattern = '/^Disposition\-Notification\-To:.*\n/m';
594            $match = preg_match($pattern, $aux_cifra1, $teste1);
595
596            if (!empty($match)){
597                $aux_cifra1 = preg_replace($pattern, '', $aux_cifra1, 1); // retira o Disposition-Notification-To
598
599                $match = 0;
600                $teste2 = array();
601                $pattern = '/^MIME\-Version:.*\n/m';
602                $match = preg_match($pattern, $aux_cifra1, $teste2);
603                $aux_cifra1 = preg_replace($pattern, $teste1[0].$teste2[0], $aux_cifra1, 1); // Adiciona Disposition-Notification-To logo acima de MIME-Version
604
605            }
606            // Fim relocação dos headers
607
608           // Vai partir em duas partes a msg.  A primeira parte he a dos headers, e a segunda vai ser criptografada ...
609            $pos_content_type = strpos($aux_cifra1,'Content-Type:');
610            $pos_MIME_Version = strpos($aux_cifra1,'MIME-Version: 1.0' . chr(0x0D) . chr(0x0A));
611            $valx_len = 19;
612            if($pos_MIME_Version === False)
613                    {
614                $pos_MIME_Version = strpos($aux_cifra1,'MIME-Version: 1.0' . chr(0x0A));
615                $valx_len = 18;
616                    }
617
618            if($pos_MIME_Version >= $pos_content_type)
619            {
620                // nao deve enviar a msg..... O header MIME-Version com posicao invalida ......
621                $this->SetError('Formato dos headers da msg estao invalidos.(CD-17) - A');
622                $this->smtp->Reset();
623                return false;
624            }
625
626            $aux_cifra2 = array();
627            $aux_cifra2[] = substr($aux_cifra1,0,$pos_MIME_Version - 1);
628            $aux_cifra2[] = substr($aux_cifra1,$pos_MIME_Version + $valx_len);
629
630               /*
631                        // este explode pode ser fonte de problemas .......
632                        $aux_cifra2 = explode('MIME-Version: 1.0' . chr(0x0A), $aux_cifra1);
633                        // Pode ocorrer um erro se nao tiver o header MIME-Version .....
634                        if(count($aux_cifra2)  != 2 )
635                                {
636                                        $aux_cifra2 = explode('MIME-Version: 1.0' . chr(0x0D) . chr(0x0A), $aux_cifra1);
637                                        if(count($aux_cifra2)  != 2 )
638                                                {
639                                                        // nao deve enviar a msg..... nao tem o header MIME-Version ......
640                                                        $this->SetError('Formato dos headers da msg estao invalidos.(CD-17) - ' . count($aux_cifra2));
641                                                        $this->smtp->Reset();
642                                                        return false;
643                                                }
644                                }
645                */
646                        $certificado = new certificadoB();
647                        $h = array();
648                        $aux_body = $certificado->encriptar($aux_cifra2[1], $this->Certs_crypt, $h);
649                        if(!$aux_body)
650            {
651                $this->SetError('Ocorreu um erro. A msg nao foi enviada. (CD-18)');
652                $this->smtp->Reset();
653                return false;
654            }
655                        // salvar sem cifra......
656                        //$smtpSent = $this->smtp->Data($aux_cifra2[0] . $aux_body);
657
658                        // salva a msg sifrada. neste caso deve ter sido adicionado o certificado do autor da msg......
659                        $header = $aux_cifra2[0];
660                        $body = $aux_body;
661        $smtpSent = $this->smtp->Data($header . $body);
662        }
663        else
664                {
665                        $smtpSent = $this->smtp->Data($header . $body);
666                }
667
668        if(!$smtpSent)
669        {
670            $this->SetError($this->Lang("data_not_accepted") .' '. $this->smtp->error['error'] .','. $this->smtp->error['smtp_code'].','. $this->smtp->error['smtp_msg']);
671            $this->smtp->Reset();
672            return false;
673        }
674        if($this->SMTPKeepAlive == true)
675            $this->smtp->Reset();
676        else
677            $this->SmtpClose();
678
679        if ($this->SaveMessageInFolder){
680                        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
681                        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
682                        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
683                        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
684                       
685                        if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
686                        {
687                                $imap_options = '/tls/novalidate-cert';
688                        }
689                        else
690                        {
691                                $imap_options = '/notls/novalidate-cert';
692                        }               
693                        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$this->SaveMessageInFolder, $username, $password);
694
695                        ##
696                        # @AUTHOR Rodrigo Souza dos Santos
697                        # @DATE 2008/09/11
698                        # @BRIEF Adding arbitrarily the BCC field. You may need to
699                        #        check if this field already exists in the header.
700                        ##
701                        if ( count($this->bcc) > 0 )
702                        {
703                                $target = stripos($header, 'subject');
704                                $header = substr($header, 0, $target) . $this->AddrAppend("Bcc", $this->bcc) . substr($header, $target);
705                        }
706            $new_headerx = str_replace(chr(0x0A),chr(0x0D).chr(0x0A), $header);
707                        $new_bodyx = str_replace(chr(0x0A),chr(0x0D).chr(0x0A), $body);
708                        $new_header = str_replace(chr(0x0D).chr(0x0D).chr(0x0A), chr(0x0D).chr(0x0A),$new_headerx);
709                        $new_body = str_replace(chr(0x0D).chr(0x0D).chr(0x0A), chr(0x0D).chr(0x0A), $new_bodyx);
710                       
711                        if ($this->SaveMessageAsDraft){
712                                imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$this->SaveMessageInFolder, $new_header . $new_body, "\\Seen \\Draft");
713                                return true;
714                        }
715                        else
716                                imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$this->SaveMessageInFolder, $new_header . $new_body, "\\Seen");
717        }       
718       
719        return $smtpSent;
720    }
721
722
723    /**
724     * Initiates a connection to an SMTP server.  Returns false if the
725     * operation failed.
726     * @access private
727     * @return bool
728     */
729    function SmtpConnect() {
730        if($this->smtp == NULL) { $this->smtp = new SMTP(); }
731
732        $this->smtp->do_debug = $this->SMTPDebug;
733        $hosts = explode(";", $this->Host);
734        $index = 0;
735        $connection = ($this->smtp->Connected());
736
737        // Retry while there is no connection
738        while($index < count($hosts) && $connection == false)
739        {
740            if(strstr($hosts[$index], ":"))
741                list($host, $port) = explode(":", $hosts[$index]);
742            else
743            {
744                $host = $hosts[$index];
745                $port = $this->Port;
746            }
747
748            if($this->smtp->Connect($host, $port, $this->Timeout))
749            {
750                if ($this->Helo != '')
751                    $this->smtp->Hello($this->Helo);
752                else
753                    $this->smtp->Hello($this->ServerHostname());
754       
755                if($this->SMTPAuth)
756                {
757                    if(!$this->smtp->Authenticate($this->Username,
758                                                  $this->Password))
759                    {
760                        $this->SetError($this->Lang("authenticate"));
761                        $this->smtp->Reset();
762                        $connection = false;
763                    }
764                }
765                $connection = true;
766            }
767            ++$index;
768        }
769        if(!$connection)
770            $this->SetError($this->Lang("connect_host"));
771
772        return $connection;
773    }
774
775    /**
776     * Closes the active SMTP session if one exists.
777     * @return void
778     */
779    function SmtpClose() {
780        if($this->smtp != NULL)
781        {
782            if($this->smtp->Connected())
783            {
784                $this->smtp->Quit();
785                $this->smtp->Close();
786            }
787        }
788    }
789
790    /**
791     * Sets the language for all class error messages.  Returns false
792     * if it cannot load the language file.  The default language type
793     * is English.
794     * @param string $lang_type Type of language (e.g. Portuguese: "br")
795     * @param string $lang_path Path to the language file directory
796     * @access public
797     * @return bool
798     */
799    function SetLanguage($lang_type, $lang_path = "setup/") {
800        if(file_exists($lang_path.'phpmailer.lang-'.$lang_type.'.php'))
801            include($lang_path.'phpmailer.lang-'.$lang_type.'.php');
802        else if(file_exists($lang_path.'phpmailer.lang-en.php'))
803            include($lang_path.'phpmailer.lang-en.php');
804        else
805        {
806            $this->SetError("Could not load language file");
807            return false;
808        }
809        $this->language = $PHPMAILER_LANG;
810   
811        return true;
812    }
813
814    /////////////////////////////////////////////////
815    // MESSAGE CREATION METHODS
816    /////////////////////////////////////////////////
817
818    /**
819     * Creates recipient headers. 
820     * @access private
821     * @return string
822     */
823    function AddrAppend($type, $addr) {
824        $addr_str = $type . ": ";
825        $addr_str .= $this->AddrFormat($addr[0]);
826        if(count($addr) > 1)
827        {
828            for($i = 1; $i < count($addr); ++$i)
829                $addr_str .= ", " . $this->AddrFormat($addr[$i]);
830        }
831        $addr_str .= $this->LE;
832
833        return $addr_str;
834    }
835   
836    /**
837     * Formats an address correctly.
838     * @access private
839     * @return string
840     */
841    function AddrFormat($addr) {
842        if(empty($addr[1]))
843            $formatted = $addr[0];
844        else
845        {
846            $formatted = $this->EncodeHeader($addr[1], 'phrase') . " <" .
847                         $addr[0] . ">";
848        }
849
850        return $formatted;
851    }
852
853    /**
854     * Wraps message for use with mailers that do not
855     * automatically perform wrapping and for quoted-printable.
856     * Original written by philippe. 
857     * @access private
858     * @return string
859     */
860    function WrapText($message, $length, $qp_mode = false) {
861        $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
862
863        $message = $this->FixEOL($message);
864        if (substr($message, -1) == $this->LE)
865            $message = substr($message, 0, -1);
866
867        $line = explode($this->LE, $message);
868        $message = "";
869        for ($i=0 ;$i < count($line); ++$i)
870        {
871          $line_part = explode(" ", $line[$i]);
872          $buf = "";
873          for ($e = 0; $e<count($line_part); $e++)
874          {
875              $word = $line_part[$e];
876              if ($qp_mode and (strlen($word) > $length))
877              {
878                $space_left = $length - strlen($buf) - 1;
879                if ($e != 0)
880                {
881                    if ($space_left > 20)
882                    {
883                        $len = $space_left;
884                        if (substr($word, $len - 1, 1) == "=")
885                          $len--;
886                        elseif (substr($word, $len - 2, 1) == "=")
887                          $len -= 2;
888                        $part = substr($word, 0, $len);
889                        $word = substr($word, $len);
890                        $buf .= " " . $part;
891                        $message .= $buf . sprintf("=%s", $this->LE);
892                    }
893                    else
894                    {
895                        $message .= $buf . $soft_break;
896                    }
897                    $buf = "";
898                }
899                while (strlen($word) > 0)
900                {
901                    $len = $length;
902                    if (substr($word, $len - 1, 1) == "=")
903                        $len--;
904                    elseif (substr($word, $len - 2, 1) == "=")
905                        $len -= 2;
906                    $part = substr($word, 0, $len);
907                    $word = substr($word, $len);
908
909                    if (strlen($word) > 0)
910                        $message .= $part . sprintf("=%s", $this->LE);
911                    else
912                        $buf = $part;
913                }
914              }
915              else
916              {
917                $buf_o = $buf;
918                $buf .= ($e == 0) ? $word : (" " . $word);
919
920                if (strlen($buf) > $length and $buf_o != "")
921                {
922                    $message .= $buf_o . $soft_break;
923                    $buf = $word;
924                }
925              }
926          }
927          $message .= $buf . $this->LE;
928        }
929
930        return $message;
931    }
932   
933    /**
934     * Set the body wrapping.
935     * @access private
936     * @return void
937     */
938    function SetWordWrap() {
939        if($this->WordWrap < 1)
940            return;
941           
942        switch($this->message_type)
943        {
944           case "alt":
945              // fall through
946           case "alt_attachments":
947              $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
948              break;
949           default:
950              $this->Body = $this->WrapText($this->Body, $this->WordWrap);
951              break;
952        }
953    }
954
955    /**
956     * Assembles message header. 
957     * @access private
958     * @return string
959     */
960    function CreateHeader() {
961        $result = "";
962       
963        // Set the boundaries
964        $uniq_id = md5(uniqid(time()));
965        $this->boundary[1] = "b1_" . $uniq_id;
966        $this->boundary[2] = "b2_" . $uniq_id;
967
968        $result .= $this->HeaderLine("Date", $this->RFCDate());
969        if($this->Sender == "")
970            $result .= $this->HeaderLine("Return-Path", trim($this->From));
971        else
972            $result .= $this->HeaderLine("Return-Path", trim($this->Sender));
973       
974        // To be created automatically by mail()
975        if($this->Mailer != "mail")
976        {
977            if(count($this->to) > 0)
978                $result .= $this->AddrAppend("To", $this->to);
979            else if ((count($this->cc) == 0) && (!$this->SaveMessageAsDraft))
980            {
981                $result .= $this->HeaderLine("To", $this->Lang('undisclosed-recipient'));
982            }
983            if(count($this->cc) > 0)
984                $result .= $this->AddrAppend("Cc", $this->cc);
985        }
986
987        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_x_origin'])
988                $result .= $this->HeaderLine("X-Origin", isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
989
990                $from = array();
991                $from[0][0] = trim($this->From);
992                $from[0][1] = $this->FromName;
993                $result .= $this->AddrAppend("From", $from);
994/*
995                if (!$this->SaveMessageAsDraft){
996                $from = array();
997            $from[0][0] = trim($this->From);
998                $from[0][1] = $this->FromName;
999                $result .= $this->AddrAppend("From", $from);
1000                }
1001                if($this->Sender) {
1002                        $sender = array();
1003                        $sender[0][0] = trim($this->Sender);
1004                $sender[0][1] = $this->SenderName;
1005                $result .= $this->AddrAppend("Sender", $sender);
1006                }
1007*/
1008        // sendmail and mail() extract Bcc from the header before sending
1009        if((($this->Mailer == "sendmail") || ($this->Mailer == "mail")) && (count($this->bcc) > 0))
1010            $result .= $this->AddrAppend("Bcc", $this->bcc);
1011        if ($this->SaveMessageAsDraft){
1012            $result .= $this->AddrAppend("Bcc", $this->bcc);
1013                }
1014        if(count($this->ReplyTo) > 0)
1015            $result .= $this->AddrAppend("Reply-to", $this->ReplyTo);
1016
1017        // mail() sets the subject itself
1018        if($this->Mailer != "mail")
1019            $result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject)));
1020
1021        $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
1022        $result .= $this->HeaderLine("X-Priority", $this->Priority);
1023        $result .= $this->HeaderLine("Importance", $this->Importance);
1024        $result .= $this->HeaderLine("X-Mailer", "ExpressoMail [version " . $this->Version . "]");
1025       
1026        if($this->ConfirmReadingTo != "")
1027        {
1028            $result .= $this->HeaderLine("Disposition-Notification-To",
1029                       "<" . trim($this->ConfirmReadingTo) . ">");
1030        }
1031
1032        // Add custom headers
1033        for($index = 0; $index < count($this->CustomHeader); ++$index)
1034        {
1035            $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]),
1036                       $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
1037        }
1038        $result .= $this->HeaderLine("MIME-Version", "1.0");
1039
1040        $result .= $this->write_message_type();
1041
1042        if($this->Mailer != "mail")
1043            $result .= $this->LE.$this->LE;
1044
1045        return $result;
1046    }
1047
1048
1049    function write_message_type()
1050        {
1051                $result = "";
1052        switch($this->message_type)
1053        {
1054            case "plain":$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
1055                $result .= $this->HeaderLine("Content-Transfer-Encoding", $this->Encoding);
1056                $result .= sprintf("Content-Type: %s; charset=\"%s\"",
1057                                    $this->ContentType, $this->CharSet);
1058                return $result;
1059            case "attachments":
1060                // fall through
1061            case "alt_attachments":
1062                if($this->InlineImageExists())
1063                {
1064                    $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s",
1065                                    "multipart/related", $this->LE, $this->LE,
1066                                    $this->boundary[1], $this->LE);
1067                }
1068                else
1069                {
1070                    $result .= $this->HeaderLine("Content-Type", "multipart/mixed;");
1071                    $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1072                }
1073                return $result;
1074            case "alt":
1075                $result .= $this->HeaderLine("Content-Type", "multipart/alternative;");
1076                $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1077                return $result;
1078        }
1079
1080        if($this->Mailer != "mail")
1081            $result .= $this->LE.$this->LE;
1082
1083        return $result;
1084    }
1085
1086    /**
1087     * Assembles the message body.  Returns an empty string on failure.
1088     * @access private
1089     * @return string
1090     */
1091    function CreateBody() {
1092        $result = "";
1093
1094        $this->SetWordWrap();
1095        switch($this->message_type)
1096        {
1097            case "alt":
1098                $result .= $this->GetBoundary($this->boundary[1], "",
1099                                              "text/plain", "");
1100                $result .= $this->EncodeString($this->AltBody, $this->Encoding);
1101                $result .= $this->LE.$this->LE;
1102                $result .= $this->GetBoundary($this->boundary[1], "",
1103                                              "text/html", "");
1104               
1105                $result .= $this->EncodeString($this->Body, $this->Encoding);
1106                $result .= $this->LE.$this->LE;
1107   
1108                $result .= $this->EndBoundary($this->boundary[1]);
1109                break;
1110            case "plain":
1111                $result .= $this->EncodeString($this->Body, $this->Encoding);
1112                break;
1113            case "attachments":
1114                $result .= $this->GetBoundary($this->boundary[1], "", "", "");
1115                $result .= $this->EncodeString($this->Body, $this->Encoding);
1116                $result .= $this->LE;
1117     
1118                $result .= $this->AttachAll();
1119                break;
1120            case "alt_attachments":
1121                $result .= sprintf("--%s%s", $this->boundary[1], $this->LE);
1122                $result .= sprintf("Content-Type: %s;%s" .
1123                                   "\tboundary=\"%s\"%s",
1124                                   "multipart/alternative", $this->LE,
1125                                   $this->boundary[2], $this->LE.$this->LE);
1126   
1127                // Create text body
1128                $result .= $this->GetBoundary($this->boundary[2], "",
1129                                              "text/plain", "") . $this->LE;
1130
1131                $result .= $this->EncodeString($this->AltBody, $this->Encoding);
1132                $result .= $this->LE.$this->LE;
1133   
1134                // Create the HTML body
1135                $result .= $this->GetBoundary($this->boundary[2], "",
1136                                              "text/html", "") . $this->LE;
1137   
1138                $result .= $this->EncodeString($this->Body, $this->Encoding);
1139                $result .= $this->LE.$this->LE;
1140
1141                $result .= $this->EndBoundary($this->boundary[2]);
1142               
1143                $result .= $this->AttachAll();
1144                break;
1145        }
1146        if($this->IsError())
1147            $result = "";
1148
1149        return $result;
1150    }
1151
1152    /**
1153     * Returns the start of a message boundary.
1154     * @access private
1155     */
1156    function GetBoundary($boundary, $charSet, $contentType, $encoding) {
1157        $result = "";
1158        if($charSet == "") { $charSet = $this->CharSet; }
1159        if($contentType == "") { $contentType = $this->ContentType; }
1160        if($encoding == "") { $encoding = $this->Encoding; }
1161
1162        $result .= $this->TextLine("--" . $boundary);
1163        $result .= sprintf("Content-Type: %s; charset = \"%s\"",
1164                            $contentType, $charSet);
1165        $result .= $this->LE;
1166        $result .= $this->HeaderLine("Content-Transfer-Encoding", $encoding);
1167        $result .= $this->LE;
1168       
1169        return $result;
1170    }
1171   
1172    /**
1173     * Returns the end of a message boundary.
1174     * @access private
1175     */
1176    function EndBoundary($boundary) {
1177        return $this->LE . "--" . $boundary . "--" . $this->LE;
1178    }
1179   
1180    /**
1181     * Sets the message type.
1182     * @access private
1183     * @return void
1184     */
1185    function SetMessageType() {
1186        if(count($this->attachment) < 1 && strlen($this->AltBody) < 1)
1187            $this->message_type = "plain";
1188        else
1189        {
1190            if(count($this->attachment) > 0)
1191                $this->message_type = "attachments";
1192            if(strlen($this->AltBody) > 0 && count($this->attachment) < 1)
1193                $this->message_type = "alt";
1194            if(strlen($this->AltBody) > 0 && count($this->attachment) > 0)
1195                $this->message_type = "alt_attachments";
1196        }
1197    }
1198
1199    /**
1200     * Returns a formatted header line.
1201     * @access private
1202     * @return string
1203     */
1204    function HeaderLine($name, $value) {
1205        return $name . ": " . $value . $this->LE;
1206    }
1207
1208    /**
1209     * Returns a formatted mail line.
1210     * @access private
1211     * @return string
1212     */
1213    function TextLine($value) {
1214        return $value . $this->LE;
1215    }
1216
1217    /////////////////////////////////////////////////
1218    // ATTACHMENT METHODS
1219    /////////////////////////////////////////////////
1220
1221    /**
1222     * Adds an attachment from a path on the filesystem.
1223     * Returns false if the file could not be found
1224     * or accessed.
1225     * @param string $path Path to the attachment.
1226     * @param string $name Overrides the attachment name.
1227     * @param string $encoding File encoding (see $Encoding).
1228     * @param string $type File extension (MIME) type.
1229     * @return bool
1230     */
1231    function AddAttachment($path, $name = "", $encoding = "base64",
1232                           $type = "application/octet-stream") {
1233        if(!@is_file($path))
1234        {
1235            $this->SetError($this->Lang("file_access") . $path);
1236            return false;
1237        }
1238
1239        $filename = basename($path);
1240        if($name == "")
1241            $name = $filename;
1242
1243        $cur = count($this->attachment);
1244        $this->attachment[$cur][0] = $path;
1245        $this->attachment[$cur][1] = $filename;
1246        $this->attachment[$cur][2] = $name;
1247        $this->attachment[$cur][3] = $encoding;
1248        $this->attachment[$cur][4] = $type;
1249        $this->attachment[$cur][5] = false; // isStringAttachment
1250        $this->attachment[$cur][6] = "attachment";
1251        $this->attachment[$cur][7] = 0;
1252
1253        return true;
1254    }
1255
1256    /**
1257     * Attaches all fs, string, and binary attachments to the message.
1258     * Returns an empty string on failure.
1259     * @access private
1260     * @return string
1261     */
1262    function AttachAll() {
1263        // Return text of body
1264        $mime = array();
1265
1266        // Add all attachments
1267        for($i = 0; $i < count($this->attachment); ++$i)
1268        {
1269            // Check for string attachment
1270            $bString = $this->attachment[$i][5];
1271            if ($bString)
1272                $string = $this->attachment[$i][0];
1273            else
1274                $path = $this->attachment[$i][0];
1275
1276            $filename    = $this->attachment[$i][1];
1277            $name        = $this->attachment[$i][2];
1278            $encoding    = $this->attachment[$i][3];
1279            $type        = $this->attachment[$i][4];
1280            $disposition = $this->attachment[$i][6];
1281            $cid         = $this->attachment[$i][7];
1282           
1283            $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
1284            $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $name, $this->LE);
1285            $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
1286
1287            if($disposition == "inline")
1288                $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
1289
1290            $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s",
1291                              $disposition, $name, $this->LE.$this->LE);
1292
1293            // Encode as string attachment
1294            if($bString)
1295            {
1296                $mime[] = $this->EncodeString($string, $encoding);
1297                if($this->IsError()) { return ""; }
1298                $mime[] = $this->LE.$this->LE;
1299            }
1300            else
1301            {
1302                $mime[] = $this->EncodeFile($path, $encoding);               
1303                if($this->IsError()) { return ""; }
1304                $mime[] = $this->LE.$this->LE;
1305            }
1306        }
1307
1308        $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
1309
1310        return join("", $mime);
1311    }
1312   
1313    /**
1314     * Encodes attachment in requested format.  Returns an
1315     * empty string on failure.
1316     * @access private
1317     * @return string
1318     */
1319    function EncodeFile ($path, $encoding = "base64") {
1320        if(!@$fd = fopen($path, "rb"))
1321        {
1322            $this->SetError($this->Lang("file_open") . $path);
1323            return "";
1324        }
1325        $magic_quotes = get_magic_quotes_runtime();
1326        set_magic_quotes_runtime(0);
1327        $file_buffer = fread($fd, filesize($path));
1328        $file_buffer = $this->EncodeString($file_buffer, $encoding);
1329        fclose($fd);
1330        set_magic_quotes_runtime($magic_quotes);
1331
1332        return $file_buffer;
1333    }
1334
1335    /**
1336     * Encodes string to requested format. Returns an
1337     * empty string on failure.
1338     * @access private
1339     * @return string
1340     */
1341    function EncodeString ($str, $encoding = "base64") {
1342        $encoded = "";
1343        switch(strtolower($encoding)) {
1344          case "base64":
1345              // chunk_split is found in PHP >= 3.0.6
1346              $encoded = @chunk_split(base64_encode($str), 76, $this->LE);
1347              break;
1348          case "7bit":
1349          case "8bit":
1350              $encoded = $this->FixEOL($str);
1351              if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1352                $encoded .= $this->LE;
1353              break;
1354          case "binary":
1355              $encoded = $str;
1356              break;
1357          case "quoted-printable":
1358              $encoded = $this->EncodeQP($str);
1359              break;
1360          default:
1361              $this->SetError($this->Lang("encoding") . $encoding);
1362              break;
1363        }
1364        return $encoded;
1365    }
1366
1367    /**
1368     * Encode a header string to best of Q, B, quoted or none. 
1369     * @access private
1370     * @return string
1371     */
1372    function EncodeHeader ($str, $position = 'text') {
1373      $x = 0;
1374     
1375      switch (strtolower($position)) {
1376        case 'phrase':
1377          if (!preg_match('/[\200-\377]/', $str)) {
1378            // Can't use addslashes as we don't know what value has magic_quotes_sybase.
1379            $encoded = addcslashes($str, "\0..\37\177\\\"");
1380
1381            if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str))
1382              return ($encoded);
1383            else
1384              return ("\"$encoded\"");
1385          }
1386          $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
1387          break;
1388        case 'comment':
1389          $x = preg_match_all('/[()"]/', $str, $matches);
1390          // Fall-through
1391        case 'text':
1392        default:
1393          $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
1394          break;
1395      }
1396
1397      if ($x == 0)
1398        return ($str);
1399
1400      $maxlen = 75 - 7 - strlen($this->CharSet);
1401      // Try to select the encoding which should produce the shortest output
1402      if (strlen($str)/3 < $x) {
1403        $encoding = 'B';
1404        $encoded = base64_encode($str);
1405        $maxlen -= $maxlen % 4;
1406        $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
1407      } else {
1408        $encoding = 'Q';
1409        $encoded = $this->EncodeQ($str, $position);
1410        $encoded = $this->WrapText($encoded, $maxlen, true);
1411        $encoded = str_replace("=".$this->LE, "\n", trim($encoded));
1412      }
1413
1414      $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
1415      $encoded = trim(str_replace("\n", $this->LE, $encoded));
1416     
1417      return $encoded;
1418    }
1419   
1420    /**
1421     * Encode string to quoted-printable. 
1422     * @access private
1423     * @return string
1424     */
1425    function EncodeQP ($str) {
1426        $encoded = $this->FixEOL($str);
1427        if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1428            $encoded .= $this->LE;
1429
1430        // Replace every high ascii, control and = characters
1431        $encoded = preg_replace('/([\000-\010\013\014\016-\037\075\177-\377])/e',
1432                  "'='.sprintf('%02X', ord('\\1'))", $encoded);
1433        // Replace every spaces and tabs when it's the last character on a line
1434        $encoded = preg_replace("/([\011\040])".$this->LE."/e",
1435                  "'='.sprintf('%02X', ord('\\1')).'".$this->LE."'", $encoded);
1436
1437        // Maximum line length of 76 characters before CRLF (74 + space + '=')
1438        $encoded = $this->WrapText($encoded, 74, true);
1439               
1440        return $encoded;
1441    }
1442
1443    /**
1444     * Encode string to q encoding. 
1445     * @access private
1446     * @return string
1447     */
1448    function EncodeQ ($str, $position = "text") {
1449        // There should not be any EOL in the string
1450        $encoded = preg_replace("[\r\n]", "", $str);
1451        switch (strtolower($position)) {
1452          case "phrase":
1453            $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1454            break;
1455          case "comment":
1456            $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1457          case "text":
1458          default:
1459            // Replace every high ascii, control =, ? and _ characters
1460            $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
1461                  "'='.sprintf('%02X', ord('\\1'))", $encoded);
1462            break;
1463        }
1464       
1465        // Replace every spaces to _ (more readable than =20)
1466        $encoded = str_replace(" ", "_", $encoded);
1467
1468        return $encoded;
1469    }
1470
1471    /**
1472     * Adds a string or binary attachment (non-filesystem) to the list.
1473     * This method can be used to attach ascii or binary data,
1474     * such as a BLOB record from a database.
1475     * @param string $string String attachment data.
1476     * @param string $filename Name of the attachment.
1477     * @param string $encoding File encoding (see $Encoding).
1478     * @param string $type File extension (MIME) type.
1479     * @return void
1480     */
1481    function AddStringAttachment($string, $filename, $encoding = "base64",
1482                                 $type = "application/octet-stream") {
1483        // Append to $attachment array
1484        $cur = count($this->attachment);
1485        $this->attachment[$cur][0] = $string;
1486        $this->attachment[$cur][1] = $filename;
1487        $this->attachment[$cur][2] = $filename;
1488        $this->attachment[$cur][3] = $encoding;
1489        $this->attachment[$cur][4] = $type;
1490        $this->attachment[$cur][5] = true; // isString
1491        $this->attachment[$cur][6] = "attachment";
1492        $this->attachment[$cur][7] = 0;
1493    }
1494   
1495    /**
1496     * Adds an embedded attachment.  This can include images, sounds, and
1497     * just about any other document.  Make sure to set the $type to an
1498     * image type.  For JPEG images use "image/jpeg" and for GIF images
1499     * use "image/gif".
1500     * @param string $path Path to the attachment.
1501     * @param string $cid Content ID of the attachment.  Use this to identify
1502     *        the Id for accessing the image in an HTML form.
1503     * @param string $name Overrides the attachment name.
1504     * @param string $encoding File encoding (see $Encoding).
1505     * @param string $type File extension (MIME) type. 
1506     * @return bool
1507     */
1508    function AddEmbeddedImage($path, $cid, $name = "", $encoding = "base64",
1509                              $type = "application/octet-stream") {
1510   
1511        if(!@is_file($path))
1512        {
1513            $this->SetError($this->Lang("file_access") . $path);
1514            return false;
1515        }
1516
1517        $filename = basename($path);
1518        if($name == "")
1519            $name = $filename;
1520
1521        // Append to $attachment array
1522        $cur = count($this->attachment);
1523        $this->attachment[$cur][0] = $path;
1524        $this->attachment[$cur][1] = $filename;
1525        $this->attachment[$cur][2] = $name;
1526        $this->attachment[$cur][3] = $encoding;
1527        $this->attachment[$cur][4] = $type;
1528        $this->attachment[$cur][5] = false; // isStringAttachment
1529        $this->attachment[$cur][6] = "inline";
1530        $this->attachment[$cur][7] = $cid;
1531   
1532        return true;
1533    }
1534   
1535    /**
1536     * Returns true if an inline attachment is present.
1537     * @access private
1538     * @return bool
1539     */
1540    function InlineImageExists() {
1541        $result = false;
1542        for($i = 0; $i < count($this->attachment); ++$i)
1543        {
1544            if($this->attachment[$i][6] == "inline")
1545            {
1546                $result = true;
1547                break;
1548            }
1549        }
1550       
1551        return $result;
1552    }
1553
1554    /////////////////////////////////////////////////
1555    // MESSAGE RESET METHODS
1556    /////////////////////////////////////////////////
1557
1558    /**
1559     * Clears all recipients assigned in the TO array.  Returns void.
1560     * @return void
1561     */
1562    function ClearAddresses() {
1563        $this->to = array();
1564    }
1565
1566    /**
1567     * Clears all recipients assigned in the CC array.  Returns void.
1568     * @return void
1569     */
1570    function ClearCCs() {
1571        $this->cc = array();
1572    }
1573
1574    /**
1575     * Clears all recipients assigned in the BCC array.  Returns void.
1576     * @return void
1577     */
1578    function ClearBCCs() {
1579        $this->bcc = array();
1580    }
1581
1582    /**
1583     * Clears all recipients assigned in the ReplyTo array.  Returns void.
1584     * @return void
1585     */
1586    function ClearReplyTos() {
1587        $this->ReplyTo = array();
1588    }
1589
1590    /**
1591     * Clears all recipients assigned in the TO, CC and BCC
1592     * array.  Returns void.
1593     * @return void
1594     */
1595    function ClearAllRecipients() {
1596        $this->to = array();
1597        $this->cc = array();
1598        $this->bcc = array();
1599    }
1600
1601    /**
1602     * Clears all previously set filesystem, string, and binary
1603     * attachments.  Returns void.
1604     * @return void
1605     */
1606    function ClearAttachments() {
1607        $this->attachment = array();
1608    }
1609
1610    /**
1611     * Clears all custom headers.  Returns void.
1612     * @return void
1613     */
1614    function ClearCustomHeaders() {
1615        $this->CustomHeader = array();
1616    }
1617
1618
1619    /////////////////////////////////////////////////
1620    // MISCELLANEOUS METHODS
1621    /////////////////////////////////////////////////
1622
1623    /**
1624     * Adds the error message to the error container.
1625     * Returns void.
1626     * @access private
1627     * @return void
1628     */
1629    function SetError($msg) {
1630        $this->error_count++;
1631        $this->ErrorInfo = $msg;
1632    }
1633
1634    /**
1635     * Returns the proper RFC 822 formatted date.
1636     * @access private
1637     * @return string
1638     */
1639    function RFCDate() {
1640        $tz = date("Z");
1641        $tzs = ($tz < 0) ? "-" : "+";
1642        $tz = abs($tz);
1643        $tz = ($tz/3600)*100 + ($tz%3600)/60;
1644        $result = sprintf("%s %s%04d", date("D, j M Y H:i:s"), $tzs, $tz);
1645
1646        return $result;
1647    }
1648   
1649    /**
1650     * Returns the appropriate server variable.  Should work with both
1651     * PHP 4.1.0+ as well as older versions.  Returns an empty string
1652     * if nothing is found.
1653     * @access private
1654     * @return mixed
1655     */
1656    function ServerVar($varName) {
1657        global $HTTP_SERVER_VARS;
1658        global $HTTP_ENV_VARS;
1659
1660        if(!isset($_SERVER))
1661        {
1662            $_SERVER = $HTTP_SERVER_VARS;
1663            if(!isset($_SERVER["REMOTE_ADDR"]))
1664                $_SERVER = $HTTP_ENV_VARS; // must be Apache
1665        }
1666       
1667        if(isset($_SERVER[$varName]))
1668            return $_SERVER[$varName];
1669        else
1670            return "";
1671    }
1672
1673    /**
1674     * Returns the server hostname or 'localhost.localdomain' if unknown.
1675     * @access private
1676     * @return string
1677     */
1678    function ServerHostname() {
1679        if ($this->Hostname != "")
1680            $result = $this->Hostname;
1681        elseif ($this->ServerVar('SERVER_NAME') != "")
1682            $result = $this->ServerVar('SERVER_NAME');
1683        else
1684            $result = "localhost.localdomain";
1685
1686        return $result;
1687    }
1688
1689    /**
1690     * Returns a message in the appropriate language.
1691     * @access private
1692     * @return string
1693     */
1694    function Lang($key) {
1695        if(count($this->language) < 1)
1696            $this->SetLanguage("br"); // set the default language
1697   
1698        if(isset($this->language[$key]))
1699            return $this->language[$key];
1700        else
1701            return "Language string failed to load: " . $key;
1702    }
1703   
1704    /**
1705     * Returns true if an error occurred.
1706     * @return bool
1707     */
1708    function IsError() {
1709        return ($this->error_count > 0);
1710    }
1711
1712    /**
1713     * Changes every end of line from CR or LF to CRLF. 
1714     * @access private
1715     * @return string
1716     */
1717    function FixEOL($str) {
1718        $str = str_replace("\r\n", "\n", $str);
1719        $str = str_replace("\r", "\n", $str);
1720        $str = str_replace("\n", $this->LE, $str);
1721        return $str;
1722    }
1723
1724    /**
1725     * Adds a custom header.
1726     * @return void
1727     */
1728    function AddCustomHeader($custom_header) {
1729        $this->CustomHeader[] = explode(":", $custom_header, 2);
1730    }
1731}
1732
1733?>
Note: See TracBrowser for help on using the repository browser.