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

Revision 2940, 54.0 KB checked in by amuller, 14 years ago (diff)

Ticket #818 - Remove a validação equívocada

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