* (bug 7010) Don't send email notifications for watched talk pages when user
[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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
30 */
31 function wfRFC822Phrase( $phrase ) {
32 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
33 return '"' . $phrase . '"';
34 }
35
36 class MailAddress {
37 /**
38 * @param mixed $address String with an email address, or a User object
39 * @param string $name Human-readable name if a string address is given
40 */
41 function MailAddress( $address, $name=null ) {
42 if( is_object( $address ) && is_a( $address, 'User' ) ) {
43 $this->address = $address->getEmail();
44 $this->name = $address->getName();
45 } else {
46 $this->address = strval( $address );
47 $this->name = strval( $name );
48 }
49 }
50
51 /**
52 * Return formatted and quoted address to insert into SMTP headers
53 * @return string
54 */
55 function toString() {
56 if( $this->name != '' ) {
57 $quoted = wfQuotedPrintable( $this->name );
58 if( strpos( $quoted, '.' ) !== false ) {
59 $quoted = '"' . $quoted . '"';
60 }
61 return "$quoted <{$this->address}>";
62 } else {
63 return $this->address;
64 }
65 }
66 }
67
68 /**
69 * This function will perform a direct (authenticated) login to
70 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
71 * array of parameters. It requires PEAR:Mail to do that.
72 * Otherwise it just uses the standard PHP 'mail' function.
73 *
74 * @param $to MailAddress: recipient's email
75 * @param $from MailAddress: sender's email
76 * @param $subject String: email's subject.
77 * @param $body String: email's text.
78 * @param $replyto String: optional reply-to email (default: false).
79 */
80 function userMailer( $to, $from, $subject, $body, $replyto=false ) {
81 global $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString;
82
83 if (is_array( $wgSMTP )) {
84 require_once( 'Mail.php' );
85
86 $timestamp = time();
87 $dest = $to->address;
88
89 $headers['From'] = $from->toString();
90 $headers['To'] = $to->toString();
91 if ( $replyto ) {
92 $headers['Reply-To'] = $replyto;
93 }
94 $headers['Subject'] = wfQuotedPrintable( $subject );
95 $headers['Date'] = date( 'r' );
96 $headers['MIME-Version'] = '1.0';
97 $headers['Content-type'] = 'text/plain; charset='.$wgOutputEncoding;
98 $headers['Content-transfer-encoding'] = '8bit';
99 $headers['Message-ID'] = "<{$timestamp}" . $wgUser->getName() . '@' . $wgSMTP['IDHost'] . '>'; // FIXME
100 $headers['X-Mailer'] = 'MediaWiki mailer';
101
102 // Create the mail object using the Mail::factory method
103 $mail_object =& Mail::factory('smtp', $wgSMTP);
104 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
105 $mailResult =& $mail_object->send($dest, $headers, $body);
106
107 # Based on the result return an error string,
108 if ($mailResult === true) {
109 return '';
110 } elseif (is_object($mailResult)) {
111 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
112 return $mailResult->getMessage();
113 } else {
114 wfDebug( "PEAR::Mail failed, unknown error result\n" );
115 return 'Mail object return unknown error.';
116 }
117 } else {
118 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
119 # (fifth parameter of the PHP mail function, see some lines below)
120 $headers =
121 "MIME-Version: 1.0\n" .
122 "Content-type: text/plain; charset={$wgOutputEncoding}\n" .
123 "Content-Transfer-Encoding: 8bit\n" .
124 "X-Mailer: MediaWiki mailer\n".
125 'From: ' . $from->toString() . "\n";
126 if ($replyto) {
127 $headers .= "Reply-To: $replyto\n";
128 }
129
130 $dest = $to->toString();
131
132 $wgErrorString = '';
133 set_error_handler( 'mailErrorHandler' );
134 wfDebug( "Sending mail via internal mail() function to $dest\n" );
135 mail( $dest, wfQuotedPrintable( $subject ), $body, $headers );
136 restore_error_handler();
137
138 if ( $wgErrorString ) {
139 wfDebug( "Error sending mail: $wgErrorString\n" );
140 }
141 return $wgErrorString;
142 }
143 }
144
145 /**
146 * Get the mail error message in global $wgErrorString
147 *
148 * @param $code Integer: error number
149 * @param $string String: error message
150 */
151 function mailErrorHandler( $code, $string ) {
152 global $wgErrorString;
153 $wgErrorString = preg_replace( "/^mail\(\): /", '', $string );
154 }
155
156
157 /**
158 * This module processes the email notifications when the current page is
159 * changed. It looks up the table watchlist to find out which users are watching
160 * that page.
161 *
162 * The current implementation sends independent emails to each watching user for
163 * the following reason:
164 *
165 * - Each watching user will be notified about the page edit time expressed in
166 * his/her local time (UTC is shown additionally). To achieve this, we need to
167 * find the individual timeoffset of each watching user from the preferences..
168 *
169 * Suggested improvement to slack down the number of sent emails: We could think
170 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
171 * same timeoffset in their preferences.
172 *
173 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
174 *
175 * @package MediaWiki
176 *
177 */
178 class EmailNotification {
179 /**@{{
180 * @private
181 */
182 var $to, $subject, $body, $replyto, $from;
183 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
184
185 /**@}}*/
186
187 /**
188 * @todo document
189 * @param $title Title object
190 * @param $timestamp
191 * @param $summary
192 * @param $minorEdit
193 * @param $oldid (default: false)
194 */
195 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
196
197 # we use $wgEmergencyContact as sender's address
198 global $wgUser, $wgEnotifWatchlist;
199 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
200
201 $fname = 'UserMailer::notifyOnPageChange';
202 wfProfileIn( $fname );
203
204 # The following code is only run, if several conditions are met:
205 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
206 # 2. minor edits (changes) are only regarded if the global flag indicates so
207
208 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
209 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
210 $enotifwatchlistpage = $wgEnotifWatchlist;
211
212 if ( (!$minorEdit || $wgEnotifMinorEdits) ) {
213 if( $wgEnotifWatchlist ) {
214 // Send updates to watchers other than the current editor
215 $userCondition = 'wl_user <> ' . intval( $wgUser->getId() );
216 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK ) {
217 $targetUser = User::newFromName( $title->getText() );
218 if( is_null( $targetUser ) ) {
219 wfDebug( "$fname: user-talk-only mode; no such user\n" );
220 $userCondition = false;
221 } elseif( $targetUser->getId() == $wgUser->getId() ) {
222 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
223 $userCondition = false;
224 } else {
225 // Don't notify anyone other than the owner of the talk page
226 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
227 }
228 } else {
229 // Notifications disabled
230 $userCondition = false;
231 }
232 if( $userCondition ) {
233 $dbr =& wfGetDB( DB_MASTER );
234 extract( $dbr->tableNames( 'watchlist' ) );
235
236 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
237 array(
238 'wl_title' => $title->getDBkey(),
239 'wl_namespace' => $title->getNamespace(),
240 $userCondition,
241 'wl_notificationtimestamp IS NULL',
242 ), $fname );
243
244 # if anyone is watching ... set up the email message text which is
245 # common for all receipients ...
246 if ( $dbr->numRows( $res ) > 0 ) {
247 $this->title =& $title;
248 $this->timestamp = $timestamp;
249 $this->summary = $summary;
250 $this->minorEdit = $minorEdit;
251 $this->oldid = $oldid;
252
253 $this->composeCommonMailtext();
254 $watchingUser = new User();
255
256 # ... now do for all watching users ... if the options fit
257 for ($i = 1; $i <= $dbr->numRows( $res ); $i++) {
258
259 $wuser = $dbr->fetchObject( $res );
260 $watchingUser->setID($wuser->wl_user);
261
262 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
263 ( $enotifusertalkpage
264 && $watchingUser->getOption('enotifusertalkpages')
265 && $title->equals( $watchingUser->getTalkPage() ) )
266 && (!$minorEdit || ($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
267 && ($watchingUser->isEmailConfirmed() ) ) {
268 # ... adjust remaining text and page edit time placeholders
269 # which needs to be personalized for each user
270 $this->composeAndSendPersonalisedMail( $watchingUser );
271
272 } # if the watching user has an email address in the preferences
273 }
274 }
275 } # if anyone is watching
276 } # if $wgEnotifWatchlist = true
277
278 if ( $wgShowUpdatedMarker || $wgEnotifWatchlist ) {
279 # mark the changed watch-listed page with a timestamp, so that the page is
280 # listed with an "updated since your last visit" icon in the watch list, ...
281 $dbw =& wfGetDB( DB_MASTER );
282 $success = $dbw->update( 'watchlist',
283 array( /* SET */
284 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
285 ), array( /* WHERE */
286 'wl_title' => $title->getDBkey(),
287 'wl_namespace' => $title->getNamespace(),
288 ), 'UserMailer::NotifyOnChange'
289 );
290 # FIXME what do we do on failure ?
291 }
292 wfProfileOut( $fname );
293 } # function NotifyOnChange
294
295 /**
296 * @private
297 */
298 function composeCommonMailtext() {
299 global $wgUser, $wgEmergencyContact, $wgNoReplyAddress;
300 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
301
302 $summary = ($this->summary == '') ? ' - ' : $this->summary;
303 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
304
305 # You as the WikiAdmin and Sysops can make use of plenty of
306 # named variables when composing your notification emails while
307 # simply editing the Meta pages
308
309 $subject = wfMsgForContent( 'enotif_subject' );
310 $body = wfMsgForContent( 'enotif_body' );
311 $from = ''; /* fail safe */
312 $replyto = ''; /* fail safe */
313 $keys = array();
314
315 # regarding the use of oldid as an indicator for the last visited version, see also
316 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
317 # However, in the case of a new page which is already watched, we have no previous version to compare
318 if( $this->oldid ) {
319 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
320 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
321 $keys['$OLDID'] = $this->oldid;
322 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
323 } else {
324 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
325 # clear $OLDID placeholder in the message template
326 $keys['$OLDID'] = '';
327 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
328 }
329
330 $body = strtr( $body, $keys );
331 $pagetitle = $this->title->getPrefixedText();
332 $keys['$PAGETITLE'] = $pagetitle;
333 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
334
335 $keys['$PAGEMINOREDIT'] = $medit;
336 $keys['$PAGESUMMARY'] = $summary;
337
338 $subject = strtr( $subject, $keys );
339
340 # Reveal the page editor's address as REPLY-TO address only if
341 # the user has not opted-out and the option is enabled at the
342 # global configuration level.
343 $name = $wgUser->getName();
344 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
345 $editorAddress = new MailAddress( $wgUser );
346 if( $wgEnotifRevealEditorAddress
347 && ( $wgUser->getEmail() != '' )
348 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
349 if( $wgEnotifFromEditor ) {
350 $from = $editorAddress;
351 } else {
352 $from = $adminAddress;
353 $replyto = $editorAddress;
354 }
355 } else {
356 $from = $adminAddress;
357 $replyto = $wgNoReplyAddress;
358 }
359
360 if( $wgUser->isIP( $name ) ) {
361 #real anon (user:xxx.xxx.xxx.xxx)
362 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
363 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
364 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
365 } else {
366 $subject = str_replace('$PAGEEDITOR', $name, $subject);
367 $keys['$PAGEEDITOR'] = $name;
368 $emailPage = Title::makeTitle( NS_SPECIAL, 'Emailuser/' . $name );
369 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
370 }
371 $userPage = $wgUser->getUserPage();
372 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
373 $body = strtr( $body, $keys );
374 $body = wordwrap( $body, 72 );
375
376 # now save this as the constant user-independent part of the message
377 $this->from = $from;
378 $this->replyto = $replyto;
379 $this->subject = $subject;
380 $this->body = $body;
381 }
382
383
384
385 /**
386 * Does the per-user customizations to a notification e-mail (name,
387 * timestamp in proper timezone, etc) and sends it out.
388 * Returns true if the mail was sent successfully.
389 *
390 * @param User $watchingUser
391 * @param object $mail
392 * @return bool
393 * @private
394 */
395 function composeAndSendPersonalisedMail( $watchingUser ) {
396 global $wgLang;
397 // From the PHP manual:
398 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
399 // The mail command will not parse this properly while talking with the MTA.
400 $to = new MailAddress( $watchingUser );
401 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body );
402
403 $timecorrection = $watchingUser->getOption( 'timecorrection' );
404
405 # $PAGEEDITDATE is the time and date of the page change
406 # expressed in terms of individual local time of the notification
407 # recipient, i.e. watching user
408 $body = str_replace('$PAGEEDITDATE',
409 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
410 $body);
411
412 $error = userMailer( $to, $this->from, $this->subject, $body, $this->replyto );
413 return ($error == '');
414 }
415
416 } # end of class EmailNotification
417 ?>