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