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

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

Ticket #804 - Adicionando '..' na frente do caminho absoluto.

  • 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                return true;
733        $mail_retorno = FALSE;
734        if ((strlen($email) >= 6) && (substr_count($email,"@") == 1) && (substr($email,0,1) != "@") && (substr($email,strlen($email)-1,1) != "@"))
735        {
736            if ((!strstr($email,"'")) && (!strstr($email,"\"")) && (!strstr($email,"\\")) && (!strstr($email,"\$")) && (!strstr($email," ")))
737            {
738                //testa se tem caracter .
739                if (substr_count($email,".")>= 1)
740                {
741                    //obtem a terminação do dominio
742                    $term_dom = substr(strrchr ($email, '.'),1);
743                    //verifica se terminação do dominio esta correcta
744                    if (strlen($term_dom)>1 && strlen($term_dom)<5 && (!strstr($term_dom,"@")) )
745                    {
746                        $antes_dom = substr($email,0,strlen($email) - strlen($term_dom) - 1);
747                        $caracter_ult = substr($antes_dom,strlen($antes_dom)-1,1);
748                        if ($caracter_ult != "@" && $caracter_ult != ".")
749                        {
750                            $mail_retorno = TRUE;
751                        }
752                    }
753                }
754            }
755        }
756        return $mail_retorno;
757    }
758
759    /**
760     * Initiates a connection to an SMTP server.  Returns false if the
761     * operation failed.
762     * @access private
763     * @return bool
764     */
765    function SmtpConnect() {
766        if($this->smtp == NULL) { $this->smtp = new SMTP(); }
767
768        $this->smtp->do_debug = $this->SMTPDebug;
769        $hosts = explode(";", $this->Host);
770        $index = 0;
771        $connection = ($this->smtp->Connected());
772
773        // Retry while there is no connection
774        while($index < count($hosts) && $connection == false)
775        {
776            if(strstr($hosts[$index], ":"))
777                list($host, $port) = explode(":", $hosts[$index]);
778            else
779            {
780                $host = $hosts[$index];
781                $port = $this->Port;
782            }
783
784            if($this->smtp->Connect($host, $port, $this->Timeout))
785            {
786                if ($this->Helo != '')
787                    $this->smtp->Hello($this->Helo);
788                else
789                    $this->smtp->Hello($this->ServerHostname());
790       
791                if($this->SMTPAuth)
792                {
793                    if(!$this->smtp->Authenticate($this->Username,
794                                                  $this->Password))
795                    {
796                        $this->SetError($this->Lang("authenticate"));
797                        $this->smtp->Reset();
798                        $connection = false;
799                    }
800                }
801                $connection = true;
802            }
803            $index++;
804        }
805        if(!$connection)
806            $this->SetError($this->Lang("connect_host"));
807
808        return $connection;
809    }
810
811    /**
812     * Closes the active SMTP session if one exists.
813     * @return void
814     */
815    function SmtpClose() {
816        if($this->smtp != NULL)
817        {
818            if($this->smtp->Connected())
819            {
820                $this->smtp->Quit();
821                $this->smtp->Close();
822            }
823        }
824    }
825
826    /**
827     * Sets the language for all class error messages.  Returns false
828     * if it cannot load the language file.  The default language type
829     * is English.
830     * @param string $lang_type Type of language (e.g. Portuguese: "br")
831     * @param string $lang_path Path to the language file directory
832     * @access public
833     * @return bool
834     */
835    function SetLanguage($lang_type, $lang_path = "setup/") {
836        if(file_exists($lang_path.'phpmailer.lang-'.$lang_type.'.php'))
837            include($lang_path.'phpmailer.lang-'.$lang_type.'.php');
838        else if(file_exists($lang_path.'phpmailer.lang-en.php'))
839            include($lang_path.'phpmailer.lang-en.php');
840        else
841        {
842            $this->SetError("Could not load language file");
843            return false;
844        }
845        $this->language = $PHPMAILER_LANG;
846   
847        return true;
848    }
849
850    /////////////////////////////////////////////////
851    // MESSAGE CREATION METHODS
852    /////////////////////////////////////////////////
853
854    /**
855     * Creates recipient headers. 
856     * @access private
857     * @return string
858     */
859    function AddrAppend($type, $addr) {
860        $addr_str = $type . ": ";
861        $addr_str .= $this->AddrFormat($addr[0]);
862        if(count($addr) > 1)
863        {
864            for($i = 1; $i < count($addr); $i++)
865                $addr_str .= ", " . $this->AddrFormat($addr[$i]);
866        }
867        $addr_str .= $this->LE;
868
869        return $addr_str;
870    }
871   
872    /**
873     * Formats an address correctly.
874     * @access private
875     * @return string
876     */
877    function AddrFormat($addr) {
878        if(empty($addr[1]))
879            $formatted = $addr[0];
880        else
881        {
882            $formatted = $this->EncodeHeader($addr[1], 'phrase') . " <" .
883                         $addr[0] . ">";
884        }
885
886        return $formatted;
887    }
888
889    /**
890     * Wraps message for use with mailers that do not
891     * automatically perform wrapping and for quoted-printable.
892     * Original written by philippe. 
893     * @access private
894     * @return string
895     */
896    function WrapText($message, $length, $qp_mode = false) {
897        $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
898
899        $message = $this->FixEOL($message);
900        if (substr($message, -1) == $this->LE)
901            $message = substr($message, 0, -1);
902
903        $line = explode($this->LE, $message);
904        $message = "";
905        for ($i=0 ;$i < count($line); $i++)
906        {
907          $line_part = explode(" ", $line[$i]);
908          $buf = "";
909          for ($e = 0; $e<count($line_part); $e++)
910          {
911              $word = $line_part[$e];
912              if ($qp_mode and (strlen($word) > $length))
913              {
914                $space_left = $length - strlen($buf) - 1;
915                if ($e != 0)
916                {
917                    if ($space_left > 20)
918                    {
919                        $len = $space_left;
920                        if (substr($word, $len - 1, 1) == "=")
921                          $len--;
922                        elseif (substr($word, $len - 2, 1) == "=")
923                          $len -= 2;
924                        $part = substr($word, 0, $len);
925                        $word = substr($word, $len);
926                        $buf .= " " . $part;
927                        $message .= $buf . sprintf("=%s", $this->LE);
928                    }
929                    else
930                    {
931                        $message .= $buf . $soft_break;
932                    }
933                    $buf = "";
934                }
935                while (strlen($word) > 0)
936                {
937                    $len = $length;
938                    if (substr($word, $len - 1, 1) == "=")
939                        $len--;
940                    elseif (substr($word, $len - 2, 1) == "=")
941                        $len -= 2;
942                    $part = substr($word, 0, $len);
943                    $word = substr($word, $len);
944
945                    if (strlen($word) > 0)
946                        $message .= $part . sprintf("=%s", $this->LE);
947                    else
948                        $buf = $part;
949                }
950              }
951              else
952              {
953                $buf_o = $buf;
954                $buf .= ($e == 0) ? $word : (" " . $word);
955
956                if (strlen($buf) > $length and $buf_o != "")
957                {
958                    $message .= $buf_o . $soft_break;
959                    $buf = $word;
960                }
961              }
962          }
963          $message .= $buf . $this->LE;
964        }
965
966        return $message;
967    }
968   
969    /**
970     * Set the body wrapping.
971     * @access private
972     * @return void
973     */
974    function SetWordWrap() {
975        if($this->WordWrap < 1)
976            return;
977           
978        switch($this->message_type)
979        {
980           case "alt":
981              // fall through
982           case "alt_attachments":
983              $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
984              break;
985           default:
986              $this->Body = $this->WrapText($this->Body, $this->WordWrap);
987              break;
988        }
989    }
990
991    /**
992     * Assembles message header. 
993     * @access private
994     * @return string
995     */
996    function CreateHeader() {
997        $result = "";
998       
999        // Set the boundaries
1000        $uniq_id = md5(uniqid(time()));
1001        $this->boundary[1] = "b1_" . $uniq_id;
1002        $this->boundary[2] = "b2_" . $uniq_id;
1003
1004        $result .= $this->HeaderLine("Date", $this->RFCDate());
1005        if($this->Sender == "")
1006            $result .= $this->HeaderLine("Return-Path", trim($this->From));
1007        else
1008            $result .= $this->HeaderLine("Return-Path", trim($this->Sender));
1009       
1010        // To be created automatically by mail()
1011        if($this->Mailer != "mail")
1012        {
1013            if(count($this->to) > 0)
1014                $result .= $this->AddrAppend("To", $this->to);
1015            else if ((count($this->cc) == 0) && (!$this->SaveMessageAsDraft))
1016            {
1017                $result .= $this->HeaderLine("To", $this->Lang('undisclosed-recipient'));
1018            }
1019            if(count($this->cc) > 0)
1020                $result .= $this->AddrAppend("Cc", $this->cc);
1021        }
1022
1023                $from = array();
1024                $from[0][0] = trim($this->From);
1025                $from[0][1] = $this->FromName;
1026                $result .= $this->AddrAppend("From", $from);
1027/*
1028                if (!$this->SaveMessageAsDraft){
1029                $from = array();
1030            $from[0][0] = trim($this->From);
1031                $from[0][1] = $this->FromName;
1032                $result .= $this->AddrAppend("From", $from);
1033                }
1034                if($this->Sender) {
1035                        $sender = array();
1036                        $sender[0][0] = trim($this->Sender);
1037                $sender[0][1] = $this->SenderName;
1038                $result .= $this->AddrAppend("Sender", $sender);
1039                }
1040*/
1041        // sendmail and mail() extract Bcc from the header before sending
1042        if((($this->Mailer == "sendmail") || ($this->Mailer == "mail")) && (count($this->bcc) > 0))
1043            $result .= $this->AddrAppend("Bcc", $this->bcc);
1044        if ($this->SaveMessageAsDraft){
1045            $result .= $this->AddrAppend("Bcc", $this->bcc);
1046                }
1047        if(count($this->ReplyTo) > 0)
1048            $result .= $this->AddrAppend("Reply-to", $this->ReplyTo);
1049
1050        // mail() sets the subject itself
1051        if($this->Mailer != "mail")
1052            $result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject)));
1053
1054        $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
1055        $result .= $this->HeaderLine("X-Priority", $this->Priority);
1056        $result .= $this->HeaderLine("Importance", $this->Importance);
1057        $result .= $this->HeaderLine("X-Mailer", "ExpressoMail [version " . $this->Version . "]");
1058       
1059        if($this->ConfirmReadingTo != "")
1060        {
1061            $result .= $this->HeaderLine("Disposition-Notification-To",
1062                       "<" . trim($this->ConfirmReadingTo) . ">");
1063        }
1064
1065        // Add custom headers
1066        for($index = 0; $index < count($this->CustomHeader); $index++)
1067        {
1068            $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]),
1069                       $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
1070        }
1071        $result .= $this->HeaderLine("MIME-Version", "1.0");
1072
1073        $result .= $this->write_message_type();
1074
1075        if($this->Mailer != "mail")
1076            $result .= $this->LE.$this->LE;
1077
1078        return $result;
1079    }
1080
1081
1082    function write_message_type()
1083        {
1084                $result = "";
1085        switch($this->message_type)
1086        {
1087            case "plain":$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
1088                $result .= $this->HeaderLine("Content-Transfer-Encoding", $this->Encoding);
1089                $result .= sprintf("Content-Type: %s; charset=\"%s\"",
1090                                    $this->ContentType, $this->CharSet);
1091                return $result;
1092            case "attachments":
1093                // fall through
1094            case "alt_attachments":
1095                if($this->InlineImageExists())
1096                {
1097                    $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s",
1098                                    "multipart/related", $this->LE, $this->LE,
1099                                    $this->boundary[1], $this->LE);
1100                }
1101                else
1102                {
1103                    $result .= $this->HeaderLine("Content-Type", "multipart/mixed;");
1104                    $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1105                }
1106                return $result;
1107            case "alt":
1108                $result .= $this->HeaderLine("Content-Type", "multipart/alternative;");
1109                $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1110                return $result;
1111        }
1112
1113        if($this->Mailer != "mail")
1114            $result .= $this->LE.$this->LE;
1115
1116        return $result;
1117    }
1118
1119    /**
1120     * Assembles the message body.  Returns an empty string on failure.
1121     * @access private
1122     * @return string
1123     */
1124    function CreateBody() {
1125        $result = "";
1126
1127        $this->SetWordWrap();
1128        switch($this->message_type)
1129        {
1130            case "alt":
1131                $result .= $this->GetBoundary($this->boundary[1], "",
1132                                              "text/plain", "");
1133                $result .= $this->EncodeString($this->AltBody, $this->Encoding);
1134                $result .= $this->LE.$this->LE;
1135                $result .= $this->GetBoundary($this->boundary[1], "",
1136                                              "text/html", "");
1137               
1138                $result .= $this->EncodeString($this->Body, $this->Encoding);
1139                $result .= $this->LE.$this->LE;
1140   
1141                $result .= $this->EndBoundary($this->boundary[1]);
1142                break;
1143            case "plain":
1144                $result .= $this->EncodeString($this->Body, $this->Encoding);
1145                break;
1146            case "attachments":
1147                $result .= $this->GetBoundary($this->boundary[1], "", "", "");
1148                $result .= $this->EncodeString($this->Body, $this->Encoding);
1149                $result .= $this->LE;
1150     
1151                $result .= $this->AttachAll();
1152                break;
1153            case "alt_attachments":
1154                $result .= sprintf("--%s%s", $this->boundary[1], $this->LE);
1155                $result .= sprintf("Content-Type: %s;%s" .
1156                                   "\tboundary=\"%s\"%s",
1157                                   "multipart/alternative", $this->LE,
1158                                   $this->boundary[2], $this->LE.$this->LE);
1159   
1160                // Create text body
1161                $result .= $this->GetBoundary($this->boundary[2], "",
1162                                              "text/plain", "") . $this->LE;
1163
1164                $result .= $this->EncodeString($this->AltBody, $this->Encoding);
1165                $result .= $this->LE.$this->LE;
1166   
1167                // Create the HTML body
1168                $result .= $this->GetBoundary($this->boundary[2], "",
1169                                              "text/html", "") . $this->LE;
1170   
1171                $result .= $this->EncodeString($this->Body, $this->Encoding);
1172                $result .= $this->LE.$this->LE;
1173
1174                $result .= $this->EndBoundary($this->boundary[2]);
1175               
1176                $result .= $this->AttachAll();
1177                break;
1178        }
1179        if($this->IsError())
1180            $result = "";
1181
1182        return $result;
1183    }
1184
1185    /**
1186     * Returns the start of a message boundary.
1187     * @access private
1188     */
1189    function GetBoundary($boundary, $charSet, $contentType, $encoding) {
1190        $result = "";
1191        if($charSet == "") { $charSet = $this->CharSet; }
1192        if($contentType == "") { $contentType = $this->ContentType; }
1193        if($encoding == "") { $encoding = $this->Encoding; }
1194
1195        $result .= $this->TextLine("--" . $boundary);
1196        $result .= sprintf("Content-Type: %s; charset = \"%s\"",
1197                            $contentType, $charSet);
1198        $result .= $this->LE;
1199        $result .= $this->HeaderLine("Content-Transfer-Encoding", $encoding);
1200        $result .= $this->LE;
1201       
1202        return $result;
1203    }
1204   
1205    /**
1206     * Returns the end of a message boundary.
1207     * @access private
1208     */
1209    function EndBoundary($boundary) {
1210        return $this->LE . "--" . $boundary . "--" . $this->LE;
1211    }
1212   
1213    /**
1214     * Sets the message type.
1215     * @access private
1216     * @return void
1217     */
1218    function SetMessageType() {
1219        if(count($this->attachment) < 1 && strlen($this->AltBody) < 1)
1220            $this->message_type = "plain";
1221        else
1222        {
1223            if(count($this->attachment) > 0)
1224                $this->message_type = "attachments";
1225            if(strlen($this->AltBody) > 0 && count($this->attachment) < 1)
1226                $this->message_type = "alt";
1227            if(strlen($this->AltBody) > 0 && count($this->attachment) > 0)
1228                $this->message_type = "alt_attachments";
1229        }
1230    }
1231
1232    /**
1233     * Returns a formatted header line.
1234     * @access private
1235     * @return string
1236     */
1237    function HeaderLine($name, $value) {
1238        return $name . ": " . $value . $this->LE;
1239    }
1240
1241    /**
1242     * Returns a formatted mail line.
1243     * @access private
1244     * @return string
1245     */
1246    function TextLine($value) {
1247        return $value . $this->LE;
1248    }
1249
1250    /////////////////////////////////////////////////
1251    // ATTACHMENT METHODS
1252    /////////////////////////////////////////////////
1253
1254    /**
1255     * Adds an attachment from a path on the filesystem.
1256     * Returns false if the file could not be found
1257     * or accessed.
1258     * @param string $path Path to the attachment.
1259     * @param string $name Overrides the attachment name.
1260     * @param string $encoding File encoding (see $Encoding).
1261     * @param string $type File extension (MIME) type.
1262     * @return bool
1263     */
1264    function AddAttachment($path, $name = "", $encoding = "base64",
1265                           $type = "application/octet-stream") {
1266        if(!@is_file($path))
1267        {
1268            $this->SetError($this->Lang("file_access") . $path);
1269            return false;
1270        }
1271
1272        $filename = basename($path);
1273        if($name == "")
1274            $name = $filename;
1275
1276        $cur = count($this->attachment);
1277        $this->attachment[$cur][0] = $path;
1278        $this->attachment[$cur][1] = $filename;
1279        $this->attachment[$cur][2] = $name;
1280        $this->attachment[$cur][3] = $encoding;
1281        $this->attachment[$cur][4] = $type;
1282        $this->attachment[$cur][5] = false; // isStringAttachment
1283        $this->attachment[$cur][6] = "attachment";
1284        $this->attachment[$cur][7] = 0;
1285
1286        return true;
1287    }
1288
1289    /**
1290     * Attaches all fs, string, and binary attachments to the message.
1291     * Returns an empty string on failure.
1292     * @access private
1293     * @return string
1294     */
1295    function AttachAll() {
1296        // Return text of body
1297        $mime = array();
1298
1299        // Add all attachments
1300        for($i = 0; $i < count($this->attachment); $i++)
1301        {
1302            // Check for string attachment
1303            $bString = $this->attachment[$i][5];
1304            if ($bString)
1305                $string = $this->attachment[$i][0];
1306            else
1307                $path = $this->attachment[$i][0];
1308
1309            $filename    = $this->attachment[$i][1];
1310            $name        = $this->attachment[$i][2];
1311            $encoding    = $this->attachment[$i][3];
1312            $type        = $this->attachment[$i][4];
1313            $disposition = $this->attachment[$i][6];
1314            $cid         = $this->attachment[$i][7];
1315           
1316            $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
1317            $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $name, $this->LE);
1318            $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
1319
1320            if($disposition == "inline")
1321                $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
1322
1323            $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s",
1324                              $disposition, $name, $this->LE.$this->LE);
1325
1326            // Encode as string attachment
1327            if($bString)
1328            {
1329                $mime[] = $this->EncodeString($string, $encoding);
1330                if($this->IsError()) { return ""; }
1331                $mime[] = $this->LE.$this->LE;
1332            }
1333            else
1334            {
1335                $mime[] = $this->EncodeFile($path, $encoding);               
1336                if($this->IsError()) { return ""; }
1337                $mime[] = $this->LE.$this->LE;
1338            }
1339        }
1340
1341        $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
1342
1343        return join("", $mime);
1344    }
1345   
1346    /**
1347     * Encodes attachment in requested format.  Returns an
1348     * empty string on failure.
1349     * @access private
1350     * @return string
1351     */
1352    function EncodeFile ($path, $encoding = "base64") {
1353        if(!@$fd = fopen($path, "rb"))
1354        {
1355            $this->SetError($this->Lang("file_open") . $path);
1356            return "";
1357        }
1358        $magic_quotes = get_magic_quotes_runtime();
1359        set_magic_quotes_runtime(0);
1360        $file_buffer = fread($fd, filesize($path));
1361        $file_buffer = $this->EncodeString($file_buffer, $encoding);
1362        fclose($fd);
1363        set_magic_quotes_runtime($magic_quotes);
1364
1365        return $file_buffer;
1366    }
1367
1368    /**
1369     * Encodes string to requested format. Returns an
1370     * empty string on failure.
1371     * @access private
1372     * @return string
1373     */
1374    function EncodeString ($str, $encoding = "base64") {
1375        $encoded = "";
1376        switch(strtolower($encoding)) {
1377          case "base64":
1378              // chunk_split is found in PHP >= 3.0.6
1379              $encoded = @chunk_split(base64_encode($str), 76, $this->LE);
1380              break;
1381          case "7bit":
1382          case "8bit":
1383              $encoded = $this->FixEOL($str);
1384              if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1385                $encoded .= $this->LE;
1386              break;
1387          case "binary":
1388              $encoded = $str;
1389              break;
1390          case "quoted-printable":
1391              $encoded = $this->EncodeQP($str);
1392              break;
1393          default:
1394              $this->SetError($this->Lang("encoding") . $encoding);
1395              break;
1396        }
1397        return $encoded;
1398    }
1399
1400    /**
1401     * Encode a header string to best of Q, B, quoted or none. 
1402     * @access private
1403     * @return string
1404     */
1405    function EncodeHeader ($str, $position = 'text') {
1406      $x = 0;
1407     
1408      switch (strtolower($position)) {
1409        case 'phrase':
1410          if (!preg_match('/[\200-\377]/', $str)) {
1411            // Can't use addslashes as we don't know what value has magic_quotes_sybase.
1412            $encoded = addcslashes($str, "\0..\37\177\\\"");
1413
1414            if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str))
1415              return ($encoded);
1416            else
1417              return ("\"$encoded\"");
1418          }
1419          $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
1420          break;
1421        case 'comment':
1422          $x = preg_match_all('/[()"]/', $str, $matches);
1423          // Fall-through
1424        case 'text':
1425        default:
1426          $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
1427          break;
1428      }
1429
1430      if ($x == 0)
1431        return ($str);
1432
1433      $maxlen = 75 - 7 - strlen($this->CharSet);
1434      // Try to select the encoding which should produce the shortest output
1435      if (strlen($str)/3 < $x) {
1436        $encoding = 'B';
1437        $encoded = base64_encode($str);
1438        $maxlen -= $maxlen % 4;
1439        $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
1440      } else {
1441        $encoding = 'Q';
1442        $encoded = $this->EncodeQ($str, $position);
1443        $encoded = $this->WrapText($encoded, $maxlen, true);
1444        $encoded = str_replace("=".$this->LE, "\n", trim($encoded));
1445      }
1446
1447      $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
1448      $encoded = trim(str_replace("\n", $this->LE, $encoded));
1449     
1450      return $encoded;
1451    }
1452   
1453    /**
1454     * Encode string to quoted-printable. 
1455     * @access private
1456     * @return string
1457     */
1458    function EncodeQP ($str) {
1459        $encoded = $this->FixEOL($str);
1460        if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1461            $encoded .= $this->LE;
1462
1463        // Replace every high ascii, control and = characters
1464        $encoded = preg_replace('/([\000-\010\013\014\016-\037\075\177-\377])/e',
1465                  "'='.sprintf('%02X', ord('\\1'))", $encoded);
1466        // Replace every spaces and tabs when it's the last character on a line
1467        $encoded = preg_replace("/([\011\040])".$this->LE."/e",
1468                  "'='.sprintf('%02X', ord('\\1')).'".$this->LE."'", $encoded);
1469
1470        // Maximum line length of 76 characters before CRLF (74 + space + '=')
1471        $encoded = $this->WrapText($encoded, 74, true);
1472               
1473        return $encoded;
1474    }
1475
1476    /**
1477     * Encode string to q encoding. 
1478     * @access private
1479     * @return string
1480     */
1481    function EncodeQ ($str, $position = "text") {
1482        // There should not be any EOL in the string
1483        $encoded = preg_replace("[\r\n]", "", $str);
1484        switch (strtolower($position)) {
1485          case "phrase":
1486            $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1487            break;
1488          case "comment":
1489            $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1490          case "text":
1491          default:
1492            // Replace every high ascii, control =, ? and _ characters
1493            $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
1494                  "'='.sprintf('%02X', ord('\\1'))", $encoded);
1495            break;
1496        }
1497       
1498        // Replace every spaces to _ (more readable than =20)
1499        $encoded = str_replace(" ", "_", $encoded);
1500
1501        return $encoded;
1502    }
1503
1504    /**
1505     * Adds a string or binary attachment (non-filesystem) to the list.
1506     * This method can be used to attach ascii or binary data,
1507     * such as a BLOB record from a database.
1508     * @param string $string String attachment data.
1509     * @param string $filename Name of the attachment.
1510     * @param string $encoding File encoding (see $Encoding).
1511     * @param string $type File extension (MIME) type.
1512     * @return void
1513     */
1514    function AddStringAttachment($string, $filename, $encoding = "base64",
1515                                 $type = "application/octet-stream") {
1516        // Append to $attachment array
1517        $cur = count($this->attachment);
1518        $this->attachment[$cur][0] = $string;
1519        $this->attachment[$cur][1] = $filename;
1520        $this->attachment[$cur][2] = $filename;
1521        $this->attachment[$cur][3] = $encoding;
1522        $this->attachment[$cur][4] = $type;
1523        $this->attachment[$cur][5] = true; // isString
1524        $this->attachment[$cur][6] = "attachment";
1525        $this->attachment[$cur][7] = 0;
1526    }
1527   
1528    /**
1529     * Adds an embedded attachment.  This can include images, sounds, and
1530     * just about any other document.  Make sure to set the $type to an
1531     * image type.  For JPEG images use "image/jpeg" and for GIF images
1532     * use "image/gif".
1533     * @param string $path Path to the attachment.
1534     * @param string $cid Content ID of the attachment.  Use this to identify
1535     *        the Id for accessing the image in an HTML form.
1536     * @param string $name Overrides the attachment name.
1537     * @param string $encoding File encoding (see $Encoding).
1538     * @param string $type File extension (MIME) type. 
1539     * @return bool
1540     */
1541    function AddEmbeddedImage($path, $cid, $name = "", $encoding = "base64",
1542                              $type = "application/octet-stream") {
1543   
1544        if(!@is_file($path))
1545        {
1546            $this->SetError($this->Lang("file_access") . $path);
1547            return false;
1548        }
1549
1550        $filename = basename($path);
1551        if($name == "")
1552            $name = $filename;
1553
1554        // Append to $attachment array
1555        $cur = count($this->attachment);
1556        $this->attachment[$cur][0] = $path;
1557        $this->attachment[$cur][1] = $filename;
1558        $this->attachment[$cur][2] = $name;
1559        $this->attachment[$cur][3] = $encoding;
1560        $this->attachment[$cur][4] = $type;
1561        $this->attachment[$cur][5] = false; // isStringAttachment
1562        $this->attachment[$cur][6] = "inline";
1563        $this->attachment[$cur][7] = $cid;
1564   
1565        return true;
1566    }
1567   
1568    /**
1569     * Returns true if an inline attachment is present.
1570     * @access private
1571     * @return bool
1572     */
1573    function InlineImageExists() {
1574        $result = false;
1575        for($i = 0; $i < count($this->attachment); $i++)
1576        {
1577            if($this->attachment[$i][6] == "inline")
1578            {
1579                $result = true;
1580                break;
1581            }
1582        }
1583       
1584        return $result;
1585    }
1586
1587    /////////////////////////////////////////////////
1588    // MESSAGE RESET METHODS
1589    /////////////////////////////////////////////////
1590
1591    /**
1592     * Clears all recipients assigned in the TO array.  Returns void.
1593     * @return void
1594     */
1595    function ClearAddresses() {
1596        $this->to = array();
1597    }
1598
1599    /**
1600     * Clears all recipients assigned in the CC array.  Returns void.
1601     * @return void
1602     */
1603    function ClearCCs() {
1604        $this->cc = array();
1605    }
1606
1607    /**
1608     * Clears all recipients assigned in the BCC array.  Returns void.
1609     * @return void
1610     */
1611    function ClearBCCs() {
1612        $this->bcc = array();
1613    }
1614
1615    /**
1616     * Clears all recipients assigned in the ReplyTo array.  Returns void.
1617     * @return void
1618     */
1619    function ClearReplyTos() {
1620        $this->ReplyTo = array();
1621    }
1622
1623    /**
1624     * Clears all recipients assigned in the TO, CC and BCC
1625     * array.  Returns void.
1626     * @return void
1627     */
1628    function ClearAllRecipients() {
1629        $this->to = array();
1630        $this->cc = array();
1631        $this->bcc = array();
1632    }
1633
1634    /**
1635     * Clears all previously set filesystem, string, and binary
1636     * attachments.  Returns void.
1637     * @return void
1638     */
1639    function ClearAttachments() {
1640        $this->attachment = array();
1641    }
1642
1643    /**
1644     * Clears all custom headers.  Returns void.
1645     * @return void
1646     */
1647    function ClearCustomHeaders() {
1648        $this->CustomHeader = array();
1649    }
1650
1651
1652    /////////////////////////////////////////////////
1653    // MISCELLANEOUS METHODS
1654    /////////////////////////////////////////////////
1655
1656    /**
1657     * Adds the error message to the error container.
1658     * Returns void.
1659     * @access private
1660     * @return void
1661     */
1662    function SetError($msg) {
1663        $this->error_count++;
1664        $this->ErrorInfo = $msg;
1665    }
1666
1667    /**
1668     * Returns the proper RFC 822 formatted date.
1669     * @access private
1670     * @return string
1671     */
1672    function RFCDate() {
1673        $tz = date("Z");
1674        $tzs = ($tz < 0) ? "-" : "+";
1675        $tz = abs($tz);
1676        $tz = ($tz/3600)*100 + ($tz%3600)/60;
1677        $result = sprintf("%s %s%04d", date("D, j M Y H:i:s"), $tzs, $tz);
1678
1679        return $result;
1680    }
1681   
1682    /**
1683     * Returns the appropriate server variable.  Should work with both
1684     * PHP 4.1.0+ as well as older versions.  Returns an empty string
1685     * if nothing is found.
1686     * @access private
1687     * @return mixed
1688     */
1689    function ServerVar($varName) {
1690        global $HTTP_SERVER_VARS;
1691        global $HTTP_ENV_VARS;
1692
1693        if(!isset($_SERVER))
1694        {
1695            $_SERVER = $HTTP_SERVER_VARS;
1696            if(!isset($_SERVER["REMOTE_ADDR"]))
1697                $_SERVER = $HTTP_ENV_VARS; // must be Apache
1698        }
1699       
1700        if(isset($_SERVER[$varName]))
1701            return $_SERVER[$varName];
1702        else
1703            return "";
1704    }
1705
1706    /**
1707     * Returns the server hostname or 'localhost.localdomain' if unknown.
1708     * @access private
1709     * @return string
1710     */
1711    function ServerHostname() {
1712        if ($this->Hostname != "")
1713            $result = $this->Hostname;
1714        elseif ($this->ServerVar('SERVER_NAME') != "")
1715            $result = $this->ServerVar('SERVER_NAME');
1716        else
1717            $result = "localhost.localdomain";
1718
1719        return $result;
1720    }
1721
1722    /**
1723     * Returns a message in the appropriate language.
1724     * @access private
1725     * @return string
1726     */
1727    function Lang($key) {
1728        if(count($this->language) < 1)
1729            $this->SetLanguage("br"); // set the default language
1730   
1731        if(isset($this->language[$key]))
1732            return $this->language[$key];
1733        else
1734            return "Language string failed to load: " . $key;
1735    }
1736   
1737    /**
1738     * Returns true if an error occurred.
1739     * @return bool
1740     */
1741    function IsError() {
1742        return ($this->error_count > 0);
1743    }
1744
1745    /**
1746     * Changes every end of line from CR or LF to CRLF. 
1747     * @access private
1748     * @return string
1749     */
1750    function FixEOL($str) {
1751        $str = str_replace("\r\n", "\n", $str);
1752        $str = str_replace("\r", "\n", $str);
1753        $str = str_replace("\n", $this->LE, $str);
1754        return $str;
1755    }
1756
1757    /**
1758     * Adds a custom header.
1759     * @return void
1760     */
1761    function AddCustomHeader($custom_header) {
1762        $this->CustomHeader[] = explode(":", $custom_header, 2);
1763    }
1764}
1765
1766?>
Note: See TracBrowser for help on using the repository browser.