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
26 use MediaWiki\Linker\LinkTarget
;
28 use MediaWiki\MediaWikiServices
;
31 * This module processes the email notifications when the current page is
32 * changed. It looks up the table watchlist to find out which users are watching
35 * The current implementation sends independent emails to each watching user for
36 * the following reason:
38 * - Each watching user will be notified about the page edit time expressed in
39 * his/her local time (UTC is shown additionally). To achieve this, we need to
40 * find the individual timeoffset of each watching user from the preferences..
42 * Suggested improvement to slack down the number of sent emails: We could think
43 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
44 * same timeoffset in their preferences.
46 * Visit the documentation pages under
47 * https://www.mediawiki.org/wiki/Help:Watching_pages
49 class EmailNotification
{
52 * Notification is due to user's user talk being edited
54 const USER_TALK
= 'user_talk';
56 * Notification is due to a watchlisted page being edited
58 const WATCHLIST
= 'watchlist';
60 * Notification because user is notified for all changes
62 const ALL_CHANGES
= 'all_changes';
64 protected $subject, $body, $replyto, $from;
65 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
66 protected $mailTargets = [];
79 * @deprecated since 1.27 use WatchedItemStore::updateNotificationTimestamp directly
81 * @param User $editor The editor that triggered the update. Their notification
82 * timestamp will not be updated(they have already seen it)
83 * @param LinkTarget $linkTarget The link target of the title to update timestamps for
84 * @param string $timestamp Set the update timestamp to this value
86 * @return int[] Array of user IDs
88 public static function updateWatchlistTimestamp(
90 LinkTarget
$linkTarget,
93 // wfDeprecated( __METHOD__, '1.27' );
94 $config = RequestContext
::getMain()->getConfig();
95 if ( !$config->get( 'EnotifWatchlist' ) && !$config->get( 'ShowUpdatedMarker' ) ) {
98 return MediaWikiServices
::getInstance()->getWatchedItemStore()->updateNotificationTimestamp(
106 * Send emails corresponding to the user $editor editing the page $title.
108 * May be deferred via the job queue.
110 * @param User $editor
111 * @param Title $title
112 * @param string $timestamp
113 * @param string $summary
114 * @param bool $minorEdit
115 * @param bool $oldid (default: false)
116 * @param string $pageStatus (default: 'changed')
118 public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
119 $minorEdit, $oldid = false, $pageStatus = 'changed'
121 global $wgEnotifMinorEdits, $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
123 if ( $title->getNamespace() < 0 ) {
127 // update wl_notificationtimestamp for watchers
128 $config = RequestContext
::getMain()->getConfig();
130 if ( $config->get( 'EnotifWatchlist' ) ||
$config->get( 'ShowUpdatedMarker' ) ) {
131 $watchers = MediaWikiServices
::getInstance()->getWatchedItemStore()->updateNotificationTimestamp(
139 // $watchers deals with $wgEnotifWatchlist.
140 // If nobody is watching the page, and there are no users notified on all changes
141 // don't bother creating a job/trying to send emails, unless it's a
142 // talk page with an applicable notification.
143 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
145 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
146 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
147 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
148 if ( $wgEnotifUserTalk
150 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
158 JobQueueGroup
::singleton()->lazyPush( new EnotifNotifyJob(
161 'editor' => $editor->getName(),
162 'editorID' => $editor->getId(),
163 'timestamp' => $timestamp,
164 'summary' => $summary,
165 'minorEdit' => $minorEdit,
167 'watchers' => $watchers,
168 'pageStatus' => $pageStatus
175 * Immediate version of notifyOnPageChange().
177 * Send emails corresponding to the user $editor editing the page $title.
179 * @note Do not call directly. Use notifyOnPageChange so that wl_notificationtimestamp is updated.
180 * @param User $editor
181 * @param Title $title
182 * @param string $timestamp Edit timestamp
183 * @param string $summary Edit summary
184 * @param bool $minorEdit
185 * @param int $oldid Revision ID
186 * @param array $watchers Array of user IDs
187 * @param string $pageStatus
188 * @throws MWException
190 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
191 $oldid, $watchers, $pageStatus = 'changed' ) {
192 # we use $wgPasswordSender as sender's address
193 global $wgUsersNotifiedOnAllChanges;
194 global $wgEnotifWatchlist, $wgBlockDisablesLogin;
195 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
197 # The following code is only run, if several conditions are met:
198 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
199 # 2. minor edits (changes) are only regarded if the global flag indicates so
201 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
203 $this->title
= $title;
204 $this->timestamp
= $timestamp;
205 $this->summary
= $summary;
206 $this->minorEdit
= $minorEdit;
207 $this->oldid
= $oldid;
208 $this->editor
= $editor;
209 $this->composed_common
= false;
210 $this->pageStatus
= $pageStatus;
212 $formattedPageStatus = [ 'deleted', 'created', 'moved', 'restored', 'changed' ];
214 Hooks
::run( 'UpdateUserMailerFormattedPageStatus', [ &$formattedPageStatus ] );
215 if ( !in_array( $this->pageStatus
, $formattedPageStatus ) ) {
216 throw new MWException( 'Not a valid page status!' );
221 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
222 if ( $wgEnotifUserTalk
224 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
226 $targetUser = User
::newFromName( $title->getText() );
227 $this->compose( $targetUser, self
::USER_TALK
);
228 $userTalkId = $targetUser->getId();
231 if ( $wgEnotifWatchlist ) {
232 // Send updates to watchers other than the current editor
233 // and don't send to watchers who are blocked and cannot login
234 $userArray = UserArray
::newFromIDs( $watchers );
235 foreach ( $userArray as $watchingUser ) {
236 if ( $watchingUser->getOption( 'enotifwatchlistpages' )
237 && ( !$minorEdit ||
$watchingUser->getOption( 'enotifminoredits' ) )
238 && $watchingUser->isEmailConfirmed()
239 && $watchingUser->getId() != $userTalkId
240 && !in_array( $watchingUser->getName(), $wgUsersNotifiedOnAllChanges )
241 && !( $wgBlockDisablesLogin && $watchingUser->isBlocked() )
243 if ( Hooks
::run( 'SendWatchlistEmailNotification', [ $watchingUser, $title, $this ] ) ) {
244 $this->compose( $watchingUser, self
::WATCHLIST
);
251 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
252 if ( $editor->getName() == $name ) {
253 // No point notifying the user that actually made the change!
256 $user = User
::newFromName( $name );
257 $this->compose( $user, self
::ALL_CHANGES
);
264 * @param User $editor
265 * @param Title $title
266 * @param bool $minorEdit
269 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
270 global $wgEnotifUserTalk, $wgBlockDisablesLogin;
271 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
273 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
274 $targetUser = User
::newFromName( $title->getText() );
276 if ( !$targetUser ||
$targetUser->isAnon() ) {
277 wfDebug( __METHOD__
. ": user talk page edited, but user does not exist\n" );
278 } elseif ( $targetUser->getId() == $editor->getId() ) {
279 wfDebug( __METHOD__
. ": user edited their own talk page, no notification sent\n" );
280 } elseif ( $wgBlockDisablesLogin && $targetUser->isBlocked() ) {
281 wfDebug( __METHOD__
. ": talk page owner is blocked and cannot login, no notification sent\n" );
282 } elseif ( $targetUser->getOption( 'enotifusertalkpages' )
283 && ( !$minorEdit ||
$targetUser->getOption( 'enotifminoredits' ) )
285 if ( !$targetUser->isEmailConfirmed() ) {
286 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
287 } elseif ( !Hooks
::run( 'AbortTalkPageEmailNotification', [ $targetUser, $title ] ) ) {
288 wfDebug( __METHOD__
. ": talk page update notification is aborted for this user\n" );
290 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
294 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
301 * Generate the generic "this page has been changed" e-mail text.
303 private function composeCommonMailtext() {
304 global $wgPasswordSender, $wgNoReplyAddress;
305 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
306 global $wgEnotifImpersonal, $wgEnotifUseRealName;
308 $this->composed_common
= true;
310 # You as the WikiAdmin and Sysops can make use of plenty of
311 # named variables when composing your notification emails while
312 # simply editing the Meta pages
315 $postTransformKeys = [];
316 $pageTitleUrl = $this->title
->getCanonicalURL();
317 $pageTitle = $this->title
->getPrefixedText();
319 if ( $this->oldid
) {
320 // Always show a link to the diff which triggered the mail. See T34210.
321 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
322 $this->title
->getCanonicalURL( [ 'diff' => 'next', 'oldid' => $this->oldid
] ) )
323 ->inContentLanguage()->text();
325 if ( !$wgEnotifImpersonal ) {
326 // For personal mail, also show a link to the diff of all changes
327 // since last visited.
328 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
329 $this->title
->getCanonicalURL( [ 'diff' => '0', 'oldid' => $this->oldid
] ) )
330 ->inContentLanguage()->text();
332 $keys['$OLDID'] = $this->oldid
;
333 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
334 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
336 # clear $OLDID placeholder in the message template
337 $keys['$OLDID'] = '';
338 $keys['$NEWPAGE'] = '';
339 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
340 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
343 $keys['$PAGETITLE'] = $this->title
->getPrefixedText();
344 $keys['$PAGETITLE_URL'] = $this->title
->getCanonicalURL();
345 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
346 wfMessage( 'enotif_minoredit' )->inContentLanguage()->text() : '';
347 $keys['$UNWATCHURL'] = $this->title
->getCanonicalURL( 'action=unwatch' );
349 if ( $this->editor
->isAnon() ) {
350 # real anon (user:xxx.xxx.xxx.xxx)
351 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor
->getName() )
352 ->inContentLanguage()->text();
353 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
356 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName && $this->editor
->getRealName() !== ''
357 ?
$this->editor
->getRealName() : $this->editor
->getName();
358 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $this->editor
->getName() );
359 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
362 $keys['$PAGEEDITOR_WIKI'] = $this->editor
->getUserPage()->getCanonicalURL();
363 $keys['$HELPPAGE'] = wfExpandUrl(
364 Skin
::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
367 # Replace this after transforming the message, T37019
368 $postTransformKeys['$PAGESUMMARY'] = $this->summary
== '' ?
' - ' : $this->summary
;
370 // Now build message's subject and body
373 // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
374 // enotif_subject_restored, enotif_subject_changed
375 $this->subject
= wfMessage( 'enotif_subject_' . $this->pageStatus
)->inContentLanguage()
376 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
379 // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
380 // enotif_body_intro_restored, enotif_body_intro_changed
381 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus
)
382 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
385 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
386 $body = strtr( $body, $keys );
387 $body = MessageCache
::singleton()->transform( $body, false, null, $this->title
);
388 $this->body
= wordwrap( strtr( $body, $postTransformKeys ), 72 );
390 # Reveal the page editor's address as REPLY-TO address only if
391 # the user has not opted-out and the option is enabled at the
392 # global configuration level.
393 $adminAddress = new MailAddress( $wgPasswordSender,
394 wfMessage( 'emailsender' )->inContentLanguage()->text() );
395 if ( $wgEnotifRevealEditorAddress
396 && ( $this->editor
->getEmail() != '' )
397 && $this->editor
->getOption( 'enotifrevealaddr' )
399 $editorAddress = MailAddress
::newFromUser( $this->editor
);
400 if ( $wgEnotifFromEditor ) {
401 $this->from
= $editorAddress;
403 $this->from
= $adminAddress;
404 $this->replyto
= $editorAddress;
407 $this->from
= $adminAddress;
408 $this->replyto
= new MailAddress( $wgNoReplyAddress );
413 * Compose a mail to a given user and either queue it for sending, or send it now,
414 * depending on settings.
416 * Call sendMails() to send any mails that were queued.
418 * @param string $source
420 function compose( $user, $source ) {
421 global $wgEnotifImpersonal;
423 if ( !$this->composed_common
) {
424 $this->composeCommonMailtext();
427 if ( $wgEnotifImpersonal ) {
428 $this->mailTargets
[] = MailAddress
::newFromUser( $user );
430 $this->sendPersonalised( $user, $source );
435 * Send any queued mails
437 function sendMails() {
438 global $wgEnotifImpersonal;
439 if ( $wgEnotifImpersonal ) {
440 $this->sendImpersonal( $this->mailTargets
);
445 * Does the per-user customizations to a notification e-mail (name,
446 * timestamp in proper timezone, etc) and sends it out.
447 * Returns true if the mail was sent successfully.
449 * @param User $watchingUser
450 * @param string $source
454 function sendPersonalised( $watchingUser, $source ) {
455 global $wgContLang, $wgEnotifUseRealName;
456 // From the PHP manual:
457 // Note: The to parameter cannot be an address in the form of
458 // "Something <someone@example.com>". The mail command will not parse
459 // this properly while talking with the MTA.
460 $to = MailAddress
::newFromUser( $watchingUser );
462 # $PAGEEDITDATE is the time and date of the page change
463 # expressed in terms of individual local time of the notification
464 # recipient, i.e. watching user
466 [ '$WATCHINGUSERNAME',
469 [ $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
470 ?
$watchingUser->getRealName() : $watchingUser->getName(),
471 $wgContLang->userDate( $this->timestamp
, $watchingUser ),
472 $wgContLang->userTime( $this->timestamp
, $watchingUser ) ],
476 if ( $source === self
::WATCHLIST
) {
477 $headers['List-Help'] = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Watchlist';
480 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, [
481 'replyTo' => $this->replyto
,
482 'headers' => $headers,
487 * Same as sendPersonalised but does impersonal mail suitable for bulk
488 * mailing. Takes an array of MailAddress objects.
489 * @param MailAddress[] $addresses
490 * @return Status|null
492 function sendImpersonal( $addresses ) {
495 if ( empty( $addresses ) ) {
500 [ '$WATCHINGUSERNAME',
503 [ wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
504 $wgContLang->date( $this->timestamp
, false, false ),
505 $wgContLang->time( $this->timestamp
, false, false ) ],
508 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, [
509 'replyTo' => $this->replyto
,