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

Revision 7673, 53.7 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

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