3 * Classes used to send e-mails
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.
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.
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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author <brion@pobox.com>
22 * @author <mail@tgries.de>
23 * @author Tim Starling
24 * @author Luke Welling lwelling@wikimedia.org
28 * This module processes the email notifications when the current page is
29 * changed. It looks up the table watchlist to find out which users are watching
32 * The current implementation sends independent emails to each watching user for
33 * the following reason:
35 * - Each watching user will be notified about the page edit time expressed in
36 * his/her local time (UTC is shown additionally). To achieve this, we need to
37 * find the individual timeoffset of each watching user from the preferences..
39 * Suggested improvement to slack down the number of sent emails: We could think
40 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
41 * same timeoffset in their preferences.
43 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
45 class EmailNotification
{
48 * Notification is due to user's user talk being edited
50 const USER_TALK
= 'user_talk';
52 * Notification is due to a watchlisted page being edited
54 const WATCHLIST
= 'watchlist';
56 * Notification because user is notified for all changes
58 const ALL_CHANGES
= 'all_changes';
60 protected $subject, $body, $replyto, $from;
61 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
62 protected $mailTargets = array();
75 * @param User $editor The editor that triggered the update. Their notification
76 * timestamp will not be updated(they have already seen it)
77 * @param Title $title The title to update timestamps for
78 * @param string $timestamp Set the update timestamp to this value
79 * @return int[] Array of user IDs
81 public static function updateWatchlistTimestamp( User
$editor, Title
$title, $timestamp ) {
82 global $wgEnotifWatchlist, $wgShowUpdatedMarker;
84 if ( !$wgEnotifWatchlist && !$wgShowUpdatedMarker ) {
88 $dbw = wfGetDB( DB_MASTER
);
89 $res = $dbw->select( array( 'watchlist' ),
92 'wl_user != ' . intval( $editor->getID() ),
93 'wl_namespace' => $title->getNamespace(),
94 'wl_title' => $title->getDBkey(),
95 'wl_notificationtimestamp IS NULL',
100 foreach ( $res as $row ) {
101 $watchers[] = intval( $row->wl_user
);
105 // Update wl_notificationtimestamp for all watching users except the editor
107 $dbw->onTransactionIdle(
108 function () use ( $dbw, $timestamp, $watchers, $title, $fname ) {
109 $dbw->update( 'watchlist',
111 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
112 ), array( /* WHERE */
113 'wl_user' => $watchers,
114 'wl_namespace' => $title->getNamespace(),
115 'wl_title' => $title->getDBkey(),
126 * Send emails corresponding to the user $editor editing the page $title.
128 * May be deferred via the job queue.
130 * @param User $editor
131 * @param Title $title
132 * @param string $timestamp
133 * @param string $summary
134 * @param bool $minorEdit
135 * @param bool $oldid (default: false)
136 * @param string $pageStatus (default: 'changed')
138 public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
139 $minorEdit, $oldid = false, $pageStatus = 'changed'
141 global $wgEnotifUseJobQ, $wgEnotifMinorEdits, $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
143 if ( $title->getNamespace() < 0 ) {
147 // update wl_notificationtimestamp for watchers
148 $watchers = self
::updateWatchlistTimestamp( $editor, $title, $timestamp );
151 // $watchers deals with $wgEnotifWatchlist.
152 // If nobody is watching the page, and there are no users notified on all changes
153 // don't bother creating a job/trying to send emails, unless it's a
154 // talk page with an applicable notification.
155 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
157 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
158 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
159 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
160 if ( $wgEnotifUserTalk
162 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
173 if ( $wgEnotifUseJobQ ) {
175 'editor' => $editor->getName(),
176 'editorID' => $editor->getID(),
177 'timestamp' => $timestamp,
178 'summary' => $summary,
179 'minorEdit' => $minorEdit,
181 'watchers' => $watchers,
182 'pageStatus' => $pageStatus
184 $job = new EnotifNotifyJob( $title, $params );
185 JobQueueGroup
::singleton()->lazyPush( $job );
187 $this->actuallyNotifyOnPageChange(
201 * Immediate version of notifyOnPageChange().
203 * Send emails corresponding to the user $editor editing the page $title.
205 * @note Do not call directly. Use notifyOnPageChange so that wl_notificationtimestamp is updated.
206 * @param User $editor
207 * @param Title $title
208 * @param string $timestamp Edit timestamp
209 * @param string $summary Edit summary
210 * @param bool $minorEdit
211 * @param int $oldid Revision ID
212 * @param array $watchers Array of user IDs
213 * @param string $pageStatus
214 * @throws MWException
216 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
217 $oldid, $watchers, $pageStatus = 'changed' ) {
218 # we use $wgPasswordSender as sender's address
219 global $wgUsersNotifiedOnAllChanges;
220 global $wgEnotifWatchlist, $wgBlockDisablesLogin;
221 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
223 # The following code is only run, if several conditions are met:
224 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
225 # 2. minor edits (changes) are only regarded if the global flag indicates so
227 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
229 $this->title
= $title;
230 $this->timestamp
= $timestamp;
231 $this->summary
= $summary;
232 $this->minorEdit
= $minorEdit;
233 $this->oldid
= $oldid;
234 $this->editor
= $editor;
235 $this->composed_common
= false;
236 $this->pageStatus
= $pageStatus;
238 $formattedPageStatus = array( 'deleted', 'created', 'moved', 'restored', 'changed' );
240 Hooks
::run( 'UpdateUserMailerFormattedPageStatus', array( &$formattedPageStatus ) );
241 if ( !in_array( $this->pageStatus
, $formattedPageStatus ) ) {
242 throw new MWException( 'Not a valid page status!' );
247 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
248 if ( $wgEnotifUserTalk
250 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
252 $targetUser = User
::newFromName( $title->getText() );
253 $this->compose( $targetUser, self
::USER_TALK
);
254 $userTalkId = $targetUser->getId();
257 if ( $wgEnotifWatchlist ) {
258 // Send updates to watchers other than the current editor
259 // and don't send to watchers who are blocked and cannot login
260 $userArray = UserArray
::newFromIDs( $watchers );
261 foreach ( $userArray as $watchingUser ) {
262 if ( $watchingUser->getOption( 'enotifwatchlistpages' )
263 && ( !$minorEdit ||
$watchingUser->getOption( 'enotifminoredits' ) )
264 && $watchingUser->isEmailConfirmed()
265 && $watchingUser->getID() != $userTalkId
266 && !in_array( $watchingUser->getName(), $wgUsersNotifiedOnAllChanges )
267 && !( $wgBlockDisablesLogin && $watchingUser->isBlocked() )
269 if ( Hooks
::run( 'SendWatchlistEmailNotification', array( $watchingUser, $title, $this ) ) ) {
270 $this->compose( $watchingUser, self
::WATCHLIST
);
277 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
278 if ( $editor->getName() == $name ) {
279 // No point notifying the user that actually made the change!
282 $user = User
::newFromName( $name );
283 $this->compose( $user, self
::ALL_CHANGES
);
290 * @param User $editor
291 * @param Title $title
292 * @param bool $minorEdit
295 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
296 global $wgEnotifUserTalk, $wgBlockDisablesLogin;
297 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
299 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
300 $targetUser = User
::newFromName( $title->getText() );
302 if ( !$targetUser ||
$targetUser->isAnon() ) {
303 wfDebug( __METHOD__
. ": user talk page edited, but user does not exist\n" );
304 } elseif ( $targetUser->getId() == $editor->getId() ) {
305 wfDebug( __METHOD__
. ": user edited their own talk page, no notification sent\n" );
306 } elseif ( $wgBlockDisablesLogin && $targetUser->isBlocked() ) {
307 wfDebug( __METHOD__
. ": talk page owner is blocked and cannot login, no notification sent\n" );
308 } elseif ( $targetUser->getOption( 'enotifusertalkpages' )
309 && ( !$minorEdit ||
$targetUser->getOption( 'enotifminoredits' ) )
311 if ( !$targetUser->isEmailConfirmed() ) {
312 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
313 } elseif ( !Hooks
::run( 'AbortTalkPageEmailNotification', array( $targetUser, $title ) ) ) {
314 wfDebug( __METHOD__
. ": talk page update notification is aborted for this user\n" );
316 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
320 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
327 * Generate the generic "this page has been changed" e-mail text.
329 private function composeCommonMailtext() {
330 global $wgPasswordSender, $wgNoReplyAddress;
331 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
332 global $wgEnotifImpersonal, $wgEnotifUseRealName;
334 $this->composed_common
= true;
336 # You as the WikiAdmin and Sysops can make use of plenty of
337 # named variables when composing your notification emails while
338 # simply editing the Meta pages
341 $postTransformKeys = array();
342 $pageTitleUrl = $this->title
->getCanonicalURL();
343 $pageTitle = $this->title
->getPrefixedText();
345 if ( $this->oldid
) {
346 // Always show a link to the diff which triggered the mail. See bug 32210.
347 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
348 $this->title
->getCanonicalURL( array( 'diff' => 'next', 'oldid' => $this->oldid
) ) )
349 ->inContentLanguage()->text();
351 if ( !$wgEnotifImpersonal ) {
352 // For personal mail, also show a link to the diff of all changes
353 // since last visited.
354 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
355 $this->title
->getCanonicalURL( array( 'diff' => '0', 'oldid' => $this->oldid
) ) )
356 ->inContentLanguage()->text();
358 $keys['$OLDID'] = $this->oldid
;
359 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
360 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
362 # clear $OLDID placeholder in the message template
363 $keys['$OLDID'] = '';
364 $keys['$NEWPAGE'] = '';
365 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
366 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
369 $keys['$PAGETITLE'] = $this->title
->getPrefixedText();
370 $keys['$PAGETITLE_URL'] = $this->title
->getCanonicalURL();
371 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
372 wfMessage( 'minoredit' )->inContentLanguage()->text() : '';
373 $keys['$UNWATCHURL'] = $this->title
->getCanonicalURL( 'action=unwatch' );
375 if ( $this->editor
->isAnon() ) {
376 # real anon (user:xxx.xxx.xxx.xxx)
377 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor
->getName() )
378 ->inContentLanguage()->text();
379 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
382 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName && $this->editor
->getRealName() !== ''
383 ?
$this->editor
->getRealName() : $this->editor
->getName();
384 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $this->editor
->getName() );
385 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
388 $keys['$PAGEEDITOR_WIKI'] = $this->editor
->getUserPage()->getCanonicalURL();
389 $keys['$HELPPAGE'] = wfExpandUrl(
390 Skin
::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
393 # Replace this after transforming the message, bug 35019
394 $postTransformKeys['$PAGESUMMARY'] = $this->summary
== '' ?
' - ' : $this->summary
;
396 // Now build message's subject and body
399 // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
400 // enotif_subject_restored, enotif_subject_changed
401 $this->subject
= wfMessage( 'enotif_subject_' . $this->pageStatus
)->inContentLanguage()
402 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
405 // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
406 // enotif_body_intro_restored, enotif_body_intro_changed
407 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus
)
408 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
411 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
412 $body = strtr( $body, $keys );
413 $body = MessageCache
::singleton()->transform( $body, false, null, $this->title
);
414 $this->body
= wordwrap( strtr( $body, $postTransformKeys ), 72 );
416 # Reveal the page editor's address as REPLY-TO address only if
417 # the user has not opted-out and the option is enabled at the
418 # global configuration level.
419 $adminAddress = new MailAddress( $wgPasswordSender,
420 wfMessage( 'emailsender' )->inContentLanguage()->text() );
421 if ( $wgEnotifRevealEditorAddress
422 && ( $this->editor
->getEmail() != '' )
423 && $this->editor
->getOption( 'enotifrevealaddr' )
425 $editorAddress = MailAddress
::newFromUser( $this->editor
);
426 if ( $wgEnotifFromEditor ) {
427 $this->from
= $editorAddress;
429 $this->from
= $adminAddress;
430 $this->replyto
= $editorAddress;
433 $this->from
= $adminAddress;
434 $this->replyto
= new MailAddress( $wgNoReplyAddress );
439 * Compose a mail to a given user and either queue it for sending, or send it now,
440 * depending on settings.
442 * Call sendMails() to send any mails that were queued.
444 * @param string $source
446 function compose( $user, $source ) {
447 global $wgEnotifImpersonal;
449 if ( !$this->composed_common
) {
450 $this->composeCommonMailtext();
453 if ( $wgEnotifImpersonal ) {
454 $this->mailTargets
[] = MailAddress
::newFromUser( $user );
456 $this->sendPersonalised( $user, $source );
461 * Send any queued mails
463 function sendMails() {
464 global $wgEnotifImpersonal;
465 if ( $wgEnotifImpersonal ) {
466 $this->sendImpersonal( $this->mailTargets
);
471 * Does the per-user customizations to a notification e-mail (name,
472 * timestamp in proper timezone, etc) and sends it out.
473 * Returns true if the mail was sent successfully.
475 * @param User $watchingUser
476 * @param string $source
480 function sendPersonalised( $watchingUser, $source ) {
481 global $wgContLang, $wgEnotifUseRealName;
482 // From the PHP manual:
483 // Note: The to parameter cannot be an address in the form of
484 // "Something <someone@example.com>". The mail command will not parse
485 // this properly while talking with the MTA.
486 $to = MailAddress
::newFromUser( $watchingUser );
488 # $PAGEEDITDATE is the time and date of the page change
489 # expressed in terms of individual local time of the notification
490 # recipient, i.e. watching user
492 array( '$WATCHINGUSERNAME',
495 array( $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
496 ?
$watchingUser->getRealName() : $watchingUser->getName(),
497 $wgContLang->userDate( $this->timestamp
, $watchingUser ),
498 $wgContLang->userTime( $this->timestamp
, $watchingUser ) ),
502 if ( $source === self
::WATCHLIST
) {
503 $headers['List-Help'] = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Watchlist';
506 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, array(
507 'replyTo' => $this->replyto
,
508 'headers' => $headers,
513 * Same as sendPersonalised but does impersonal mail suitable for bulk
514 * mailing. Takes an array of MailAddress objects.
515 * @param MailAddress[] $addresses
516 * @return Status|null
518 function sendImpersonal( $addresses ) {
521 if ( empty( $addresses ) ) {
526 array( '$WATCHINGUSERNAME',
529 array( wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
530 $wgContLang->date( $this->timestamp
, false, false ),
531 $wgContLang->time( $this->timestamp
, false, false ) ),
534 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, array(
535 'replyTo' => $this->replyto
,