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