*gasp*
[lhc/web/wiklou.git] / includes / UserMailer.php
1 <?php
2 /**
3 * UserMailer.php
4 * Copyright (C) 2004 Thomas Gries <mail@tgries.de>
5 * http://www.mediawiki.org/
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @author <brion@pobox.com>
23 * @author <mail@tgries.de>
24 *
25 * @package MediaWiki
26 */
27
28 /**
29 * Provide mail capabilities
30 * @param string $string ????
31 *
32 * The function takes formats like "name <emailaddr>" into account, for which
33 * the partial string "name" will be quoted-printable converted but not
34 * "<emailaddr>".
35 *
36 * The php mail() function does not accept the email address partial string to
37 * be quotedprintable, it does not accept inputs as
38 * quotedprintable("name <emailaddr>") .
39 *
40 * case 1:
41 * input: "name <emailaddr> rest"
42 * output: "quoted-printable(name) <emailaddr>"
43 *
44 * case 2: (should not happen)
45 * input: "<emailaddr> rest"
46 * output: "<emailaddr>"
47 *
48 * case 3: (should not happen)
49 * input: "name"
50 * output: "quoted-printable(name)"
51 */
52 function wfQuotedPrintable_name_and_emailaddr( $string ) {
53
54 /* do not quote printable for email address string <emailaddr>, but only for the (leading) string, usually the name */
55 preg_match( '/^([^<]*)?(<([A-z0-9_.-]+([A-z0-9_.-]+)*\@[A-z0-9_-]+([A-z0-9_.-]+)*([A-z.]{2,})+)>)?$/', $string, $part );
56 if ( !isset($part[1]) ) return $part[2];
57 if ( !isset($part[2]) ) return wfQuotedprintable($part[1]);
58 return wfQuotedprintable($part[1]) . $part[2] ;
59 }
60
61 /**
62 * This function will perform a direct (authenticated) login to
63 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
64 * array of parameters. It requires PEAR:Mail to do that.
65 * Otherwise it just uses the standard PHP 'mail' function.
66 *
67 * @param string $to recipient's email
68 * @param string $from sender's email
69 * @param string $subject email's subject
70 * @param string $body email's text
71 * @param string $replyto optional reply-to email (default : false)
72 */
73 function userMailer( $to, $from, $subject, $body, $replyto=false ) {
74 global $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString, $wgEmergencyContact;
75
76 $qto = wfQuotedPrintable_name_and_emailaddr( $to );
77
78 if (is_array( $wgSMTP )) {
79 require_once( 'Mail.php' );
80
81 $timestamp = time();
82
83 $headers['From'] = $from;
84 /* removing to: field as it should be set by the send() function below
85 UNTESTED - Hashar */
86 // $headers['To'] = $qto;
87 /* Reply-To:
88 UNTESTED - Tom Gries */
89 $headers['Reply-To'] = $replyto;
90 $headers['Subject'] = $subject;
91 $headers['MIME-Version'] = '1.0';
92 $headers['Content-type'] = 'text/plain; charset='.$wgOutputEncoding;
93 $headers['Content-transfer-encoding'] = '8bit';
94 $headers['Message-ID'] = "<{$timestamp}" . $wgUser->getName() . '@' . $wgSMTP['IDHost'] . '>';
95 $headers['X-Mailer'] = 'MediaWiki mailer';
96
97 // Create the mail object using the Mail::factory method
98 $mail_object =& Mail::factory('smtp', $wgSMTP);
99
100 $mailResult =& $mail_object->send($to, $headers, $body);
101
102 # Based on the result return an error string,
103 if ($mailResult === true)
104 return '';
105 else if (is_object($mailResult))
106 return $mailResult->getMessage();
107 else
108 return 'Mail object return unknown error.';
109 } else {
110 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
111 # (fifth parameter of the PHP mail function, see some lines below)
112 $headers =
113 "MIME-Version: 1.0\n" .
114 "Content-type: text/plain; charset={$wgOutputEncoding}\n" .
115 "Content-Transfer-Encoding: 8bit\n" .
116 "X-Mailer: MediaWiki mailer\n".
117 'From:' . wfQuotedPrintable_name_and_emailaddr($from) . "\n";
118 if ($replyto) {
119 $headers .= 'Reply-To: '.wfQuotedPrintable_name_and_emailaddr($replyto)."\n";
120 }
121
122 $wgErrorString = '';
123 set_error_handler( 'mailErrorHandler' );
124 # added -f parameter, see PHP manual for the fifth parameter when using the mail function
125 mail( wfQuotedPrintable_name_and_emailaddr($to), $subject, $body, $headers, "-f{$wgEmergencyContact}\n");
126 restore_error_handler();
127
128 return $wgErrorString;
129 }
130 }
131
132 /**
133 * @todo document
134 */
135 function mailErrorHandler( $code, $string ) {
136 global $wgErrorString;
137 $wgErrorString = preg_replace( "/^mail\(\): /", "", $string );
138 }
139
140
141 /**
142 * This module processes the email notifications when the current page is
143 * changed. It looks up the table watchlist to find out which users are watching
144 * that page.
145 *
146 * The current implementation sends independent emails to each watching user for
147 * the following reason:
148 *
149 * - Each watching user will be notified about the page edit time expressed in
150 * his/her local time (UTC is shown additionally). To achieve this, we need to
151 * find the individual timeoffset of each watching user from the preferences..
152 *
153 * Suggested improvement to slack down the number of sent emails: We could think
154 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
155 * same timeoffset in their preferences.
156 *
157 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
158 *
159 * @package MediaWiki
160 *
161 */
162 class EmailNotification {
163 /**#@+
164 * @access private
165 */
166 var $to, $subject, $body, $replyto, $from;
167 /**#@-*/
168
169 /**
170 * @todo document
171 * @param $currentUser
172 * @param $currentPage
173 * @param $currentNs
174 * @param $timestamp
175 * @param $currentSummary
176 * @param $currentMinorEdit
177 * @param $oldid (default: false)
178 */
179 function NotifyOnPageChange($currentUser, $currentPage, $currentNs, $timestamp, $currentSummary, $currentMinorEdit, $oldid=false) {
180
181 # we use $wgEmergencyContact as sender's address
182 global $wgUser, $wgLang, $wgEmergencyContact;
183 global $wgEmailNotificationForWatchlistPages, $wgEmailNotificationForMinorEdits;
184 global $wgEmailNotificationSystembeep, $wgEmailNotificationForUserTalkPages;
185 global $wgEmailNotificationRevealPageEditorAddress;
186 global $wgEmailNotificationMailsSentFromPageEditor;
187 global $wgEmailAuthentication;
188 global $beeped;
189
190 # The following code is only run, if several conditions are met:
191 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
192 # 2. minor edits (changes) are only regarded if the global flag indicates so
193
194 $isUserTalkPage = ($currentNs == NS_USER_TALK);
195 $enotifusertalkpage = ($isUserTalkPage && $wgEmailNotificationForUserTalkPages);
196 $enotifwatchlistpage = (!$isUserTalkPage && $wgEmailNotificationForWatchlistPages);
197
198 if ( ($enotifusertalkpage || $enotifwatchlistpage)
199 && (!$currentMinorEdit || $wgEmailNotificationForMinorEdits) ) {
200
201 $dbr =& wfGetDB( DB_MASTER );
202 extract( $dbr->tableNames( 'watchlist' ) );
203 $sql = "SELECT wl_user FROM $watchlist
204 WHERE wl_title='" . $dbr->strencode($currentPage)."' AND wl_namespace = " . $currentNs .
205 " AND wl_user <>" . $currentUser . " AND wl_notificationtimestamp <= 1";
206 $res = $dbr->query( $sql,'UserMailer::NotifyOnChange');
207
208 # if anyone is watching ... set up the email message text which is
209 # common for all receipients ...
210 if ( $dbr->numRows( $res ) > 0 ) {
211
212 # This is a switch for one beep on the server when sending notification mails
213 $beeped = false;
214
215 $article->mTimestamp = $timestamp;
216 $article->mSummary = $currentSummary;
217 $article->mMinorEdit = $currentMinorEdit;
218 $article->mNamespace = $currentNs;
219 $article->mTitle = $currentPage;
220 $article->mOldid = $oldid;
221
222 $mail = $this->composeCommonMailtext( $wgUser, $article );
223 $watchingUser = new User();
224
225 # ... now do for all watching users ... if the options fit
226 for ($i = 1; $i <= $dbr->numRows( $res ); $i++) {
227
228 $wuser = $dbr->fetchObject( $res );
229 $watchingUser->setID($wuser->wl_user);
230 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
231 ( $enotifusertalkpage && $watchingUser->getOption('enotifusertalkpages') )
232 && (!$currentMinorEdit || ($wgEmailNotificationForMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
233 && ($watchingUser->getEmail() != '')
234 && (!$wgEmailAuthentication || ($watchingUser->getEmailAuthenticationtimestamp() != 0 ) ) ) {
235 # ... adjust remaining text and page edit time placeholders
236 # which needs to be personalized for each user
237 $sent = $this->composeAndSendPersonalisedMail( $watchingUser, $mail, $article );
238 /* the beep here beeps once when a watched-listed page is changed */
239 if ($sent && !$beeped && ($wgEmailNotificationSystembeep != '') ) {
240 $last_line = system($wgEmailNotificationSystembeep);
241 $beeped=true;
242 }
243 } # if the watching user has an email address in the preferences
244 # mark the changed watch-listed page with a timestamp, so that the page is listed with an "updated since your last visit" icon in the watch list, ...
245 # ... no matter, if the watching user has or has not indicated an email address in his/her preferences.
246 # We memorise the event of sending out a notification and use this as a flag to suppress further mails for changes on the same page for that watching user
247 $dbw =& wfGetDB( DB_MASTER );
248 $succes = $dbw->update( 'watchlist',
249 array( /* SET */
250 'wl_notificationtimestamp' => $article->mTimestamp
251 ), array( /* WHERE */
252 'wl_title' => $currentPage,
253 'wl_namespace' => $currentNs,
254 'wl_user' => $wuser->wl_user
255 ), 'UserMailer::NotifyOnChange'
256 );
257 } # for every watching user
258 } # if anyone is watching
259 } # if $wgEmailNotificationForWatchlistPages = true
260 } # function NotifyOnChange
261
262 /**
263 * @param User $pageeditorUser
264 * @param Article $article
265 * @access private
266 */
267 function composeCommonMailtext( $pageeditorUser, $article ) {
268 global $wgLang, $wgEmergencyContact;
269 global $wgEmailNotificationRevealPageEditorAddress;
270 global $wgEmailNotificationMailsSentFromPageEditor;
271 global $wgNoReplyAddress;
272
273 $summary = ($article->mSummary == '') ? ' - ' : $article->mSummary;
274 $medit = ($article->mMinorEdit) ? wfMsg( 'minoredit' ) : '';
275
276 # You as the WikiAdmin and Sysops can make use of plenty of
277 # named variables when composing your notification emails while
278 # simply editing the Meta pages
279
280 $to = wfMsg( 'email_notification_to' );
281 $subject = wfMsg( 'email_notification_subject' );
282 $body = wfMsg( 'email_notification_body' );
283 $from = ''; /* fail safe */
284 $replyto = ''; /* fail safe */
285 $keys = array();
286
287 # regarding the use of oldid as an indicator for the last visited version, see also
288 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
289 # However, in the case of a new page which is already watched, we have no previous version to compare
290 if( $article->mOldid ) {
291 $keys['$NEWPAGE'] = wfMsg( 'email_notification_lastvisitedrevisiontext' );
292 $keys['$OLDID'] = $article->mOldid;
293 } else {
294 $keys['$NEWPAGE'] = wfMsg( 'email_notification_newpagetext' );
295 # clear $OLDID placeholder in the message template
296 $keys['$OLDID'] = '';
297 }
298
299 $body = strtr( $body, $keys );
300
301 $pagetitle = $article->mTitle;
302 if( $article->mNamespace != NS_MAIN ) {
303 $pagetitle = $wgLang->getNsText( $article->mNamespace ) . ':' . $pagetitle;
304 }
305 $subject = str_replace( '$PAGETITLE', str_replace( '_', ' ', $pagetitle ) , $subject);
306 $keys['%24PAGETITLE_RAWURL'] = wfUrlencode( $pagetitle );
307 $keys['$PAGETITLE_RAWURL'] = wfUrlencode( $pagetitle );
308 $keys['%24PAGETITLE'] = $pagetitle; # needed for the {{localurl:$PAGETITLE}} in the messagetext, "$" appears here as "%24"
309 $keys['$PAGETITLE'] = $pagetitle;
310 $keys['$PAGETIMESTAMP'] = $article->mTimestamp; # this is the raw internal timestamp - can be useful, too
311 $keys['$PAGEEDITDATEUTC'] = $wgLang->timeanddate( $article->mTimestamp, false, false, false );
312 $keys['$PAGEMINOREDIT'] = $medit;
313 $keys['$PAGESUMMARY'] = $summary;
314
315
316 # Reveal the page editor's address as REPLY-TO address only if
317 # the user has not opted-out and the option is enabled at the
318 # global configuration level.
319 $name = $pageeditorUser->getName();
320 $adminAddress = 'WikiAdmin <' . $wgEmergencyContact . '>';
321 $editorAddress = $name . ' <' . $pageeditorUser->getEmail() . '>';
322 if( $wgEmailNotificationRevealPageEditorAddress
323 && ( $pageeditorUser->getEmail() != '' )
324 && $pageeditorUser->getOption( 'enotifrevealaddr' ) ) {
325 if( $wgEmailNotificationMailsSentFromPageEditor ) {
326 $from = $editorAddress;
327 } else {
328 $from = $adminAddress;
329 $replyto = $editorAddress;
330 }
331 $keys['$PAGEEDITORNAMEANDEMAILADDR'] = $editorAddress;
332 } else {
333 $from = $adminAddress;
334 $replyto = $wgNoReplyAddress;
335 $keys['$PAGEEDITORNAMEANDEMAILADDR'] = $replyto;
336 }
337
338 if( $pageeditorUser->isIP( $name ) ) {
339 #real anon (user:xxx.xxx.xxx.xxx)
340 $anon = $name . ' (anonymous user)';
341 $anonUrl = wfUrlencode( $name ) . ' (anonymous user)';
342 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
343
344 $keys['$PAGEEDITOR_RAWURL'] = $anonUrl;
345 $keys['%24PAGEEDITOR_RAWURL'] = $anonUrl;
346 $keys['%24PAGEEDITORE'] = $anon;
347 $keys['$PAGEEDITORE'] = $anon;
348 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
349 } else {
350 $subject = str_replace('$PAGEEDITOR', $name, $subject);
351 $keys['$PAGEEDITOR_RAWURL'] = wfUrlencode( $name );
352 $keys['%24PAGEEDITOR_RAWURL'] = wfUrlencode( $name );
353 $keys['%24PAGEEDITORE'] = $pageeditorUser->getTitleKey();
354 $keys['$PAGEEDITORE'] = $pageeditorUser->getTitleKey();
355 $keys['$PAGEEDITOR'] = $name;
356 }
357 $body = strtr( $body, $keys );
358
359 # now save this as the constant user-independent part of the message
360 $this->to = $to;
361 $this->from = $from;
362 $this->replyto = $replyto;
363 $this->subject = wfQuotedprintable($subject);
364 $this->body = $body;
365 return $this;
366 }
367
368
369
370 /**
371 * Does the per-user customizations to a notification e-mail (name,
372 * timestamp in proper timezone, etc) and sends it out.
373 * Returns true if the mail was sent successfully.
374 *
375 * @param User $watchingUser
376 * @param object $mail
377 * @param Article $article
378 * @return bool
379 * @access private
380 */
381 function composeAndSendPersonalisedMail( $watchingUser, $mail, $article ) {
382 global $wgLang;
383
384 $to = $watchingUser->getName() . ' <' . $watchingUser->getEmail() . '>';
385 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $mail->body );
386 $body = str_replace( '$WATCHINGUSEREMAILADDR', $watchingUser->getEmail(), $body );
387
388 $timecorrection = $watchingUser->getOption( 'timecorrection' );
389 if( !$timecorrection ) {
390 # fail safe - I prefer it. TomGries
391 $timecorrection = '00:00';
392 }
393 # $PAGEEDITDATE is the time and date of the page change
394 # expressed in terms of individual local time of the notification
395 # recipient, i.e. watching user
396 $body = str_replace('$PAGEEDITDATE',
397 $wgLang->timeanddate( $article->mTimestamp, true, false, $timecorrection ),
398 $body);
399
400 $error = userMailer( $to, $mail->from, $mail->subject, $body, $mail->replyto );
401 return ($error == '');
402 }
403
404 } # end of class EmailNotification
405 ?>