source: sandbox/expressoMail1_2/corretor_ortografico/inc/class.phpmailer.php @ 1793

Revision 1793, 54.1 KB checked in by rodsouza, 14 years ago (diff)

Ticket #810 - Desfazendo envio de arquivo errado na revisão 1792.

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