MediaWiki REL1_31
EmailNotification.php
Go to the documentation of this file.
1<?php
27
29
50
54 const USER_TALK = 'user_talk';
58 const WATCHLIST = 'watchlist';
62 const ALL_CHANGES = 'all_changes';
63
66 protected $mailTargets = [];
67
71 protected $title;
72
76 protected $editor;
77
88 public static function updateWatchlistTimestamp(
90 LinkTarget $linkTarget,
92 ) {
93 wfDeprecated( __METHOD__, '1.27' );
94 $config = RequestContext::getMain()->getConfig();
95 if ( !$config->get( 'EnotifWatchlist' ) && !$config->get( 'ShowUpdatedMarker' ) ) {
96 return [];
97 }
98 return MediaWikiServices::getInstance()->getWatchedItemStore()->updateNotificationTimestamp(
99 $editor,
100 $linkTarget,
102 );
103 }
104
118 public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
119 $minorEdit, $oldid = false, $pageStatus = 'changed'
120 ) {
122
123 if ( $title->getNamespace() < 0 ) {
124 return;
125 }
126
127 // update wl_notificationtimestamp for watchers
128 $config = RequestContext::getMain()->getConfig();
129 $watchers = [];
130 if ( $config->get( 'EnotifWatchlist' ) || $config->get( 'ShowUpdatedMarker' ) ) {
131 $watchers = MediaWikiServices::getInstance()->getWatchedItemStore()->updateNotificationTimestamp(
132 $editor,
133 $title,
135 );
136 }
137
138 $sendEmail = true;
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 ) ) {
144 $sendEmail = false;
145 // Only send notification for non minor edits, unless $wgEnotifMinorEdits
146 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
147 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
149 && $isUserTalkPage
150 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
151 ) {
152 $sendEmail = true;
153 }
154 }
155 }
156
157 if ( $sendEmail ) {
159 $title,
160 [
161 'editor' => $editor->getName(),
162 'editorID' => $editor->getId(),
163 'timestamp' => $timestamp,
164 'summary' => $summary,
165 'minorEdit' => $minorEdit,
166 'oldid' => $oldid,
167 'watchers' => $watchers,
168 'pageStatus' => $pageStatus
169 ]
170 ) );
171 }
172 }
173
191 $oldid, $watchers, $pageStatus = 'changed' ) {
192 # we use $wgPasswordSender as sender's address
196
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
200
201 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
202
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;
211
212 $formattedPageStatus = [ 'deleted', 'created', 'moved', 'restored', 'changed' ];
213
214 Hooks::run( 'UpdateUserMailerFormattedPageStatus', [ &$formattedPageStatus ] );
215 if ( !in_array( $this->pageStatus, $formattedPageStatus ) ) {
216 throw new MWException( 'Not a valid page status!' );
217 }
218
219 $userTalkId = false;
220
221 if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
223 && $isUserTalkPage
224 && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
225 ) {
226 $targetUser = User::newFromName( $title->getText() );
227 $this->compose( $targetUser, self::USER_TALK );
228 $userTalkId = $targetUser->getId();
229 }
230
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() )
242 ) {
243 if ( Hooks::run( 'SendWatchlistEmailNotification', [ $watchingUser, $title, $this ] ) ) {
244 $this->compose( $watchingUser, self::WATCHLIST );
245 }
246 }
247 }
248 }
249 }
250
251 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
252 if ( $editor->getName() == $name ) {
253 // No point notifying the user that actually made the change!
254 continue;
255 }
256 $user = User::newFromName( $name );
257 $this->compose( $user, self::ALL_CHANGES );
258 }
259
260 $this->sendMails();
261 }
262
269 private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
271 $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
272
273 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
274 $targetUser = User::newFromName( $title->getText() );
275
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' ) )
284 ) {
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" );
289 } else {
290 wfDebug( __METHOD__ . ": sending talk page update notification\n" );
291 return true;
292 }
293 } else {
294 wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
295 }
296 }
297 return false;
298 }
299
303 private function composeCommonMailtext() {
307
308 $this->composed_common = true;
309
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
313
314 $keys = [];
315 $postTransformKeys = [];
316 $pageTitleUrl = $this->title->getCanonicalURL();
317 $pageTitle = $this->title->getPrefixedText();
318
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();
324
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();
331 }
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();
335 } else {
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();
341 }
342
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' );
348
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();
354
355 } else {
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();
360 }
361
362 $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalURL();
363 $keys['$HELPPAGE'] = wfExpandUrl(
364 Skin::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
365 );
366
367 # Replace this after transforming the message, T37019
368 $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
369
370 // Now build message's subject and body
371
372 // Messages:
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();
377
378 // Messages:
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 )
383 ->text();
384
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 );
389
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() );
396 && ( $this->editor->getEmail() != '' )
397 && $this->editor->getOption( 'enotifrevealaddr' )
398 ) {
399 $editorAddress = MailAddress::newFromUser( $this->editor );
400 if ( $wgEnotifFromEditor ) {
401 $this->from = $editorAddress;
402 } else {
403 $this->from = $adminAddress;
404 $this->replyto = $editorAddress;
405 }
406 } else {
407 $this->from = $adminAddress;
408 $this->replyto = new MailAddress( $wgNoReplyAddress );
409 }
410 }
411
420 function compose( $user, $source ) {
421 global $wgEnotifImpersonal;
422
423 if ( !$this->composed_common ) {
424 $this->composeCommonMailtext();
425 }
426
427 if ( $wgEnotifImpersonal ) {
428 $this->mailTargets[] = MailAddress::newFromUser( $user );
429 } else {
430 $this->sendPersonalised( $user, $source );
431 }
432 }
433
437 function sendMails() {
438 global $wgEnotifImpersonal;
439 if ( $wgEnotifImpersonal ) {
440 $this->sendImpersonal( $this->mailTargets );
441 }
442 }
443
454 function sendPersonalised( $watchingUser, $source ) {
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 );
461
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
465 $body = str_replace(
466 [ '$WATCHINGUSERNAME',
467 '$PAGEEDITDATE',
468 '$PAGEEDITTIME' ],
469 [ $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
470 ? $watchingUser->getRealName() : $watchingUser->getName(),
471 $wgContLang->userDate( $this->timestamp, $watchingUser ),
472 $wgContLang->userTime( $this->timestamp, $watchingUser ) ],
473 $this->body );
474
475 $headers = [];
476 if ( $source === self::WATCHLIST ) {
477 $headers['List-Help'] = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Watchlist';
478 }
479
480 return UserMailer::send( $to, $this->from, $this->subject, $body, [
481 'replyTo' => $this->replyto,
482 'headers' => $headers,
483 ] );
484 }
485
492 function sendImpersonal( $addresses ) {
493 global $wgContLang;
494
495 if ( empty( $addresses ) ) {
496 return null;
497 }
498
499 $body = str_replace(
500 [ '$WATCHINGUSERNAME',
501 '$PAGEEDITDATE',
502 '$PAGEEDITTIME' ],
503 [ wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
504 $wgContLang->date( $this->timestamp, false, false ),
505 $wgContLang->time( $this->timestamp, false, false ) ],
506 $this->body );
507
508 return UserMailer::send( $addresses, $this->from, $this->subject, $body, [
509 'replyTo' => $this->replyto,
510 ] );
511 }
512
513}
$wgEnotifWatchlist
Allow users to enable email notification ("enotif") on watchlist changes.
$wgEnotifUserTalk
Allow users to enable email notification ("enotif") when someone edits their user talk page.
$wgNoReplyAddress
Reply-To address for e-mail notifications.
$wgEnotifFromEditor
True: from page editor if s/he opted-in.
$wgEnotifRevealEditorAddress
Set the Reply-to address in notifications to the editor's address, if user allowed this in the prefer...
$wgEnotifImpersonal
Send a generic mail instead of a personalised mail for each user.
$wgUsersNotifiedOnAllChanges
Array of usernames who will be sent a notification email for every change which occurs on a wiki.
$wgBlockDisablesLogin
If true, blocked users will not be allowed to login.
$wgEnotifMinorEdits
Potentially send notification mails on minor edits to pages.
$wgPasswordSender
Sender email address for e-mail notifications.
$wgEnotifUseRealName
Use real name instead of username in e-mail "from" field.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
This module processes the email notifications when the current page is changed.
sendImpersonal( $addresses)
Same as sendPersonalised but does impersonal mail suitable for bulk mailing.
canSendUserTalkEmail( $editor, $title, $minorEdit)
const ALL_CHANGES
Notification because user is notified for all changes.
sendMails()
Send any queued mails.
notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid=false, $pageStatus='changed')
Send emails corresponding to the user $editor editing the page $title.
sendPersonalised( $watchingUser, $source)
Does the per-user customizations to a notification e-mail (name, timestamp in proper timezone,...
compose( $user, $source)
Compose a mail to a given user and either queue it for sending, or send it now, depending on settings...
const WATCHLIST
Notification is due to a watchlisted page being edited.
actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers, $pageStatus='changed')
Immediate version of notifyOnPageChange().
const USER_TALK
Notification is due to user's user talk being edited.
static updateWatchlistTimestamp(User $editor, LinkTarget $linkTarget, $timestamp)
composeCommonMailtext()
Generate the generic "this page has been changed" e-mail text.
Job for email notification mails.
static singleton( $domain=false)
MediaWiki exception.
Stores a single person's name and email address.
static newFromUser(User $user)
Create a new MailAddress object for the given user.
MediaWikiServices is the service locator for the application scope of MediaWiki.
static singleton()
Get the signleton instance of this class.
static getMain()
Get the RequestContext object associated with the main request.
Represents a title within MediaWiki.
Definition Title.php:39
static newFromIDs( $ids)
Definition UserArray.php:45
static send( $to, $from, $subject, $body, $options=[])
This function will perform a direct (authenticated) login to a SMTP Server to use for mail relaying i...
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:53
getName()
Get the user name, or the IP of an anonymous user.
Definition User.php:2482
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition User.php:591
isAllowed( $action='')
Internal mechanics of testing a permission.
Definition User.php:3855
getId()
Get the user's ID.
Definition User.php:2457
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition design.txt:57
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition design.txt:18
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
const NS_USER_TALK
Definition Defines.php:77
$source