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 && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
133 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
134 if ( $wgEnotifUserTalk
136 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
144 JobQueueGroup
::singleton()->lazyPush( new EnotifNotifyJob(
147 'editor' => $editor->getName(),
148 'editorID' => $editor->getId(),
149 'timestamp' => $timestamp,
150 'summary' => $summary,
151 'minorEdit' => $minorEdit,
153 'watchers' => $watchers,
154 'pageStatus' => $pageStatus
161 * Immediate version of notifyOnPageChange().
163 * Send emails corresponding to the user $editor editing the page $title.
165 * @note Do not call directly. Use notifyOnPageChange so that wl_notificationtimestamp is updated.
166 * @param User $editor
167 * @param Title $title
168 * @param string $timestamp Edit timestamp
169 * @param string $summary Edit summary
170 * @param bool $minorEdit
171 * @param int $oldid Revision ID
172 * @param array $watchers Array of user IDs
173 * @param string $pageStatus
174 * @throws MWException
176 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
177 $oldid, $watchers, $pageStatus = 'changed' ) {
178 # we use $wgPasswordSender as sender's address
179 global $wgUsersNotifiedOnAllChanges;
180 global $wgEnotifWatchlist, $wgBlockDisablesLogin;
181 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
183 # The following code is only run, if several conditions are met:
184 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
185 # 2. minor edits (changes) are only regarded if the global flag indicates so
187 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
189 $this->title
= $title;
190 $this->timestamp
= $timestamp;
191 $this->summary
= $summary;
192 $this->minorEdit
= $minorEdit;
193 $this->oldid
= $oldid;
194 $this->editor
= $editor;
195 $this->composed_common
= false;
196 $this->pageStatus
= $pageStatus;
198 $formattedPageStatus = [ 'deleted', 'created', 'moved', 'restored', 'changed' ];
200 Hooks
::run( 'UpdateUserMailerFormattedPageStatus', [ &$formattedPageStatus ] );
201 if ( !in_array( $this->pageStatus
, $formattedPageStatus ) ) {
202 throw new MWException( 'Not a valid page status!' );
207 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
208 if ( $wgEnotifUserTalk
210 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
212 $targetUser = User
::newFromName( $title->getText() );
213 $this->compose( $targetUser, self
::USER_TALK
);
214 $userTalkId = $targetUser->getId();
217 if ( $wgEnotifWatchlist ) {
218 // Send updates to watchers other than the current editor
219 // and don't send to watchers who are blocked and cannot login
220 $userArray = UserArray
::newFromIDs( $watchers );
221 foreach ( $userArray as $watchingUser ) {
222 if ( $watchingUser->getOption( 'enotifwatchlistpages' )
223 && ( !$minorEdit ||
$watchingUser->getOption( 'enotifminoredits' ) )
224 && $watchingUser->isEmailConfirmed()
225 && $watchingUser->getId() != $userTalkId
226 && !in_array( $watchingUser->getName(), $wgUsersNotifiedOnAllChanges )
227 && !( $wgBlockDisablesLogin && $watchingUser->isBlocked() )
229 if ( Hooks
::run( 'SendWatchlistEmailNotification', [ $watchingUser, $title, $this ] ) ) {
230 $this->compose( $watchingUser, self
::WATCHLIST
);
237 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
238 if ( $editor->getName() == $name ) {
239 // No point notifying the user that actually made the change!
242 $user = User
::newFromName( $name );
243 $this->compose( $user, self
::ALL_CHANGES
);
250 * @param User $editor
251 * @param Title $title
252 * @param bool $minorEdit
255 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
256 global $wgEnotifUserTalk, $wgBlockDisablesLogin;
257 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
259 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
260 $targetUser = User
::newFromName( $title->getText() );
262 if ( !$targetUser ||
$targetUser->isAnon() ) {
263 wfDebug( __METHOD__
. ": user talk page edited, but user does not exist\n" );
264 } elseif ( $targetUser->getId() == $editor->getId() ) {
265 wfDebug( __METHOD__
. ": user edited their own talk page, no notification sent\n" );
266 } elseif ( $wgBlockDisablesLogin && $targetUser->isBlocked() ) {
267 wfDebug( __METHOD__
. ": talk page owner is blocked and cannot login, no notification sent\n" );
268 } elseif ( $targetUser->getOption( 'enotifusertalkpages' )
269 && ( !$minorEdit ||
$targetUser->getOption( 'enotifminoredits' ) )
271 if ( !$targetUser->isEmailConfirmed() ) {
272 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
273 } elseif ( !Hooks
::run( 'AbortTalkPageEmailNotification', [ $targetUser, $title ] ) ) {
274 wfDebug( __METHOD__
. ": talk page update notification is aborted for this user\n" );
276 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
280 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
287 * Generate the generic "this page has been changed" e-mail text.
289 private function composeCommonMailtext() {
290 global $wgPasswordSender, $wgNoReplyAddress;
291 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
292 global $wgEnotifImpersonal, $wgEnotifUseRealName;
294 $this->composed_common
= true;
296 # You as the WikiAdmin and Sysops can make use of plenty of
297 # named variables when composing your notification emails while
298 # simply editing the Meta pages
301 $postTransformKeys = [];
302 $pageTitleUrl = $this->title
->getCanonicalURL();
303 $pageTitle = $this->title
->getPrefixedText();
305 if ( $this->oldid
) {
306 // Always show a link to the diff which triggered the mail. See T34210.
307 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
308 $this->title
->getCanonicalURL( [ 'diff' => 'next', 'oldid' => $this->oldid
] ) )
309 ->inContentLanguage()->text();
311 if ( !$wgEnotifImpersonal ) {
312 // For personal mail, also show a link to the diff of all changes
313 // since last visited.
314 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
315 $this->title
->getCanonicalURL( [ 'diff' => '0', 'oldid' => $this->oldid
] ) )
316 ->inContentLanguage()->text();
318 $keys['$OLDID'] = $this->oldid
;
319 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
320 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
322 # clear $OLDID placeholder in the message template
323 $keys['$OLDID'] = '';
324 $keys['$NEWPAGE'] = '';
325 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
326 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
329 $keys['$PAGETITLE'] = $this->title
->getPrefixedText();
330 $keys['$PAGETITLE_URL'] = $this->title
->getCanonicalURL();
331 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
332 "\n\n" . wfMessage( 'enotif_minoredit' )->inContentLanguage()->text() :
334 $keys['$UNWATCHURL'] = $this->title
->getCanonicalURL( 'action=unwatch' );
336 if ( $this->editor
->isAnon() ) {
337 # real anon (user:xxx.xxx.xxx.xxx)
338 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor
->getName() )
339 ->inContentLanguage()->text();
340 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
343 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName && $this->editor
->getRealName() !== ''
344 ?
$this->editor
->getRealName() : $this->editor
->getName();
345 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $this->editor
->getName() );
346 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
349 $keys['$PAGEEDITOR_WIKI'] = $this->editor
->getUserPage()->getCanonicalURL();
350 $keys['$HELPPAGE'] = wfExpandUrl(
351 Skin
::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
354 # Replace this after transforming the message, T37019
355 $postTransformKeys['$PAGESUMMARY'] = $this->summary
== '' ?
' - ' : $this->summary
;
357 // Now build message's subject and body
360 // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
361 // enotif_subject_restored, enotif_subject_changed
362 $this->subject
= wfMessage( 'enotif_subject_' . $this->pageStatus
)->inContentLanguage()
363 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
366 // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
367 // enotif_body_intro_restored, enotif_body_intro_changed
368 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus
)
369 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
372 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
373 $body = strtr( $body, $keys );
374 $body = MessageCache
::singleton()->transform( $body, false, null, $this->title
);
375 $this->body
= wordwrap( strtr( $body, $postTransformKeys ), 72 );
377 # Reveal the page editor's address as REPLY-TO address only if
378 # the user has not opted-out and the option is enabled at the
379 # global configuration level.
380 $adminAddress = new MailAddress( $wgPasswordSender,
381 wfMessage( 'emailsender' )->inContentLanguage()->text() );
382 if ( $wgEnotifRevealEditorAddress
383 && ( $this->editor
->getEmail() != '' )
384 && $this->editor
->getOption( 'enotifrevealaddr' )
386 $editorAddress = MailAddress
::newFromUser( $this->editor
);
387 if ( $wgEnotifFromEditor ) {
388 $this->from
= $editorAddress;
390 $this->from
= $adminAddress;
391 $this->replyto
= $editorAddress;
394 $this->from
= $adminAddress;
395 $this->replyto
= new MailAddress( $wgNoReplyAddress );
400 * Compose a mail to a given user and either queue it for sending, or send it now,
401 * depending on settings.
403 * Call sendMails() to send any mails that were queued.
405 * @param string $source
407 function compose( $user, $source ) {
408 global $wgEnotifImpersonal;
410 if ( !$this->composed_common
) {
411 $this->composeCommonMailtext();
414 if ( $wgEnotifImpersonal ) {
415 $this->mailTargets
[] = MailAddress
::newFromUser( $user );
417 $this->sendPersonalised( $user, $source );
422 * Send any queued mails
424 function sendMails() {
425 global $wgEnotifImpersonal;
426 if ( $wgEnotifImpersonal ) {
427 $this->sendImpersonal( $this->mailTargets
);
432 * Does the per-user customizations to a notification e-mail (name,
433 * timestamp in proper timezone, etc) and sends it out.
434 * Returns Status if email was sent successfully or not (Status::newGood()
435 * or Status::newFatal() respectively).
437 * @param User $watchingUser
438 * @param string $source
442 function sendPersonalised( $watchingUser, $source ) {
443 global $wgEnotifUseRealName;
444 // From the PHP manual:
445 // Note: The to parameter cannot be an address in the form of
446 // "Something <someone@example.com>". The mail command will not parse
447 // this properly while talking with the MTA.
448 $to = MailAddress
::newFromUser( $watchingUser );
450 # $PAGEEDITDATE is the time and date of the page change
451 # expressed in terms of individual local time of the notification
452 # recipient, i.e. watching user
453 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
455 [ '$WATCHINGUSERNAME',
458 [ $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
459 ?
$watchingUser->getRealName() : $watchingUser->getName(),
460 $contLang->userDate( $this->timestamp
, $watchingUser ),
461 $contLang->userTime( $this->timestamp
, $watchingUser ) ],
465 if ( $source === self
::WATCHLIST
) {
466 $headers['List-Help'] = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Watchlist';
469 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, [
470 'replyTo' => $this->replyto
,
471 'headers' => $headers,
476 * Same as sendPersonalised but does impersonal mail suitable for bulk
477 * mailing. Takes an array of MailAddress objects.
478 * @param MailAddress[] $addresses
479 * @return Status|null
481 function sendImpersonal( $addresses ) {
482 if ( empty( $addresses ) ) {
486 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
488 [ '$WATCHINGUSERNAME',
491 [ wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
492 $contLang->date( $this->timestamp
, false, false ),
493 $contLang->time( $this->timestamp
, false, false ) ],
496 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, [
497 'replyTo' => $this->replyto
,