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
27 use MediaWiki\MediaWikiServices
;
30 * This module processes the email notifications when the current page is
31 * changed. It looks up the table watchlist to find out which users are watching
34 * The current implementation sends independent emails to each watching user for
35 * the following reason:
37 * - Each watching user will be notified about the page edit time expressed in
38 * his/her local time (UTC is shown additionally). To achieve this, we need to
39 * find the individual timeoffset of each watching user from the preferences..
41 * Suggested improvement to slack down the number of sent emails: We could think
42 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
43 * same timeoffset in their preferences.
45 * Visit the documentation pages under
46 * https://www.mediawiki.org/wiki/Help:Watching_pages
48 class EmailNotification
{
51 * Notification is due to user's user talk being edited
53 const USER_TALK
= 'user_talk';
55 * Notification is due to a watchlisted page being edited
57 const WATCHLIST
= 'watchlist';
59 * Notification because user is notified for all changes
61 const ALL_CHANGES
= 'all_changes';
63 protected $subject, $body, $replyto, $from;
64 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
65 protected $mailTargets = [];
78 * Extensions that have hooks for
79 * UpdateUserMailerFormattedPageStatus (to provide additional
80 * pageStatus indicators) need a way to make sure that, when their
81 * hook is called in SendWatchlistemailNotification, they only
82 * handle notifications using their pageStatus indicator.
87 public function getPageStatus() {
88 return $this->pageStatus
;
92 * Send emails corresponding to the user $editor editing the page $title.
94 * May be deferred via the job queue.
98 * @param string $timestamp
99 * @param string $summary
100 * @param bool $minorEdit
101 * @param bool $oldid (default: false)
102 * @param string $pageStatus (default: 'changed')
104 public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
105 $minorEdit, $oldid = false, $pageStatus = 'changed'
107 global $wgEnotifMinorEdits, $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
109 if ( $title->getNamespace() < 0 ) {
113 // update wl_notificationtimestamp for watchers
114 $config = RequestContext
::getMain()->getConfig();
116 if ( $config->get( 'EnotifWatchlist' ) ||
$config->get( 'ShowUpdatedMarker' ) ) {
117 $watchers = MediaWikiServices
::getInstance()->getWatchedItemStore()->updateNotificationTimestamp(
125 // $watchers deals with $wgEnotifWatchlist.
126 // If nobody is watching the page, and there are no users notified on all changes
127 // don't bother creating a job/trying to send emails, unless it's a
128 // talk page with an applicable notification.
129 if ( $watchers === [] && !count( $wgUsersNotifiedOnAllChanges ) ) {
131 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
132 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !MediaWikiServices
::getInstance()
133 ->getPermissionManager()
134 ->userHasRight( $editor, 'nominornewtalk' ) )
136 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
137 if ( $wgEnotifUserTalk
139 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
147 JobQueueGroup
::singleton()->lazyPush( new EnotifNotifyJob(
150 'editor' => $editor->getName(),
151 'editorID' => $editor->getId(),
152 'timestamp' => $timestamp,
153 'summary' => $summary,
154 'minorEdit' => $minorEdit,
156 'watchers' => $watchers,
157 'pageStatus' => $pageStatus
164 * Immediate version of notifyOnPageChange().
166 * Send emails corresponding to the user $editor editing the page $title.
168 * @note Do not call directly. Use notifyOnPageChange so that wl_notificationtimestamp is updated.
169 * @param User $editor
170 * @param Title $title
171 * @param string $timestamp Edit timestamp
172 * @param string $summary Edit summary
173 * @param bool $minorEdit
174 * @param int $oldid Revision ID
175 * @param array $watchers Array of user IDs
176 * @param string $pageStatus
177 * @throws MWException
179 public function actuallyNotifyOnPageChange(
187 $pageStatus = 'changed'
189 # we use $wgPasswordSender as sender's address
190 global $wgUsersNotifiedOnAllChanges;
191 global $wgEnotifWatchlist, $wgBlockDisablesLogin;
192 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
194 $messageCache = MediaWikiServices
::getInstance()->getMessageCache();
196 # The following code is only run, if several conditions are met:
197 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
198 # 2. minor edits (changes) are only regarded if the global flag indicates so
200 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
202 $this->title
= $title;
203 $this->timestamp
= $timestamp;
204 $this->summary
= $summary;
205 $this->minorEdit
= $minorEdit;
206 $this->oldid
= $oldid;
207 $this->editor
= $editor;
208 $this->composed_common
= false;
209 $this->pageStatus
= $pageStatus;
211 $formattedPageStatus = [ 'deleted', 'created', 'moved', 'restored', 'changed' ];
213 Hooks
::run( 'UpdateUserMailerFormattedPageStatus', [ &$formattedPageStatus ] );
214 if ( !in_array( $this->pageStatus
, $formattedPageStatus ) ) {
215 throw new MWException( 'Not a valid page status!' );
220 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !MediaWikiServices
::getInstance()
221 ->getPermissionManager()
222 ->userHasRight( $editor, 'nominornewtalk' ) )
224 if ( $wgEnotifUserTalk
226 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
228 $targetUser = User
::newFromName( $title->getText() );
229 $this->compose( $targetUser, self
::USER_TALK
, $messageCache );
230 $userTalkId = $targetUser->getId();
233 if ( $wgEnotifWatchlist ) {
234 // Send updates to watchers other than the current editor
235 // and don't send to watchers who are blocked and cannot login
236 $userArray = UserArray
::newFromIDs( $watchers );
237 foreach ( $userArray as $watchingUser ) {
238 if ( $watchingUser->getOption( 'enotifwatchlistpages' )
239 && ( !$minorEdit ||
$watchingUser->getOption( 'enotifminoredits' ) )
240 && $watchingUser->isEmailConfirmed()
241 && $watchingUser->getId() != $userTalkId
242 && !in_array( $watchingUser->getName(), $wgUsersNotifiedOnAllChanges )
243 // @TODO Partial blocks should not prevent the user from logging in.
244 // see: https://phabricator.wikimedia.org/T208895
245 && !( $wgBlockDisablesLogin && $watchingUser->getBlock() )
246 && Hooks
::run( 'SendWatchlistEmailNotification', [ $watchingUser, $title, $this ] )
248 $this->compose( $watchingUser, self
::WATCHLIST
, $messageCache );
254 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
255 if ( $editor->getName() == $name ) {
256 // No point notifying the user that actually made the change!
259 $user = User
::newFromName( $name );
260 $this->compose( $user, self
::ALL_CHANGES
, $messageCache );
267 * @param User $editor
268 * @param Title $title
269 * @param bool $minorEdit
272 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
273 global $wgEnotifUserTalk, $wgBlockDisablesLogin;
274 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
276 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
277 $targetUser = User
::newFromName( $title->getText() );
279 if ( !$targetUser ||
$targetUser->isAnon() ) {
280 wfDebug( __METHOD__
. ": user talk page edited, but user does not exist\n" );
281 } elseif ( $targetUser->getId() == $editor->getId() ) {
282 wfDebug( __METHOD__
. ": user edited their own talk page, no notification sent\n" );
283 } elseif ( $wgBlockDisablesLogin && $targetUser->getBlock() ) {
284 // @TODO Partial blocks should not prevent the user from logging in.
285 // see: https://phabricator.wikimedia.org/T208895
286 wfDebug( __METHOD__
. ": talk page owner is blocked and cannot login, no notification sent\n" );
287 } elseif ( $targetUser->getOption( 'enotifusertalkpages' )
288 && ( !$minorEdit ||
$targetUser->getOption( 'enotifminoredits' ) )
290 if ( !$targetUser->isEmailConfirmed() ) {
291 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
292 } elseif ( !Hooks
::run( 'AbortTalkPageEmailNotification', [ $targetUser, $title ] ) ) {
293 wfDebug( __METHOD__
. ": talk page update notification is aborted for this user\n" );
295 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
299 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
306 * Generate the generic "this page has been changed" e-mail text.
307 * @param MessageCache $messageCache
309 private function composeCommonMailtext( MessageCache
$messageCache ) {
310 global $wgPasswordSender, $wgNoReplyAddress;
311 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
312 global $wgEnotifImpersonal, $wgEnotifUseRealName;
314 $this->composed_common
= true;
316 # You as the WikiAdmin and Sysops can make use of plenty of
317 # named variables when composing your notification emails while
318 # simply editing the Meta pages
321 $postTransformKeys = [];
322 $pageTitleUrl = $this->title
->getCanonicalURL();
323 $pageTitle = $this->title
->getPrefixedText();
325 if ( $this->oldid
) {
326 // Always show a link to the diff which triggered the mail. See T34210.
327 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
328 $this->title
->getCanonicalURL( [ 'diff' => 'next', 'oldid' => $this->oldid
] ) )
329 ->inContentLanguage()->text();
331 if ( !$wgEnotifImpersonal ) {
332 // For personal mail, also show a link to the diff of all changes
333 // since last visited.
334 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
335 $this->title
->getCanonicalURL( [ 'diff' => '0', 'oldid' => $this->oldid
] ) )
336 ->inContentLanguage()->text();
338 $keys['$OLDID'] = $this->oldid
;
339 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
340 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
342 # clear $OLDID placeholder in the message template
343 $keys['$OLDID'] = '';
344 $keys['$NEWPAGE'] = '';
345 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
346 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
349 $keys['$PAGETITLE'] = $this->title
->getPrefixedText();
350 $keys['$PAGETITLE_URL'] = $this->title
->getCanonicalURL();
351 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
352 "\n\n" . wfMessage( 'enotif_minoredit' )->inContentLanguage()->text() :
354 $keys['$UNWATCHURL'] = $this->title
->getCanonicalURL( 'action=unwatch' );
356 if ( $this->editor
->isAnon() ) {
357 # real anon (user:xxx.xxx.xxx.xxx)
358 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor
->getName() )
359 ->inContentLanguage()->text();
360 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
363 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName && $this->editor
->getRealName() !== ''
364 ?
$this->editor
->getRealName() : $this->editor
->getName();
365 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $this->editor
->getName() );
366 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
369 $keys['$PAGEEDITOR_WIKI'] = $this->editor
->getUserPage()->getCanonicalURL();
370 $keys['$HELPPAGE'] = wfExpandUrl(
371 Skin
::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
374 # Replace this after transforming the message, T37019
375 $postTransformKeys['$PAGESUMMARY'] = $this->summary
== '' ?
' - ' : $this->summary
;
377 // Now build message's subject and body
380 // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
381 // enotif_subject_restored, enotif_subject_changed
382 $this->subject
= wfMessage( 'enotif_subject_' . $this->pageStatus
)->inContentLanguage()
383 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
386 // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
387 // enotif_body_intro_restored, enotif_body_intro_changed
388 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus
)
389 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
392 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
393 $body = strtr( $body, $keys );
394 $body = $messageCache->transform( $body, false, null, $this->title
);
395 $this->body
= wordwrap( strtr( $body, $postTransformKeys ), 72 );
397 # Reveal the page editor's address as REPLY-TO address only if
398 # the user has not opted-out and the option is enabled at the
399 # global configuration level.
400 $adminAddress = new MailAddress( $wgPasswordSender,
401 wfMessage( 'emailsender' )->inContentLanguage()->text() );
402 if ( $wgEnotifRevealEditorAddress
403 && ( $this->editor
->getEmail() != '' )
404 && $this->editor
->getOption( 'enotifrevealaddr' )
406 $editorAddress = MailAddress
::newFromUser( $this->editor
);
407 if ( $wgEnotifFromEditor ) {
408 $this->from
= $editorAddress;
410 $this->from
= $adminAddress;
411 $this->replyto
= $editorAddress;
414 $this->from
= $adminAddress;
415 $this->replyto
= new MailAddress( $wgNoReplyAddress );
420 * Compose a mail to a given user and either queue it for sending, or send it now,
421 * depending on settings.
423 * Call sendMails() to send any mails that were queued.
425 * @param string $source
426 * @param MessageCache $messageCache
428 private function compose( $user, $source, MessageCache
$messageCache ) {
429 global $wgEnotifImpersonal;
431 if ( !$this->composed_common
) {
432 $this->composeCommonMailtext( $messageCache );
435 if ( $wgEnotifImpersonal ) {
436 $this->mailTargets
[] = MailAddress
::newFromUser( $user );
438 $this->sendPersonalised( $user, $source );
443 * Send any queued mails
445 private function sendMails() {
446 global $wgEnotifImpersonal;
447 if ( $wgEnotifImpersonal ) {
448 $this->sendImpersonal( $this->mailTargets
);
453 * Does the per-user customizations to a notification e-mail (name,
454 * timestamp in proper timezone, etc) and sends it out.
455 * Returns Status if email was sent successfully or not (Status::newGood()
456 * or Status::newFatal() respectively).
458 * @param User $watchingUser
459 * @param string $source
462 private function sendPersonalised( $watchingUser, $source ) {
463 global $wgEnotifUseRealName;
464 // From the PHP manual:
465 // Note: The to parameter cannot be an address in the form of
466 // "Something <someone@example.com>". The mail command will not parse
467 // this properly while talking with the MTA.
468 $to = MailAddress
::newFromUser( $watchingUser );
470 # $PAGEEDITDATE is the time and date of the page change
471 # expressed in terms of individual local time of the notification
472 # recipient, i.e. watching user
473 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
475 [ '$WATCHINGUSERNAME',
478 [ $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
479 ?
$watchingUser->getRealName() : $watchingUser->getName(),
480 $contLang->userDate( $this->timestamp
, $watchingUser ),
481 $contLang->userTime( $this->timestamp
, $watchingUser ) ],
485 if ( $source === self
::WATCHLIST
) {
486 $headers['List-Help'] = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Watchlist';
489 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, [
490 'replyTo' => $this->replyto
,
491 'headers' => $headers,
496 * Same as sendPersonalised but does impersonal mail suitable for bulk
497 * mailing. Takes an array of MailAddress objects.
498 * @param MailAddress[] $addresses
499 * @return Status|null
501 private function sendImpersonal( $addresses ) {
502 if ( empty( $addresses ) ) {
506 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
508 [ '$WATCHINGUSERNAME',
511 [ wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
512 $contLang->date( $this->timestamp
, false, false ),
513 $contLang->time( $this->timestamp
, false, false ) ],
516 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, [
517 'replyTo' => $this->replyto
,