bb4f0e55eb863de23c59bcfdc2a14ac1454b2797
[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:: 2773                                                   $ *
14  * $Date:: 2012-06-26 01:02:44 +0200 (Tue, 26 Jun 2012)               $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author:: quix0r                                                   $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 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)) && ($toEmail > 0)) {
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') {
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()) {
85                 // In debug mode we want to display the mail instead of sending it away so we can debug this part
86                 outputHtml('<pre>
87 <strong>Headers</strong> : ' . htmlentities(trim($mailHeader)) . '
88 <strong>To</strong>      : ' . htmlentities($toEmail) . '
89 <strong>Subject</strong> : ' . htmlentities($subject) . '
90 <strong>Message(' . strlen($message) . ')</strong> : ' . htmlentities($message) . '
91 </pre>');
92
93                 // This is always fine
94                 return true;
95         } elseif (!empty($toEmail)) {
96                 // Send Mail away
97                 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
98         } elseif ($isHtml != 'Y') {
99                 // Problem detected while sending a mail, forward it to admin
100                 return sendRawEmail(getWebmaster(), '[PROBLEM:]' . $subject, $message, $mailHeader);
101         }
102
103         // Why did we end up here? This should not happen
104         reportBug(__FUNCTION__, __LINE__, 'Ending up: template=' . $template);
105 }
106
107 /**
108  * Check to use whether plain mail() command or PHPMailer class
109  * @TODO Rewrite this to an extension 'smtp'
110  * @private
111  */
112 function isPhpMailerConfigured () {
113         return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
114 }
115
116 // Send out a raw email with PHPMailer class or plain mail() command
117 function sendRawEmail ($toEmail, $subject, $message, $headers) {
118         // Just compile all to put out all configs, etc.
119         $eval  = '$toEmail = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($toEmail), false)) . '"); ';
120         $eval .= '$subject = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($subject), false)) . '"); ';
121         $eval .= '$headers = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($headers), false)) . '"); ';
122
123         // Do not decode entities in the message because we also send HTML mails through this function
124         $eval .= '$message = "' . escapeQuotes(doFinalCompilation(compileRawCode($message), false)) . '";';
125
126         // Run the final eval() command
127         eval($eval);
128
129         // Shall we use PHPMailer class or plain mail() command?
130         if (isPhpMailerConfigured()) {
131                 // Use PHPMailer class with SMTP enabled
132                 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
133                 loadIncludeOnce('inc/phpmailer/class.smtp.php');
134
135                 // get new instance
136                 $mail = new PHPMailer();
137
138                 // Set charset to UTF-8
139                 $mail->CharSet = 'UTF-8';
140
141                 // Path for PHPMailer
142                 $mail->PluginDir  = sprintf("%sinc/phpmailer/", getPath());
143
144                 $mail->IsSMTP();
145                 $mail->SMTPAuth   = true;
146                 $mail->Host       = getConfig('SMTP_HOSTNAME');
147                 $mail->Port       = 25;
148                 $mail->Username   = getConfig('SMTP_USER');
149                 $mail->Password   = getConfig('SMTP_PASSWORD');
150                 if (empty($headers)) {
151                         $mail->From = getWebmaster();
152                 } else {
153                         $mail->From = $headers;
154                 }
155                 $mail->FromName   = getMainTitle();
156                 $mail->Subject    = $subject;
157                 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
158                         $mail->Body       = $message;
159                         $mail->AltBody    = decodeEntities($message);
160                         $mail->WordWrap   = 70;
161                         $mail->IsHTML(true);
162                 } else {
163                         $mail->Body       = decodeEntities(strip_tags($message));
164                 }
165
166                 $mail->AddAddress($toEmail, '');
167                 $mail->AddReplyTo(getWebmaster(), getMainTitle());
168                 $mail->AddCustomHeader('Errors-To: ' . getWebmaster());
169                 $mail->AddCustomHeader('X-Loop: ' . getWebmaster());
170                 $mail->AddCustomHeader('Bounces-To: ' . getWebmaster());
171                 $mail->Send();
172
173                 // Has an error occured?
174                 if (!empty($mail->ErrorInfo)) {
175                         // Log message
176                         logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
177
178                         // Raise an error
179                         return false;
180                 } else {
181                         // All fine!
182                         return true;
183                 }
184         } else {
185                 // Use plain mail() command
186                 return mail($toEmail, $subject, decodeEntities($message), $headers);
187         }
188 }
189
190 // Send notification to admin
191 function sendAdminNotification ($subject, $templateName, $content = array(), $userid = NULL) {
192         if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
193                 // Send new way
194                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=Y,subject=' . $subject . ',templateName=' . $templateName . ' - OKAY!');
195                 sendAdminsEmails($subject, $templateName, $content, $userid);
196         } else {
197                 // Send out-dated way
198                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=N,subject=' . $subject . ',templateName=' . $templateName . ' - OUT-DATED!');
199                 $message = loadEmailTemplate($templateName, $content, $userid);
200                 sendAdminEmails($subject, $message, ($templateName == 'admin_report_bug'));
201         }
202 }
203
204 // ----------------------------------------------------------------------------
205 //                           Template helper functions
206 // ----------------------------------------------------------------------------
207
208 // Helper function to add extra headers to text mails
209 function doTemplateAddExtraTextMailHeaders ($templateName, $clear, $extraHeaders = '') {
210         // Run the header through the filter
211         $extraHeaders = runFilterChain('add_extra_text_mail_headers', $extraHeaders);
212
213         // And return it
214         return $extraHeaders;
215 }
216
217 // Helper function to add extra headers to HTML mails
218 function doTemplateAddExtraHtmlMailHeaders ($templateName, $clear, $extraHeaders = '') {
219         // Run the header through the filter
220         $extraHeaders = runFilterChain('add_extra_html_mail_headers', $extraHeaders);
221
222         // And return it
223         return $extraHeaders;
224 }
225
226 // Send mails for del/edit/lock build modes
227 // @TODO $rawUserId is currently unused
228 function sendGenericBuildMails ($mode, $tableName, $content, $id, $subjectPart = '', $userIdColumn = array('userid'), $rawUserId = array('userid')) {
229         // $tableName must be an array
230         if ((!is_array($tableName)) || (count($tableName) != 1)) {
231                 // $tableName is no array
232                 reportBug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
233         } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
234                 // $tableName is no array
235                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
236         } // END - if
237
238         // Default subject is the subject part
239         $subject = $subjectPart;
240
241         // Is the subject part not set?
242         if (empty($subjectPart)) {
243                 // Then use it from the mode
244                 $subject = strtoupper($mode);
245         } // END - if
246
247         // Is the raw userid set?
248         if (postRequestElement($userIdColumn[0], $id) > 0) {
249                 // Load email template
250                 if (!empty($subjectPart)) {
251                         $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content);
252                 } else {
253                         $mail = loadEmailTemplate('member_' . $mode . '_' . $tableName[0], $content);
254                 }
255
256                 // Send email out
257                 sendEmail(postRequestElement($userIdColumn[0], $id), strtoupper('{--MEMBER_' . $subject . '_' . $tableName[0] . '_SUBJECT--}'), $mail);
258         } // END - if
259
260         // Generate subject
261         $subject = strtoupper('{--ADMIN_' . $subject . '_' . $tableName[0] . '_SUBJECT--}');
262
263         // Send admin notification out
264         if (!empty($subjectPart)) {
265                 sendAdminNotification($subject, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
266         } else {
267                 sendAdminNotification($subject, 'admin_' . $mode . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
268         }
269 }
270
271 // [EOF]
272 ?>