2 ////////////////////////////////////////////////////
3 // PHPMailer - PHP email class
5 // Class for sending email using either
6 // sendmail, PHP mail(), or SMTP. Methods are
7 // based upon the standard AspEmail(tm) classes.
9 // Copyright (C) 2001 - 2003 Brent R. Matzelle
11 // License: LGPL, see LICENSE
12 ////////////////////////////////////////////////////
15 * PHPMailer - PHP email transport class
17 * @author Brent R. Matzelle
18 * @copyright 2001 - 2003 Brent R. Matzelle
22 /////////////////////////////////////////////////
24 /////////////////////////////////////////////////
27 * Email priority (1 = High, 3 = Normal, 5 = low).
33 * Sets the CharSet of the message.
36 var $CharSet = "iso-8859-1";
39 * Sets the Content-type of the message.
42 var $ContentType = "text/plain";
45 * Sets the Encoding of the message. Options for this are "8bit",
46 * "7bit", "binary", "base64", and "quoted-printable".
49 var $Encoding = "8bit";
52 * Holds the most recent mailer error message.
58 * Sets the From email address for the message.
61 var $From = "root@localhost";
64 * Sets the From name of the message.
67 var $FromName = "Root User";
70 * Sets the Sender email (Return-Path) of the message. If not empty,
71 * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
77 * Sets the Subject of the message.
83 * Sets the Body of the message. This can be either an HTML or text body.
84 * If HTML then run IsHTML(true).
90 * Sets the text-only body of the message. This automatically sets the
91 * email to multipart/alternative. This body can be read by mail
92 * clients that do not have HTML email capability such as mutt. Clients
93 * that can read HTML will view the normal Body.
99 * Sets word wrapping on the body of the message to a given number of
106 * Method to send mail: ("mail", "sendmail", or "smtp").
109 var $Mailer = "mail";
112 * Sets the path of the sendmail program.
115 var $Sendmail = "/usr/sbin/sendmail";
118 * Path to PHPMailer plugins. This is now only useful if the SMTP class
119 * is in a different directory than the PHP include path.
125 * Holds PHPMailer version.
128 var $Version = "1.73";
131 * Sets the email address that a reading confirmation will be sent.
134 var $ConfirmReadingTo = "";
137 * Sets the hostname to use in Message-Id and Received headers
138 * and as default HELO string. If empty, the value returned
139 * by SERVER_NAME is used or 'localhost.localdomain'.
144 /////////////////////////////////////////////////
146 /////////////////////////////////////////////////
149 * Sets the SMTP hosts. All hosts must be separated by a
150 * semicolon. You can also specify a different port
151 * for each host by using this format: [hostname:port]
152 * (e.g. "smtp1.example.com:25;smtp2.example.com").
153 * Hosts will be tried in order.
156 var $Host = "localhost";
159 * Sets the default SMTP server port.
165 * Sets the SMTP HELO of the message (Default is $Hostname).
171 * Sets SMTP authentication. Utilizes the Username and Password variables.
174 var $SMTPAuth = false;
177 * Sets SMTP username.
183 * Sets SMTP password.
189 * Sets the SMTP server timeout in seconds. This function will not
190 * work with the win32 version.
196 * Sets SMTP class debugging on or off.
199 var $SMTPDebug = false;
202 * Prevents the SMTP connection from being closed after each mail
203 * sending. If this is set to true then to close the connection
204 * requires an explicit call to SmtpClose().
207 var $SMTPKeepAlive = false;
216 var $ReplyTo = array();
217 var $attachment = array();
218 var $CustomHeader = array();
219 var $message_type = "";
220 var $boundary = array();
221 var $language = array();
222 var $error_count = 0;
226 /////////////////////////////////////////////////
228 /////////////////////////////////////////////////
232 * Hack for Moodle as class may be included from various locations
237 function PHPMailer () {
239 $this->PluginDir
= $CFG->libdir
.'/phpmailer/';
245 * Sets message type to HTML.
249 function IsHTML($bool) {
251 $this->ContentType
= "text/html";
253 $this->ContentType
= "text/plain";
257 * Sets Mailer to send message using SMTP.
261 $this->Mailer
= "smtp";
265 * Sets Mailer to send message using PHP mail() function.
269 $this->Mailer
= "mail";
273 * Sets Mailer to send message using the $Sendmail program.
276 function IsSendmail() {
277 $this->Mailer
= "sendmail";
281 * Sets Mailer to send message using the qmail MTA.
285 $this->Sendmail
= "/var/qmail/bin/sendmail";
286 $this->Mailer
= "sendmail";
290 /////////////////////////////////////////////////
292 /////////////////////////////////////////////////
295 * Adds a "To" address.
296 * @param string $address
297 * @param string $name
300 function AddAddress($address, $name = "") {
301 $cur = count($this->to
);
302 $this->to
[$cur][0] = trim($address);
303 $this->to
[$cur][1] = $name;
307 * Adds a "Cc" address. Note: this function works
308 * with the SMTP mailer on win32, not with the "mail"
310 * @param string $address
311 * @param string $name
314 function AddCC($address, $name = "") {
315 $cur = count($this->cc
);
316 $this->cc
[$cur][0] = trim($address);
317 $this->cc
[$cur][1] = $name;
321 * Adds a "Bcc" address. Note: this function works
322 * with the SMTP mailer on win32, not with the "mail"
324 * @param string $address
325 * @param string $name
328 function AddBCC($address, $name = "") {
329 $cur = count($this->bcc
);
330 $this->bcc
[$cur][0] = trim($address);
331 $this->bcc
[$cur][1] = $name;
335 * Adds a "Reply-to" address.
336 * @param string $address
337 * @param string $name
340 function AddReplyTo($address, $name = "") {
341 $cur = count($this->ReplyTo
);
342 $this->ReplyTo
[$cur][0] = trim($address);
343 $this->ReplyTo
[$cur][1] = $name;
347 /////////////////////////////////////////////////
348 // MAIL SENDING METHODS
349 /////////////////////////////////////////////////
352 * Creates message and assigns Mailer. If the message is
353 * not sent successfully then it returns false. Use the ErrorInfo
354 * variable to view description of the error.
362 if((count($this->to
) +
count($this->cc
) +
count($this->bcc
)) < 1)
364 $this->SetError($this->Lang("provide_address"));
368 // Set whether the message is multipart/alternative
369 if(!empty($this->AltBody
))
370 $this->ContentType
= "multipart/alternative";
372 $this->error_count
= 0; // reset errors
373 $this->SetMessageType();
374 $header .= $this->CreateHeader();
375 $body = $this->CreateBody();
377 if($body == "") { return false; }
380 switch($this->Mailer
)
383 $result = $this->SendmailSend($header, $body);
386 $result = $this->MailSend($header, $body);
389 $result = $this->SmtpSend($header, $body);
392 $this->SetError($this->Mailer
. $this->Lang("mailer_not_supported"));
401 * Sends mail using the $Sendmail program.
405 function SendmailSend($header, $body) {
406 if ($this->Sender
!= "")
407 $sendmail = sprintf("%s -oi -f %s -t", $this->Sendmail
, $this->Sender
);
409 $sendmail = sprintf("%s -oi -t", $this->Sendmail
);
411 if(!@$mail = popen($sendmail, "w"))
413 $this->SetError($this->Lang("execute") . $this->Sendmail
);
417 fputs($mail, $header);
420 $result = pclose($mail) >> 8 & 0xFF;
423 $this->SetError($this->Lang("execute") . $this->Sendmail
);
431 * Sends mail using the PHP mail() function.
435 function MailSend($header, $body) {
437 for($i = 0; $i < count($this->to
); $i++
)
439 if($i != 0) { $to .= ", "; }
440 $to .= $this->to
[$i][0];
443 if ($this->Sender
!= "" && strlen(ini_get("safe_mode"))< 1)
445 $old_from = ini_get("sendmail_from");
446 ini_set("sendmail_from", $this->Sender
);
447 $params = sprintf("-oi -f %s", $this->Sender
);
448 $rt = @mail
($to, $this->EncodeHeader($this->Subject
), $body,
452 $rt = @mail
($to, $this->EncodeHeader($this->Subject
), $body, $header);
454 if (isset($old_from))
455 ini_set("sendmail_from", $old_from);
459 $this->SetError($this->Lang("instantiate"));
467 * Sends mail via SMTP using PhpSMTP (Author:
468 * Chris Ryan). Returns bool. Returns false if there is a
469 * bad MAIL FROM, RCPT, or DATA input.
473 function SmtpSend($header, $body) {
474 include_once($this->PluginDir
."class.smtp.php");
478 if(!$this->SmtpConnect())
481 $smtp_from = ($this->Sender
== "") ?
$this->From
: $this->Sender
;
482 if(!$this->smtp
->Mail($smtp_from))
484 $error = $this->Lang("from_failed") . $smtp_from;
485 $this->SetError($error);
486 $this->smtp
->Reset();
490 // Attempt to send attach all recipients
491 for($i = 0; $i < count($this->to
); $i++
)
493 if(!$this->smtp
->Recipient($this->to
[$i][0]))
494 $bad_rcpt[] = $this->to
[$i][0];
496 for($i = 0; $i < count($this->cc
); $i++
)
498 if(!$this->smtp
->Recipient($this->cc
[$i][0]))
499 $bad_rcpt[] = $this->cc
[$i][0];
501 for($i = 0; $i < count($this->bcc
); $i++
)
503 if(!$this->smtp
->Recipient($this->bcc
[$i][0]))
504 $bad_rcpt[] = $this->bcc
[$i][0];
507 if(count($bad_rcpt) > 0) // Create error message
509 for($i = 0; $i < count($bad_rcpt); $i++
)
511 if($i != 0) { $error .= ", "; }
512 $error .= $bad_rcpt[$i];
514 $error = $this->Lang("recipients_failed") . $error;
515 $this->SetError($error);
516 $this->smtp
->Reset();
520 if(!$this->smtp
->Data($header . $body))
522 $this->SetError($this->Lang("data_not_accepted"));
523 $this->smtp
->Reset();
526 if($this->SMTPKeepAlive
== true)
527 $this->smtp
->Reset();
535 * Initiates a connection to an SMTP server. Returns false if the
540 function SmtpConnect() {
541 if($this->smtp
== NULL) { $this->smtp
= new SMTP(); }
543 $this->smtp
->do_debug
= $this->SMTPDebug
;
544 $hosts = explode(";", $this->Host
);
546 $connection = ($this->smtp
->Connected());
548 // Retry while there is no connection
549 while($index < count($hosts) && $connection == false)
551 if(strstr($hosts[$index], ":"))
552 list($host, $port) = explode(":", $hosts[$index]);
555 $host = $hosts[$index];
559 if($this->smtp
->Connect($host, $port, $this->Timeout
))
561 if ($this->Helo
!= '')
562 $this->smtp
->Hello($this->Helo
);
564 $this->smtp
->Hello($this->ServerHostname());
568 if(!$this->smtp
->Authenticate($this->Username
,
571 $this->SetError($this->Lang("authenticate"));
572 $this->smtp
->Reset();
581 $this->SetError($this->Lang("connect_host"));
587 * Closes the active SMTP session if one exists.
590 function SmtpClose() {
591 if($this->smtp
!= NULL)
593 if($this->smtp
->Connected())
596 $this->smtp
->Close();
602 * Sets the language for all class error messages. Returns false
603 * if it cannot load the language file. The default language type
605 * SE 20041001: Added '$this->PluginDir' for Moodle compatibility
607 * @param string $lang_type Type of language (e.g. Portuguese: "br")
608 * @param string $lang_path Path to the language file directory
612 function SetLanguage($lang_type, $lang_path = "language/") {
613 if(file_exists($this->PluginDir
.$lang_path.'phpmailer.lang-'.$lang_type.'.php'))
614 include($this->PluginDir
.$lang_path.'phpmailer.lang-'.$lang_type.'.php');
615 else if(file_exists($lang_path.'phpmailer.lang-en.php'))
616 include($this->PluginDir
.$lang_path.'phpmailer.lang-en.php');
619 $this->SetError("Could not load language file");
622 $this->language
= $PHPMAILER_LANG;
627 /////////////////////////////////////////////////
628 // MESSAGE CREATION METHODS
629 /////////////////////////////////////////////////
632 * Creates recipient headers.
636 function AddrAppend($type, $addr) {
637 $addr_str = $type . ": ";
638 $addr_str .= $this->AddrFormat($addr[0]);
641 for($i = 1; $i < count($addr); $i++
)
642 $addr_str .= ", " . $this->AddrFormat($addr[$i]);
644 $addr_str .= $this->LE
;
650 * Formats an address correctly.
654 function AddrFormat($addr) {
656 $formatted = $addr[0];
659 $formatted = $this->EncodeHeader($addr[1], 'phrase') . " <" .
667 * Wraps message for use with mailers that do not
668 * automatically perform wrapping and for quoted-printable.
669 * Original written by philippe.
673 function WrapText($message, $length, $qp_mode = false) {
674 $soft_break = ($qp_mode) ?
sprintf(" =%s", $this->LE
) : $this->LE
;
676 $message = $this->FixEOL($message);
677 if (substr($message, -1) == $this->LE
)
678 $message = substr($message, 0, -1);
680 $line = explode($this->LE
, $message);
682 for ($i=0 ;$i < count($line); $i++
)
684 $line_part = explode(" ", $line[$i]);
686 for ($e = 0; $e<count($line_part); $e++
)
688 $word = $line_part[$e];
689 if ($qp_mode and (strlen($word) > $length))
691 $space_left = $length - strlen($buf) - 1;
694 if ($space_left > 20)
697 if (substr($word, $len - 1, 1) == "=")
699 elseif (substr($word, $len - 2, 1) == "=")
701 $part = substr($word, 0, $len);
702 $word = substr($word, $len);
704 $message .= $buf . sprintf("=%s", $this->LE
);
708 $message .= $buf . $soft_break;
712 while (strlen($word) > 0)
715 if (substr($word, $len - 1, 1) == "=")
717 elseif (substr($word, $len - 2, 1) == "=")
719 $part = substr($word, 0, $len);
720 $word = substr($word, $len);
722 if (strlen($word) > 0)
723 $message .= $part . sprintf("=%s", $this->LE
);
731 $buf .= ($e == 0) ?
$word : (" " . $word);
733 if (strlen($buf) > $length and $buf_o != "")
735 $message .= $buf_o . $soft_break;
740 $message .= $buf . $this->LE
;
747 * Set the body wrapping.
751 function SetWordWrap() {
752 if($this->WordWrap
< 1)
755 switch($this->message_type
)
759 case "alt_attachments":
760 $this->AltBody
= $this->WrapText($this->AltBody
, $this->WordWrap
);
763 $this->Body
= $this->WrapText($this->Body
, $this->WordWrap
);
769 * Assembles message header.
773 function CreateHeader() {
776 // Set the boundaries
777 $uniq_id = md5(uniqid(time()));
778 $this->boundary
[1] = "b1_" . $uniq_id;
779 $this->boundary
[2] = "b2_" . $uniq_id;
781 $result .= $this->HeaderLine("Date", $this->RFCDate());
782 if($this->Sender
== "")
783 $result .= $this->HeaderLine("Return-Path", trim($this->From
));
785 $result .= $this->HeaderLine("Return-Path", trim($this->Sender
));
787 // To be created automatically by mail()
788 if($this->Mailer
!= "mail")
790 if(count($this->to
) > 0)
791 $result .= $this->AddrAppend("To", $this->to
);
792 else if (count($this->cc
) == 0)
793 $result .= $this->HeaderLine("To", "undisclosed-recipients:;");
794 if(count($this->cc
) > 0)
795 $result .= $this->AddrAppend("Cc", $this->cc
);
799 $from[0][0] = trim($this->From
);
800 $from[0][1] = $this->FromName
;
801 $result .= $this->AddrAppend("From", $from);
803 // sendmail and mail() extract Bcc from the header before sending
804 if((($this->Mailer
== "sendmail") ||
($this->Mailer
== "mail")) && (count($this->bcc
) > 0))
805 $result .= $this->AddrAppend("Bcc", $this->bcc
);
807 if(count($this->ReplyTo
) > 0)
808 $result .= $this->AddrAppend("Reply-to", $this->ReplyTo
);
810 // mail() sets the subject itself
811 if($this->Mailer
!= "mail")
812 $result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject
)));
815 * BEGIN original phpmailer code
817 * Commented out is the original line we are replacing.
818 * Vy-Shane Sin Fat <vy-shane At moodle.com>, 14 Feb 2007.
820 //$result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
822 * END original phpmailer code
826 * BEGIN custom Moodle code
828 * This change is made necessary by MDL-3681. The Moodle forum module
829 * adds Message-ID as a custom header for each forum post mailout.
830 * This is used to help email clients display the messages in a
831 * threaded view. However, phpmailer also adds it's own Message-ID
832 * to every email that it sends. We want this to happen only if we
833 * haven't defined our own custom Message-ID for the email.
835 * Vy-Shane Sin Fat <vy-shane At moodle.com>, 14 Feb 2007.
837 $needmessageid = true;
839 for($i=0; $i<count($this->CustomHeader
); $i++
)
841 if (strtolower(trim($this->CustomHeader
[$i][0])) == 'message-id') {
842 $needmessageid = false;
846 if ($needmessageid) {
847 $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE
);
850 * END custom Moodle code
853 $result .= $this->HeaderLine("X-Priority", $this->Priority
);
854 $result .= $this->HeaderLine("X-Mailer", "PHPMailer [version " . $this->Version
. "]");
856 if($this->ConfirmReadingTo
!= "")
858 $result .= $this->HeaderLine("Disposition-Notification-To",
859 "<" . trim($this->ConfirmReadingTo
) . ">");
862 // Add custom headers
863 for($index = 0; $index < count($this->CustomHeader
); $index++
)
865 $result .= $this->HeaderLine(trim($this->CustomHeader
[$index][0]),
866 $this->EncodeHeader(trim($this->CustomHeader
[$index][1])));
868 $result .= $this->HeaderLine("MIME-Version", "1.0");
870 switch($this->message_type
)
873 $result .= $this->HeaderLine("Content-Transfer-Encoding", $this->Encoding
);
874 $result .= sprintf("Content-Type: %s; charset=\"%s\"",
875 $this->ContentType
, $this->CharSet
);
879 case "alt_attachments":
880 if($this->InlineImageExists())
882 $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s",
883 "multipart/related", $this->LE
, $this->LE
,
884 $this->boundary
[1], $this->LE
);
888 $result .= $this->HeaderLine("Content-Type", "multipart/mixed;");
889 $result .= $this->TextLine("\tboundary=\"" . $this->boundary
[1] . '"');
893 $result .= $this->HeaderLine("Content-Type", "multipart/alternative;");
894 $result .= $this->TextLine("\tboundary=\"" . $this->boundary
[1] . '"');
898 if($this->Mailer
!= "mail")
899 $result .= $this->LE
.$this->LE
;
905 * Assembles the message body. Returns an empty string on failure.
909 function CreateBody() {
912 $this->SetWordWrap();
914 switch($this->message_type
)
917 $result .= $this->GetBoundary($this->boundary
[1], "",
919 $result .= $this->EncodeString($this->AltBody
, $this->Encoding
);
920 $result .= $this->LE
.$this->LE
;
921 $result .= $this->GetBoundary($this->boundary
[1], "",
924 $result .= $this->EncodeString($this->Body
, $this->Encoding
);
925 $result .= $this->LE
.$this->LE
;
927 $result .= $this->EndBoundary($this->boundary
[1]);
930 $result .= $this->EncodeString($this->Body
, $this->Encoding
);
933 $result .= $this->GetBoundary($this->boundary
[1], "", "", "");
934 $result .= $this->EncodeString($this->Body
, $this->Encoding
);
935 $result .= $this->LE
;
937 $result .= $this->AttachAll();
939 case "alt_attachments":
940 $result .= sprintf("--%s%s", $this->boundary
[1], $this->LE
);
941 $result .= sprintf("Content-Type: %s;%s" .
942 "\tboundary=\"%s\"%s",
943 "multipart/alternative", $this->LE
,
944 $this->boundary
[2], $this->LE
.$this->LE
);
947 $result .= $this->GetBoundary($this->boundary
[2], "",
948 "text/plain", "") . $this->LE
;
950 $result .= $this->EncodeString($this->AltBody
, $this->Encoding
);
951 $result .= $this->LE
.$this->LE
;
953 // Create the HTML body
954 $result .= $this->GetBoundary($this->boundary
[2], "",
955 "text/html", "") . $this->LE
;
957 $result .= $this->EncodeString($this->Body
, $this->Encoding
);
958 $result .= $this->LE
.$this->LE
;
960 $result .= $this->EndBoundary($this->boundary
[2]);
962 $result .= $this->AttachAll();
972 * Returns the start of a message boundary.
975 function GetBoundary($boundary, $charSet, $contentType, $encoding) {
977 if($charSet == "") { $charSet = $this->CharSet
; }
978 if($contentType == "") { $contentType = $this->ContentType
; }
979 if($encoding == "") { $encoding = $this->Encoding
; }
981 $result .= $this->TextLine("--" . $boundary);
982 $result .= sprintf("Content-Type: %s; charset = \"%s\"",
983 $contentType, $charSet);
984 $result .= $this->LE
;
985 $result .= $this->HeaderLine("Content-Transfer-Encoding", $encoding);
986 $result .= $this->LE
;
992 * Returns the end of a message boundary.
995 function EndBoundary($boundary) {
996 return $this->LE
. "--" . $boundary . "--" . $this->LE
;
1000 * Sets the message type.
1004 function SetMessageType() {
1005 if(count($this->attachment
) < 1 && strlen($this->AltBody
) < 1)
1006 $this->message_type
= "plain";
1009 if(count($this->attachment
) > 0)
1010 $this->message_type
= "attachments";
1011 if(strlen($this->AltBody
) > 0 && count($this->attachment
) < 1)
1012 $this->message_type
= "alt";
1013 if(strlen($this->AltBody
) > 0 && count($this->attachment
) > 0)
1014 $this->message_type
= "alt_attachments";
1019 * Returns a formatted header line.
1023 function HeaderLine($name, $value) {
1024 return $name . ": " . $value . $this->LE
;
1028 * Returns a formatted mail line.
1032 function TextLine($value) {
1033 return $value . $this->LE
;
1036 /////////////////////////////////////////////////
1037 // ATTACHMENT METHODS
1038 /////////////////////////////////////////////////
1041 * Adds an attachment from a path on the filesystem.
1042 * Returns false if the file could not be found
1044 * @param string $path Path to the attachment.
1045 * @param string $name Overrides the attachment name.
1046 * @param string $encoding File encoding (see $Encoding).
1047 * @param string $type File extension (MIME) type.
1050 function AddAttachment($path, $name = "", $encoding = "base64",
1051 $type = "application/octet-stream") {
1052 if(!@is_file
($path))
1054 $this->SetError($this->Lang("file_access") . $path);
1058 $filename = basename($path);
1062 $cur = count($this->attachment
);
1063 $this->attachment
[$cur][0] = $path;
1064 $this->attachment
[$cur][1] = $filename;
1065 $this->attachment
[$cur][2] = $name;
1066 $this->attachment
[$cur][3] = $encoding;
1067 $this->attachment
[$cur][4] = $type;
1068 $this->attachment
[$cur][5] = false; // isStringAttachment
1069 $this->attachment
[$cur][6] = "attachment";
1070 $this->attachment
[$cur][7] = 0;
1076 * Attaches all fs, string, and binary attachments to the message.
1077 * Returns an empty string on failure.
1081 function AttachAll() {
1082 // Return text of body
1085 // Add all attachments
1086 for($i = 0; $i < count($this->attachment
); $i++
)
1088 // Check for string attachment
1089 $bString = $this->attachment
[$i][5];
1091 $string = $this->attachment
[$i][0];
1093 $path = $this->attachment
[$i][0];
1095 $filename = $this->attachment
[$i][1];
1096 $name = $this->attachment
[$i][2];
1097 $encoding = $this->attachment
[$i][3];
1098 $type = $this->attachment
[$i][4];
1099 $disposition = $this->attachment
[$i][6];
1100 $cid = $this->attachment
[$i][7];
1102 $mime[] = sprintf("--%s%s", $this->boundary
[1], $this->LE
);
1103 $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $name, $this->LE
);
1104 $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE
);
1106 if($disposition == "inline")
1107 $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE
);
1109 $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s",
1110 $disposition, $name, $this->LE
.$this->LE
);
1112 // Encode as string attachment
1115 $mime[] = $this->EncodeString($string, $encoding);
1116 if($this->IsError()) { return ""; }
1117 $mime[] = $this->LE
.$this->LE
;
1121 $mime[] = $this->EncodeFile($path, $encoding);
1122 if($this->IsError()) { return ""; }
1123 $mime[] = $this->LE
.$this->LE
;
1127 $mime[] = sprintf("--%s--%s", $this->boundary
[1], $this->LE
);
1129 return join("", $mime);
1133 * Encodes attachment in requested format. Returns an
1134 * empty string on failure.
1138 function EncodeFile ($path, $encoding = "base64") {
1139 if(!@$fd = fopen($path, "rb"))
1141 $this->SetError($this->Lang("file_open") . $path);
1144 $magic_quotes = get_magic_quotes_runtime();
1145 set_magic_quotes_runtime(0);
1146 $file_buffer = fread($fd, filesize($path));
1147 $file_buffer = $this->EncodeString($file_buffer, $encoding);
1149 set_magic_quotes_runtime($magic_quotes);
1151 return $file_buffer;
1155 * Encodes string to requested format. Returns an
1156 * empty string on failure.
1160 function EncodeString ($str, $encoding = "base64") {
1162 switch(strtolower($encoding)) {
1164 // chunk_split is found in PHP >= 3.0.6
1165 $encoded = chunk_split(base64_encode($str), 76, $this->LE
);
1169 $encoded = $this->FixEOL($str);
1170 if (substr($encoded, -(strlen($this->LE
))) != $this->LE
)
1171 $encoded .= $this->LE
;
1176 case "quoted-printable":
1177 $encoded = $this->EncodeQP($str);
1180 $this->SetError($this->Lang("encoding") . $encoding);
1187 * Encode a header string to best of Q, B, quoted or none.
1191 function EncodeHeader ($str, $position = 'text') {
1193 /// Start Moodle Hack - do our own multibyte-safe header encoding
1194 $textlib = textlib_get_instance();
1195 $result = $textlib->encode_mimeheader($str, $this->CharSet
);
1196 if ($result !== false) {
1199 // try the old way that does not handle binary-safe line splitting in mime header
1203 switch (strtolower($position)) {
1205 if (!preg_match('/[\200-\377]/', $str)) {
1206 // Can't use addslashes as we don't know what value has magic_quotes_sybase.
1207 $encoded = addcslashes($str, "\0..\37\177\\\"");
1209 if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str))
1212 return ("\"$encoded\"");
1214 $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
1217 $x = preg_match_all('/[()"]/', $str, $matches);
1221 $x +
= preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
1228 $maxlen = 75 - 7 - strlen($this->CharSet
);
1229 // Try to select the encoding which should produce the shortest output
1230 if (strlen($str)/3 < $x) {
1232 $encoded = base64_encode($str);
1233 $maxlen -= $maxlen %
4;
1234 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
1237 $encoded = $this->EncodeQ($str, $position);
1238 $encoded = $this->WrapText($encoded, $maxlen, true);
1239 $encoded = str_replace("=".$this->LE
, "\n", trim($encoded));
1242 $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet
."?$encoding?\\1?=", $encoded);
1243 $encoded = trim(str_replace("\n", $this->LE
, $encoded));
1249 * Encode string to quoted-printable.
1253 function EncodeQP ($str) {
1254 $encoded = $this->FixEOL($str);
1255 if (substr($encoded, -(strlen($this->LE
))) != $this->LE
)
1256 $encoded .= $this->LE
;
1258 // Replace every high ascii, control and = characters
1259 $encoded = preg_replace('/([\000-\010\013\014\016-\037\075\177-\377])/e',
1260 "'='.sprintf('%02X', ord('\\1'))", $encoded);
1261 // Replace every spaces and tabs when it's the last character on a line
1262 $encoded = preg_replace("/([\011\040])".$this->LE
."/e",
1263 "'='.sprintf('%02X', ord('\\1')).'".$this->LE
."'", $encoded);
1265 // Maximum line length of 76 characters before CRLF (74 + space + '=')
1266 $encoded = $this->WrapText($encoded, 74, true);
1272 * Encode string to q encoding.
1276 function EncodeQ ($str, $position = "text") {
1277 // There should not be any EOL in the string
1278 $encoded = preg_replace("[\r\n]", "", $str);
1280 switch (strtolower($position)) {
1282 $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1285 $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1288 // Replace every high ascii, control =, ? and _ characters
1289 $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
1290 "'='.sprintf('%02X', ord('\\1'))", $encoded);
1294 // Replace every spaces to _ (more readable than =20)
1295 $encoded = str_replace(" ", "_", $encoded);
1301 * Adds a string or binary attachment (non-filesystem) to the list.
1302 * This method can be used to attach ascii or binary data,
1303 * such as a BLOB record from a database.
1304 * @param string $string String attachment data.
1305 * @param string $filename Name of the attachment.
1306 * @param string $encoding File encoding (see $Encoding).
1307 * @param string $type File extension (MIME) type.
1310 function AddStringAttachment($string, $filename, $encoding = "base64",
1311 $type = "application/octet-stream") {
1312 // Append to $attachment array
1313 $cur = count($this->attachment
);
1314 $this->attachment
[$cur][0] = $string;
1315 $this->attachment
[$cur][1] = $filename;
1316 $this->attachment
[$cur][2] = $filename;
1317 $this->attachment
[$cur][3] = $encoding;
1318 $this->attachment
[$cur][4] = $type;
1319 $this->attachment
[$cur][5] = true; // isString
1320 $this->attachment
[$cur][6] = "attachment";
1321 $this->attachment
[$cur][7] = 0;
1325 * Adds an embedded attachment. This can include images, sounds, and
1326 * just about any other document. Make sure to set the $type to an
1327 * image type. For JPEG images use "image/jpeg" and for GIF images
1329 * @param string $path Path to the attachment.
1330 * @param string $cid Content ID of the attachment. Use this to identify
1331 * the Id for accessing the image in an HTML form.
1332 * @param string $name Overrides the attachment name.
1333 * @param string $encoding File encoding (see $Encoding).
1334 * @param string $type File extension (MIME) type.
1337 function AddEmbeddedImage($path, $cid, $name = "", $encoding = "base64",
1338 $type = "application/octet-stream") {
1340 if(!@is_file
($path))
1342 $this->SetError($this->Lang("file_access") . $path);
1346 $filename = basename($path);
1350 // Append to $attachment array
1351 $cur = count($this->attachment
);
1352 $this->attachment
[$cur][0] = $path;
1353 $this->attachment
[$cur][1] = $filename;
1354 $this->attachment
[$cur][2] = $name;
1355 $this->attachment
[$cur][3] = $encoding;
1356 $this->attachment
[$cur][4] = $type;
1357 $this->attachment
[$cur][5] = false; // isStringAttachment
1358 $this->attachment
[$cur][6] = "inline";
1359 $this->attachment
[$cur][7] = $cid;
1365 * Returns true if an inline attachment is present.
1369 function InlineImageExists() {
1371 for($i = 0; $i < count($this->attachment
); $i++
)
1373 if($this->attachment
[$i][6] == "inline")
1383 /////////////////////////////////////////////////
1384 // MESSAGE RESET METHODS
1385 /////////////////////////////////////////////////
1388 * Clears all recipients assigned in the TO array. Returns void.
1391 function ClearAddresses() {
1392 $this->to
= array();
1396 * Clears all recipients assigned in the CC array. Returns void.
1399 function ClearCCs() {
1400 $this->cc
= array();
1404 * Clears all recipients assigned in the BCC array. Returns void.
1407 function ClearBCCs() {
1408 $this->bcc
= array();
1412 * Clears all recipients assigned in the ReplyTo array. Returns void.
1415 function ClearReplyTos() {
1416 $this->ReplyTo
= array();
1420 * Clears all recipients assigned in the TO, CC and BCC
1421 * array. Returns void.
1424 function ClearAllRecipients() {
1425 $this->to
= array();
1426 $this->cc
= array();
1427 $this->bcc
= array();
1431 * Clears all previously set filesystem, string, and binary
1432 * attachments. Returns void.
1435 function ClearAttachments() {
1436 $this->attachment
= array();
1440 * Clears all custom headers. Returns void.
1443 function ClearCustomHeaders() {
1444 $this->CustomHeader
= array();
1448 /////////////////////////////////////////////////
1449 // MISCELLANEOUS METHODS
1450 /////////////////////////////////////////////////
1453 * Adds the error message to the error container.
1458 function SetError($msg) {
1459 $this->error_count++
;
1460 $this->ErrorInfo
= $msg;
1464 * Returns the proper RFC 822 formatted date.
1468 function RFCDate() {
1470 $tzs = ($tz < 0) ?
"-" : "+";
1472 $tz = ($tz/3600)*100 +
($tz%3600
)/60;
1473 $result = sprintf("%s %s%04d", date("D, j M Y H:i:s"), $tzs, $tz);
1479 * Returns the appropriate server variable. Should work with both
1480 * PHP 4.1.0+ as well as older versions. Returns an empty string
1481 * if nothing is found.
1485 function ServerVar($varName) {
1486 global $HTTP_SERVER_VARS;
1487 global $HTTP_ENV_VARS;
1489 if(!isset($_SERVER))
1491 $_SERVER = $HTTP_SERVER_VARS;
1492 if(!isset($_SERVER["REMOTE_ADDR"]))
1493 $_SERVER = $HTTP_ENV_VARS; // must be Apache
1496 if(isset($_SERVER[$varName]))
1497 return $_SERVER[$varName];
1503 * Returns the server hostname or 'localhost.localdomain' if unknown.
1507 function ServerHostname() {
1508 if ($this->Hostname
!= "")
1509 $result = $this->Hostname
;
1510 elseif ($this->ServerVar('SERVER_NAME') != "")
1511 $result = $this->ServerVar('SERVER_NAME');
1513 $result = "localhost.localdomain";
1519 * Returns a message in the appropriate language.
1523 function Lang($key) {
1524 if(count($this->language
) < 1)
1525 $this->SetLanguage("en"); // set the default language
1527 if(isset($this->language
[$key]))
1528 return $this->language
[$key];
1530 return "Language string failed to load: " . $key;
1534 * Returns true if an error occurred.
1537 function IsError() {
1538 return ($this->error_count
> 0);
1542 * Changes every end of line from CR or LF to CRLF.
1546 function FixEOL($str) {
1547 $str = str_replace("\r\n", "\n", $str);
1548 $str = str_replace("\r", "\n", $str);
1549 $str = str_replace("\n", $this->LE
, $str);
1554 * Adds a custom header.
1557 function AddCustomHeader($custom_header) {
1558 $this->CustomHeader
[] = explode(":", $custom_header, 2);