Must be updated here as well :(
[mailer.git] / inc / email-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 07/01/2012 *
4  * ===================                          Last change: 07/01/2012 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : email-functions.php                              *
8  * -------------------------------------------------------------------- *
9  * Short description : Email-delivery-related functions                 *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Mailversand bezogene Funktionen                  *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2013 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Send mail out to an email address
44 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
45         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'toEmail=' . $toEmail . ',subject=' . $subject . ',isHtml=' . $isHtml);
46         // Empty parameters should be avoided, so we need to find them
47         if (empty($isHtml)) {
48                 // isHtml is empty
49                 reportBug(__FUNCTION__, __LINE__, 'isHtml is empty.');
50         } // END - if
51
52         // Set from header
53         if ((!isInString('@', $toEmail)) && (isValidId($toEmail))) {
54                 // Does the user exist?
55                 if ((isExtensionActive('user')) && (fetchUserData($toEmail))) {
56                         // Get the email
57                         $toEmail = getUserData('email');
58                 } else {
59                         // Set webmaster
60                         $toEmail = getWebmaster();
61                 }
62         } elseif (($toEmail == '0') || (is_null($toEmail))) {
63                 // Is the webmaster!
64                 $toEmail = getWebmaster();
65         }
66         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'TO=' . $toEmail);
67
68         // Check for PHPMailer or debug-mode
69         if ((!isPhpMailerConfigured()) || (isDebugModeEnabled())) {
70                 // Prefix is '' for text mails
71                 $prefix = '';
72
73                 // Is HTML?
74                 if ($isHtml == 'Y') {
75                         // Set prefix
76                         $prefix = 'html_';
77                 } // END - if
78
79                 // Load email header template
80                 $mailHeader = loadEmailTemplate($prefix . 'header', $mailHeader);
81         } // END - if
82
83         // Debug mode enabled?
84         if ((isDebugModeEnabled()) && (!isAjaxOutputMode())) {
85                 // Init content array
86                 $content = array(
87                         'headers' => htmlentities(trim($mailHeader)),
88                         'to'      => htmlentities($toEmail),
89                         'subject' => htmlentities($subject),
90                         'message' => htmlentities($message),
91                         'length'  => strlen($message)
92                 );
93
94                 // In debug mode display the mail instead of sending it away so it can be debugged
95                 loadTemplate('display_email', FALSE, $content);
96
97                 // This is always fine
98                 return TRUE;
99         } elseif (!empty($toEmail)) {
100                 // Send Mail away
101                 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
102         } elseif ($isHtml != 'Y') {
103                 // Problem detected while sending a mail, forward it to admin
104                 return sendRawEmail(getWebmaster(), '[PROBLEM:]' . $subject, $message, $mailHeader);
105         }
106
107         // Why did we end up here? This should not happen
108         reportBug(__FUNCTION__, __LINE__, 'Ending up: template=' . $template);
109 }
110
111 /**
112  * Check to use whether plain mail() command or PHPMailer class
113  * @TODO Rewrite this to an extension 'smtp'
114  * @private
115  */
116 function isPhpMailerConfigured () {
117         return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
118 }
119
120 // Send out a raw email with PHPMailer class or plain mail() command
121 function sendRawEmail ($toEmail, $subject, $message, $headers) {
122         // Just compile all to put out all configs, etc.
123         $eval  = '$toEmail = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($toEmail), FALSE)) . '"); ';
124         $eval .= '$subject = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($subject), FALSE)) . '"); ';
125         $eval .= '$headers = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($headers), FALSE)) . '"); ';
126
127         // Do not decode entities in the message because we also send HTML mails through this function
128         $eval .= '$message = "' . escapeQuotes(doFinalCompilation(compileRawCode($message), FALSE)) . '";';
129
130         // Run the final eval() command
131         eval($eval);
132
133         // Shall we use PHPMailer class or plain mail() command?
134         if (isPhpMailerConfigured()) {
135                 // Use PHPMailer class with SMTP enabled
136                 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
137                 loadIncludeOnce('inc/phpmailer/class.smtp.php');
138
139                 // get new instance
140                 $mail = new PHPMailer();
141
142                 // Set charset to UTF-8
143                 $mail->CharSet = 'UTF-8';
144
145                 // Path for PHPMailer
146                 $mail->PluginDir  = sprintf("%sinc/phpmailer/", getPath());
147
148                 $mail->IsSMTP();
149                 $mail->SMTPAuth   = TRUE;
150                 $mail->Host       = getConfig('SMTP_HOSTNAME');
151                 $mail->Port       = 25;
152                 $mail->Username   = getConfig('SMTP_USER');
153                 $mail->Password   = getConfig('SMTP_PASSWORD');
154                 if (empty($headers)) {
155                         $mail->From = getWebmaster();
156                 } else {
157                         $mail->From = $headers;
158                 }
159                 $mail->FromName   = getMainTitle();
160                 $mail->Subject    = $subject;
161                 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
162                         $mail->Body       = $message;
163                         $mail->AltBody    = decodeEntities($message);
164                         $mail->WordWrap   = 70;
165                         $mail->IsHTML(TRUE);
166                 } else {
167                         $mail->Body       = decodeEntities(strip_tags($message));
168                 }
169
170                 $mail->AddAddress($toEmail, '');
171                 $mail->AddReplyTo(getWebmaster(), getMainTitle());
172                 $mail->AddCustomHeader('Errors-To: ' . getWebmaster());
173                 $mail->AddCustomHeader('X-Loop: ' . getWebmaster());
174                 $mail->AddCustomHeader('Bounces-To: ' . getWebmaster());
175                 $mail->Send();
176
177                 // Has an error occured?
178                 if (!empty($mail->ErrorInfo)) {
179                         // Log message
180                         logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
181
182                         // Raise an error
183                         return FALSE;
184                 } else {
185                         // All fine!
186                         return TRUE;
187                 }
188         } else {
189                 // Use plain mail() command
190                 return mail($toEmail, $subject, decodeEntities($message), $headers);
191         }
192 }
193
194 // Send notification to admin
195 function sendAdminNotification ($subject, $templateName, $content = array(), $userid = NULL) {
196         if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
197                 // Send new way
198                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=Y,subject=' . $subject . ',templateName=' . $templateName . ' - OKAY!');
199                 sendAdminsEmails($subject, $templateName, $content, $userid);
200         } else {
201                 // Send out-dated way
202                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=N,subject=' . $subject . ',templateName=' . $templateName . ' - OUT-DATED!');
203                 $message = loadEmailTemplate($templateName, $content, $userid);
204                 sendAdminEmails($subject, $message, ($templateName == 'admin_report_bug'));
205         }
206 }
207
208 // Send mails for del/edit/lock build modes
209 // @TODO $rawUserId is currently unused
210 function sendGenericBuildMails ($mode, $tableName, $content, $id, $subjectPart = '', $userIdColumn = array('userid'), $rawUserId = array('userid')) {
211         // $tableName must be an array
212         if ((!is_array($tableName)) || (count($tableName) != 1)) {
213                 // $tableName is no array
214                 reportBug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
215         } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
216                 // $tableName is no array
217                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
218         } // END - if
219
220         // Default subject is the subject part
221         $subject = $subjectPart;
222
223         // Is the subject part not set?
224         if (empty($subjectPart)) {
225                 // Then use it from the mode
226                 $subject = strtoupper($mode);
227         } // END - if
228
229         // Is the raw userid set?
230         if (isValidId(postRequestElement($userIdColumn[0], $id))) {
231                 // Set it in content
232                 $content[$userIdColumn[0]] = bigintval(postRequestElement($userIdColumn[0], $id));
233
234                 // Load email template
235                 if (!empty($subjectPart)) {
236                         $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content);
237                 } else {
238                         $mail = loadEmailTemplate('member_' . $mode . '_' . $tableName[0], $content);
239                 }
240
241                 // Send email out
242                 sendEmail(postRequestElement($userIdColumn[0], $id), strtoupper('{--MEMBER_' . $subject . '_' . $tableName[0] . '_SUBJECT--}'), $mail);
243         } // END - if
244
245         // Generate subject
246         $subject = strtoupper('{--ADMIN_' . $subject . '_' . $tableName[0] . '_SUBJECT--}');
247
248         // Send admin notification out
249         if (!empty($subjectPart)) {
250                 sendAdminNotification($subject, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
251         } else {
252                 sendAdminNotification($subject, 'admin_' . $mode . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
253         }
254 }
255
256 // ----------------------------------------------------------------------------
257 //                           Template helper functions
258 // ----------------------------------------------------------------------------
259
260 // Helper function to add extra headers to text mails
261 function doTemplateAddExtraTextMailHeaders ($templateName, $clear, $extraHeaders = '') {
262         // Run the header through the filter
263         $extraHeaders = runFilterChain('add_extra_text_mail_headers', $extraHeaders);
264
265         // And return it
266         return $extraHeaders;
267 }
268
269 // Helper function to add extra headers to HTML mails
270 function doTemplateAddExtraHtmlMailHeaders ($templateName, $clear, $extraHeaders = '') {
271         // Run the header through the filter
272         $extraHeaders = runFilterChain('add_extra_html_mail_headers', $extraHeaders);
273
274         // And return it
275         return $extraHeaders;
276 }
277
278 // [EOF]
279 ?>