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
;
29 * This module processes the email notifications when the current page is
30 * changed. It looks up the table watchlist to find out which users are watching
33 * The current implementation sends independent emails to each watching user for
34 * the following reason:
36 * - Each watching user will be notified about the page edit time expressed in
37 * his/her local time (UTC is shown additionally). To achieve this, we need to
38 * find the individual timeoffset of each watching user from the preferences..
40 * Suggested improvement to slack down the number of sent emails: We could think
41 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
42 * same timeoffset in their preferences.
44 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
46 class EmailNotification
{
49 * Notification is due to user's user talk being edited
51 const USER_TALK
= 'user_talk';
53 * Notification is due to a watchlisted page being edited
55 const WATCHLIST
= 'watchlist';
57 * Notification because user is notified for all changes
59 const ALL_CHANGES
= 'all_changes';
61 protected $subject, $body, $replyto, $from;
62 protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
63 protected $mailTargets = [];
76 * @deprecated since 1.27 use WatchedItemStore::updateNotificationTimestamp directly
78 * @param User $editor The editor that triggered the update. Their notification
79 * timestamp will not be updated(they have already seen it)
80 * @param LinkTarget $linkTarget The link target of the title to update timestamps for
81 * @param string $timestamp Set the update timestamp to this value
83 * @return int[] Array of user IDs
85 public static function updateWatchlistTimestamp(
87 LinkTarget
$linkTarget,
90 // wfDeprecated( __METHOD__, '1.27' );
91 $config = RequestContext
::getMain()->getConfig();
92 if ( !$config->get( 'EnotifWatchlist' ) && !$config->get( 'ShowUpdatedMarker' ) ) {
95 return WatchedItemStore
::getDefaultInstance()->updateNotificationTimestamp(
103 * Send emails corresponding to the user $editor editing the page $title.
105 * May be deferred via the job queue.
107 * @param User $editor
108 * @param Title $title
109 * @param string $timestamp
110 * @param string $summary
111 * @param bool $minorEdit
112 * @param bool $oldid (default: false)
113 * @param string $pageStatus (default: 'changed')
115 public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
116 $minorEdit, $oldid = false, $pageStatus = 'changed'
118 global $wgEnotifMinorEdits, $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
120 if ( $title->getNamespace() < 0 ) {
124 // update wl_notificationtimestamp for watchers
125 $config = RequestContext
::getMain()->getConfig();
127 if ( $config->get( 'EnotifWatchlist' ) ||
$config->get( 'ShowUpdatedMarker' ) ) {
128 $watchers = WatchedItemStore
::getDefaultInstance()->updateNotificationTimestamp(
136 // $watchers deals with $wgEnotifWatchlist.
137 // If nobody is watching the page, and there are no users notified on all changes
138 // don't bother creating a job/trying to send emails, unless it's a
139 // talk page with an applicable notification.
140 if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
142 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
143 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
144 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
145 if ( $wgEnotifUserTalk
147 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
155 JobQueueGroup
::singleton()->lazyPush( new EnotifNotifyJob(
158 'editor' => $editor->getName(),
159 'editorID' => $editor->getId(),
160 'timestamp' => $timestamp,
161 'summary' => $summary,
162 'minorEdit' => $minorEdit,
164 'watchers' => $watchers,
165 'pageStatus' => $pageStatus
172 * Immediate version of notifyOnPageChange().
174 * Send emails corresponding to the user $editor editing the page $title.
176 * @note Do not call directly. Use notifyOnPageChange so that wl_notificationtimestamp is updated.
177 * @param User $editor
178 * @param Title $title
179 * @param string $timestamp Edit timestamp
180 * @param string $summary Edit summary
181 * @param bool $minorEdit
182 * @param int $oldid Revision ID
183 * @param array $watchers Array of user IDs
184 * @param string $pageStatus
185 * @throws MWException
187 public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
188 $oldid, $watchers, $pageStatus = 'changed' ) {
189 # we use $wgPasswordSender as sender's address
190 global $wgUsersNotifiedOnAllChanges;
191 global $wgEnotifWatchlist, $wgBlockDisablesLogin;
192 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
194 # The following code is only run, if several conditions are met:
195 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
196 # 2. minor edits (changes) are only regarded if the global flag indicates so
198 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
200 $this->title
= $title;
201 $this->timestamp
= $timestamp;
202 $this->summary
= $summary;
203 $this->minorEdit
= $minorEdit;
204 $this->oldid
= $oldid;
205 $this->editor
= $editor;
206 $this->composed_common
= false;
207 $this->pageStatus
= $pageStatus;
209 $formattedPageStatus = [ 'deleted', 'created', 'moved', 'restored', 'changed' ];
211 Hooks
::run( 'UpdateUserMailerFormattedPageStatus', [ &$formattedPageStatus ] );
212 if ( !in_array( $this->pageStatus
, $formattedPageStatus ) ) {
213 throw new MWException( 'Not a valid page status!' );
218 if ( !$minorEdit ||
( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
219 if ( $wgEnotifUserTalk
221 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
223 $targetUser = User
::newFromName( $title->getText() );
224 $this->compose( $targetUser, self
::USER_TALK
);
225 $userTalkId = $targetUser->getId();
228 if ( $wgEnotifWatchlist ) {
229 // Send updates to watchers other than the current editor
230 // and don't send to watchers who are blocked and cannot login
231 $userArray = UserArray
::newFromIDs( $watchers );
232 foreach ( $userArray as $watchingUser ) {
233 if ( $watchingUser->getOption( 'enotifwatchlistpages' )
234 && ( !$minorEdit ||
$watchingUser->getOption( 'enotifminoredits' ) )
235 && $watchingUser->isEmailConfirmed()
236 && $watchingUser->getId() != $userTalkId
237 && !in_array( $watchingUser->getName(), $wgUsersNotifiedOnAllChanges )
238 && !( $wgBlockDisablesLogin && $watchingUser->isBlocked() )
240 if ( Hooks
::run( 'SendWatchlistEmailNotification', [ $watchingUser, $title, $this ] ) ) {
241 $this->compose( $watchingUser, self
::WATCHLIST
);
248 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
249 if ( $editor->getName() == $name ) {
250 // No point notifying the user that actually made the change!
253 $user = User
::newFromName( $name );
254 $this->compose( $user, self
::ALL_CHANGES
);
261 * @param User $editor
262 * @param Title $title
263 * @param bool $minorEdit
266 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
267 global $wgEnotifUserTalk, $wgBlockDisablesLogin;
268 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK
);
270 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
271 $targetUser = User
::newFromName( $title->getText() );
273 if ( !$targetUser ||
$targetUser->isAnon() ) {
274 wfDebug( __METHOD__
. ": user talk page edited, but user does not exist\n" );
275 } elseif ( $targetUser->getId() == $editor->getId() ) {
276 wfDebug( __METHOD__
. ": user edited their own talk page, no notification sent\n" );
277 } elseif ( $wgBlockDisablesLogin && $targetUser->isBlocked() ) {
278 wfDebug( __METHOD__
. ": talk page owner is blocked and cannot login, no notification sent\n" );
279 } elseif ( $targetUser->getOption( 'enotifusertalkpages' )
280 && ( !$minorEdit ||
$targetUser->getOption( 'enotifminoredits' ) )
282 if ( !$targetUser->isEmailConfirmed() ) {
283 wfDebug( __METHOD__
. ": talk page owner doesn't have validated email\n" );
284 } elseif ( !Hooks
::run( 'AbortTalkPageEmailNotification', [ $targetUser, $title ] ) ) {
285 wfDebug( __METHOD__
. ": talk page update notification is aborted for this user\n" );
287 wfDebug( __METHOD__
. ": sending talk page update notification\n" );
291 wfDebug( __METHOD__
. ": talk page owner doesn't want notifications\n" );
298 * Generate the generic "this page has been changed" e-mail text.
300 private function composeCommonMailtext() {
301 global $wgPasswordSender, $wgNoReplyAddress;
302 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
303 global $wgEnotifImpersonal, $wgEnotifUseRealName;
305 $this->composed_common
= true;
307 # You as the WikiAdmin and Sysops can make use of plenty of
308 # named variables when composing your notification emails while
309 # simply editing the Meta pages
312 $postTransformKeys = [];
313 $pageTitleUrl = $this->title
->getCanonicalURL();
314 $pageTitle = $this->title
->getPrefixedText();
316 if ( $this->oldid
) {
317 // Always show a link to the diff which triggered the mail. See bug 32210.
318 $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
319 $this->title
->getCanonicalURL( [ 'diff' => 'next', 'oldid' => $this->oldid
] ) )
320 ->inContentLanguage()->text();
322 if ( !$wgEnotifImpersonal ) {
323 // For personal mail, also show a link to the diff of all changes
324 // since last visited.
325 $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
326 $this->title
->getCanonicalURL( [ 'diff' => '0', 'oldid' => $this->oldid
] ) )
327 ->inContentLanguage()->text();
329 $keys['$OLDID'] = $this->oldid
;
330 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
331 $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
333 # clear $OLDID placeholder in the message template
334 $keys['$OLDID'] = '';
335 $keys['$NEWPAGE'] = '';
336 // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
337 $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
340 $keys['$PAGETITLE'] = $this->title
->getPrefixedText();
341 $keys['$PAGETITLE_URL'] = $this->title
->getCanonicalURL();
342 $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
343 wfMessage( 'minoredit' )->inContentLanguage()->text() : '';
344 $keys['$UNWATCHURL'] = $this->title
->getCanonicalURL( 'action=unwatch' );
346 if ( $this->editor
->isAnon() ) {
347 # real anon (user:xxx.xxx.xxx.xxx)
348 $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor
->getName() )
349 ->inContentLanguage()->text();
350 $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
353 $keys['$PAGEEDITOR'] = $wgEnotifUseRealName && $this->editor
->getRealName() !== ''
354 ?
$this->editor
->getRealName() : $this->editor
->getName();
355 $emailPage = SpecialPage
::getSafeTitleFor( 'Emailuser', $this->editor
->getName() );
356 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
359 $keys['$PAGEEDITOR_WIKI'] = $this->editor
->getUserPage()->getCanonicalURL();
360 $keys['$HELPPAGE'] = wfExpandUrl(
361 Skin
::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
364 # Replace this after transforming the message, bug 35019
365 $postTransformKeys['$PAGESUMMARY'] = $this->summary
== '' ?
' - ' : $this->summary
;
367 // Now build message's subject and body
370 // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
371 // enotif_subject_restored, enotif_subject_changed
372 $this->subject
= wfMessage( 'enotif_subject_' . $this->pageStatus
)->inContentLanguage()
373 ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
376 // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
377 // enotif_body_intro_restored, enotif_body_intro_changed
378 $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus
)
379 ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
382 $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
383 $body = strtr( $body, $keys );
384 $body = MessageCache
::singleton()->transform( $body, false, null, $this->title
);
385 $this->body
= wordwrap( strtr( $body, $postTransformKeys ), 72 );
387 # Reveal the page editor's address as REPLY-TO address only if
388 # the user has not opted-out and the option is enabled at the
389 # global configuration level.
390 $adminAddress = new MailAddress( $wgPasswordSender,
391 wfMessage( 'emailsender' )->inContentLanguage()->text() );
392 if ( $wgEnotifRevealEditorAddress
393 && ( $this->editor
->getEmail() != '' )
394 && $this->editor
->getOption( 'enotifrevealaddr' )
396 $editorAddress = MailAddress
::newFromUser( $this->editor
);
397 if ( $wgEnotifFromEditor ) {
398 $this->from
= $editorAddress;
400 $this->from
= $adminAddress;
401 $this->replyto
= $editorAddress;
404 $this->from
= $adminAddress;
405 $this->replyto
= new MailAddress( $wgNoReplyAddress );
410 * Compose a mail to a given user and either queue it for sending, or send it now,
411 * depending on settings.
413 * Call sendMails() to send any mails that were queued.
415 * @param string $source
417 function compose( $user, $source ) {
418 global $wgEnotifImpersonal;
420 if ( !$this->composed_common
) {
421 $this->composeCommonMailtext();
424 if ( $wgEnotifImpersonal ) {
425 $this->mailTargets
[] = MailAddress
::newFromUser( $user );
427 $this->sendPersonalised( $user, $source );
432 * Send any queued mails
434 function sendMails() {
435 global $wgEnotifImpersonal;
436 if ( $wgEnotifImpersonal ) {
437 $this->sendImpersonal( $this->mailTargets
);
442 * Does the per-user customizations to a notification e-mail (name,
443 * timestamp in proper timezone, etc) and sends it out.
444 * Returns true if the mail was sent successfully.
446 * @param User $watchingUser
447 * @param string $source
451 function sendPersonalised( $watchingUser, $source ) {
452 global $wgContLang, $wgEnotifUseRealName;
453 // From the PHP manual:
454 // Note: The to parameter cannot be an address in the form of
455 // "Something <someone@example.com>". The mail command will not parse
456 // this properly while talking with the MTA.
457 $to = MailAddress
::newFromUser( $watchingUser );
459 # $PAGEEDITDATE is the time and date of the page change
460 # expressed in terms of individual local time of the notification
461 # recipient, i.e. watching user
463 [ '$WATCHINGUSERNAME',
466 [ $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
467 ?
$watchingUser->getRealName() : $watchingUser->getName(),
468 $wgContLang->userDate( $this->timestamp
, $watchingUser ),
469 $wgContLang->userTime( $this->timestamp
, $watchingUser ) ],
473 if ( $source === self
::WATCHLIST
) {
474 $headers['List-Help'] = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Watchlist';
477 return UserMailer
::send( $to, $this->from
, $this->subject
, $body, [
478 'replyTo' => $this->replyto
,
479 'headers' => $headers,
484 * Same as sendPersonalised but does impersonal mail suitable for bulk
485 * mailing. Takes an array of MailAddress objects.
486 * @param MailAddress[] $addresses
487 * @return Status|null
489 function sendImpersonal( $addresses ) {
492 if ( empty( $addresses ) ) {
497 [ '$WATCHINGUSERNAME',
500 [ wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
501 $wgContLang->date( $this->timestamp
, false, false ),
502 $wgContLang->time( $this->timestamp
, false, false ) ],
505 return UserMailer
::send( $addresses, $this->from
, $this->subject
, $body, [
506 'replyTo' => $this->replyto
,