MediaWiki  master
EmailNotification.php
Go to the documentation of this file.
1 <?php
28 
49 
53  const USER_TALK = 'user_talk';
57  const WATCHLIST = 'watchlist';
61  const ALL_CHANGES = 'all_changes';
62 
63  protected $subject, $body, $replyto, $from;
65  protected $mailTargets = [];
66 
70  protected $title;
71 
75  protected $editor;
76 
87  public function getPageStatus() {
88  return $this->pageStatus;
89  }
90 
104  public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
105  $minorEdit, $oldid = false, $pageStatus = 'changed'
106  ) {
108 
109  if ( $title->getNamespace() < 0 ) {
110  return;
111  }
112 
113  // update wl_notificationtimestamp for watchers
114  $config = RequestContext::getMain()->getConfig();
115  $watchers = [];
116  if ( $config->get( 'EnotifWatchlist' ) || $config->get( 'ShowUpdatedMarker' ) ) {
117  $watchers = MediaWikiServices::getInstance()->getWatchedItemStore()->updateNotificationTimestamp(
118  $editor,
119  $title,
120  $timestamp
121  );
122  }
123 
124  $sendEmail = true;
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 ) ) {
130  $sendEmail = false;
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
135  && $isUserTalkPage
136  && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
137  ) {
138  $sendEmail = true;
139  }
140  }
141  }
142 
143  if ( $sendEmail ) {
144  JobQueueGroup::singleton()->lazyPush( new EnotifNotifyJob(
145  $title,
146  [
147  'editor' => $editor->getName(),
148  'editorID' => $editor->getId(),
149  'timestamp' => $timestamp,
150  'summary' => $summary,
151  'minorEdit' => $minorEdit,
152  'oldid' => $oldid,
153  'watchers' => $watchers,
154  'pageStatus' => $pageStatus
155  ]
156  ) );
157  }
158  }
159 
176  public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
177  $oldid, $watchers, $pageStatus = 'changed' ) {
178  # we use $wgPasswordSender as sender's address
182 
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
186 
187  $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
188 
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;
197 
198  $formattedPageStatus = [ 'deleted', 'created', 'moved', 'restored', 'changed' ];
199 
200  Hooks::run( 'UpdateUserMailerFormattedPageStatus', [ &$formattedPageStatus ] );
201  if ( !in_array( $this->pageStatus, $formattedPageStatus ) ) {
202  throw new MWException( 'Not a valid page status!' );
203  }
204 
205  $userTalkId = false;
206 
207  if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
208  if ( $wgEnotifUserTalk
209  && $isUserTalkPage
210  && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
211  ) {
212  $targetUser = User::newFromName( $title->getText() );
213  $this->compose( $targetUser, self::USER_TALK );
214  $userTalkId = $targetUser->getId();
215  }
216 
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  // @TODO Partial blocks should not prevent the user from logging in.
228  // see: https://phabricator.wikimedia.org/T208895
229  && !( $wgBlockDisablesLogin && $watchingUser->getBlock() )
230  && Hooks::run( 'SendWatchlistEmailNotification', [ $watchingUser, $title, $this ] )
231  ) {
232  $this->compose( $watchingUser, self::WATCHLIST );
233  }
234  }
235  }
236  }
237 
238  foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
239  if ( $editor->getName() == $name ) {
240  // No point notifying the user that actually made the change!
241  continue;
242  }
243  $user = User::newFromName( $name );
244  $this->compose( $user, self::ALL_CHANGES );
245  }
246 
247  $this->sendMails();
248  }
249 
256  private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
258  $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
259 
260  if ( $wgEnotifUserTalk && $isUserTalkPage ) {
261  $targetUser = User::newFromName( $title->getText() );
262 
263  if ( !$targetUser || $targetUser->isAnon() ) {
264  wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
265  } elseif ( $targetUser->getId() == $editor->getId() ) {
266  wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
267  } elseif ( $wgBlockDisablesLogin && $targetUser->getBlock() ) {
268  // @TODO Partial blocks should not prevent the user from logging in.
269  // see: https://phabricator.wikimedia.org/T208895
270  wfDebug( __METHOD__ . ": talk page owner is blocked and cannot login, no notification sent\n" );
271  } elseif ( $targetUser->getOption( 'enotifusertalkpages' )
272  && ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) )
273  ) {
274  if ( !$targetUser->isEmailConfirmed() ) {
275  wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
276  } elseif ( !Hooks::run( 'AbortTalkPageEmailNotification', [ $targetUser, $title ] ) ) {
277  wfDebug( __METHOD__ . ": talk page update notification is aborted for this user\n" );
278  } else {
279  wfDebug( __METHOD__ . ": sending talk page update notification\n" );
280  return true;
281  }
282  } else {
283  wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
284  }
285  }
286  return false;
287  }
288 
292  private function composeCommonMailtext() {
296 
297  $this->composed_common = true;
298 
299  # You as the WikiAdmin and Sysops can make use of plenty of
300  # named variables when composing your notification emails while
301  # simply editing the Meta pages
302 
303  $keys = [];
304  $postTransformKeys = [];
305  $pageTitleUrl = $this->title->getCanonicalURL();
306  $pageTitle = $this->title->getPrefixedText();
307 
308  if ( $this->oldid ) {
309  // Always show a link to the diff which triggered the mail. See T34210.
310  $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
311  $this->title->getCanonicalURL( [ 'diff' => 'next', 'oldid' => $this->oldid ] ) )
312  ->inContentLanguage()->text();
313 
314  if ( !$wgEnotifImpersonal ) {
315  // For personal mail, also show a link to the diff of all changes
316  // since last visited.
317  $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
318  $this->title->getCanonicalURL( [ 'diff' => '0', 'oldid' => $this->oldid ] ) )
319  ->inContentLanguage()->text();
320  }
321  $keys['$OLDID'] = $this->oldid;
322  // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
323  $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
324  } else {
325  # clear $OLDID placeholder in the message template
326  $keys['$OLDID'] = '';
327  $keys['$NEWPAGE'] = '';
328  // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
329  $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
330  }
331 
332  $keys['$PAGETITLE'] = $this->title->getPrefixedText();
333  $keys['$PAGETITLE_URL'] = $this->title->getCanonicalURL();
334  $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
335  "\n\n" . wfMessage( 'enotif_minoredit' )->inContentLanguage()->text() :
336  '';
337  $keys['$UNWATCHURL'] = $this->title->getCanonicalURL( 'action=unwatch' );
338 
339  if ( $this->editor->isAnon() ) {
340  # real anon (user:xxx.xxx.xxx.xxx)
341  $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor->getName() )
342  ->inContentLanguage()->text();
343  $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
344 
345  } else {
346  $keys['$PAGEEDITOR'] = $wgEnotifUseRealName && $this->editor->getRealName() !== ''
347  ? $this->editor->getRealName() : $this->editor->getName();
348  $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $this->editor->getName() );
349  $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
350  }
351 
352  $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalURL();
353  $keys['$HELPPAGE'] = wfExpandUrl(
354  Skin::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
355  );
356 
357  # Replace this after transforming the message, T37019
358  $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
359 
360  // Now build message's subject and body
361 
362  // Messages:
363  // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
364  // enotif_subject_restored, enotif_subject_changed
365  $this->subject = wfMessage( 'enotif_subject_' . $this->pageStatus )->inContentLanguage()
366  ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
367 
368  // Messages:
369  // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
370  // enotif_body_intro_restored, enotif_body_intro_changed
371  $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus )
372  ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
373  ->text();
374 
375  $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
376  $body = strtr( $body, $keys );
377  $body = MessageCache::singleton()->transform( $body, false, null, $this->title );
378  $this->body = wordwrap( strtr( $body, $postTransformKeys ), 72 );
379 
380  # Reveal the page editor's address as REPLY-TO address only if
381  # the user has not opted-out and the option is enabled at the
382  # global configuration level.
383  $adminAddress = new MailAddress( $wgPasswordSender,
384  wfMessage( 'emailsender' )->inContentLanguage()->text() );
385  if ( $wgEnotifRevealEditorAddress
386  && ( $this->editor->getEmail() != '' )
387  && $this->editor->getOption( 'enotifrevealaddr' )
388  ) {
389  $editorAddress = MailAddress::newFromUser( $this->editor );
390  if ( $wgEnotifFromEditor ) {
391  $this->from = $editorAddress;
392  } else {
393  $this->from = $adminAddress;
394  $this->replyto = $editorAddress;
395  }
396  } else {
397  $this->from = $adminAddress;
398  $this->replyto = new MailAddress( $wgNoReplyAddress );
399  }
400  }
401 
410  private function compose( $user, $source ) {
411  global $wgEnotifImpersonal;
412 
413  if ( !$this->composed_common ) {
414  $this->composeCommonMailtext();
415  }
416 
417  if ( $wgEnotifImpersonal ) {
418  $this->mailTargets[] = MailAddress::newFromUser( $user );
419  } else {
420  $this->sendPersonalised( $user, $source );
421  }
422  }
423 
427  private function sendMails() {
428  global $wgEnotifImpersonal;
429  if ( $wgEnotifImpersonal ) {
430  $this->sendImpersonal( $this->mailTargets );
431  }
432  }
433 
444  private function sendPersonalised( $watchingUser, $source ) {
445  global $wgEnotifUseRealName;
446  // From the PHP manual:
447  // Note: The to parameter cannot be an address in the form of
448  // "Something <someone@example.com>". The mail command will not parse
449  // this properly while talking with the MTA.
450  $to = MailAddress::newFromUser( $watchingUser );
451 
452  # $PAGEEDITDATE is the time and date of the page change
453  # expressed in terms of individual local time of the notification
454  # recipient, i.e. watching user
455  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
456  $body = str_replace(
457  [ '$WATCHINGUSERNAME',
458  '$PAGEEDITDATE',
459  '$PAGEEDITTIME' ],
460  [ $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
461  ? $watchingUser->getRealName() : $watchingUser->getName(),
462  $contLang->userDate( $this->timestamp, $watchingUser ),
463  $contLang->userTime( $this->timestamp, $watchingUser ) ],
464  $this->body );
465 
466  $headers = [];
467  if ( $source === self::WATCHLIST ) {
468  $headers['List-Help'] = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Watchlist';
469  }
470 
471  return UserMailer::send( $to, $this->from, $this->subject, $body, [
472  'replyTo' => $this->replyto,
473  'headers' => $headers,
474  ] );
475  }
476 
483  private function sendImpersonal( $addresses ) {
484  if ( empty( $addresses ) ) {
485  return null;
486  }
487 
488  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
489  $body = str_replace(
490  [ '$WATCHINGUSERNAME',
491  '$PAGEEDITDATE',
492  '$PAGEEDITTIME' ],
493  [ wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
494  $contLang->date( $this->timestamp, false, false ),
495  $contLang->time( $this->timestamp, false, false ) ],
496  $this->body );
497 
498  return UserMailer::send( $addresses, $this->from, $this->subject, $body, [
499  'replyTo' => $this->replyto,
500  ] );
501  }
502 
503 }
This module processes the email notifications when the current page is changed.
composeCommonMailtext()
Generate the generic "this page has been changed" e-mail text.
notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid=false, $pageStatus='changed')
Send emails corresponding to the user $editor editing the page $title.
Job for email notification mails.
getText()
Get the text form (spaces not underscores) of the main part.
Definition: Title.php:1003
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...
Definition: UserMailer.php:115
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
compose( $user, $source)
Compose a mail to a given user and either queue it for sending, or send it now, depending on settings...
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable from
const WATCHLIST
Notification is due to a watchlisted page being edited.
$wgEnotifUseRealName
Use real name instead of username in e-mail "from" field.
$source
sendMails()
Send any queued mails.
bool $wgEnotifFromEditor
Allow sending of e-mail notifications with the editor&#39;s address as sender.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
title
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2251
$wgUsersNotifiedOnAllChanges
Array of usernames who will be sent a notification email for every change which occurs on a wiki...
$wgEnotifMinorEdits
Potentially send notification mails on minor edits to pages.
$wgEnotifImpersonal
Send a generic mail instead of a personalised mail for each user.
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 use $formDescriptor instead 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
static getMain()
Get the RequestContext object associated with the main request.
static newFromIDs( $ids)
Definition: UserArray.php:42
Stores a single person&#39;s name and email address.
Definition: MailAddress.php:32
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
$wgBlockDisablesLogin
If true, blocked users will not be allowed to login.
isAllowed( $action='')
Internal mechanics of testing a permission.
Definition: User.php:3642
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:773
getNamespace()
Get the namespace index, i.e.
Definition: Title.php:1045
static newFromUser(User $user)
Create a new MailAddress object for the given user.
Definition: MailAddress.php:66
actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers, $pageStatus='changed')
Immediate version of notifyOnPageChange().
sendPersonalised( $watchingUser, $source)
Does the per-user customizations to a notification e-mail (name, timestamp in proper timezone...
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$wgPasswordSender
Sender email address for e-mail notifications.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
canSendUserTalkEmail( $editor, $title, $minorEdit)
getId()
Get the user&#39;s ID.
Definition: User.php:2224
const USER_TALK
Notification is due to user&#39;s user talk being edited.
bool $wgEnotifRevealEditorAddress
Allow sending of e-mail notifications with the editor&#39;s address in "Reply-To".
static singleton( $domain=false)
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:277
static makeInternalOrExternalUrl( $name)
If url string starts with http, consider as external URL, else internal.
Definition: Skin.php:1206
sendImpersonal( $addresses)
Same as sendPersonalised but does impersonal mail suitable for bulk mailing.
getPageStatus()
Extensions that have hooks for UpdateUserMailerFormattedPageStatus (to provide additional pageStatus ...
static getSafeTitleFor( $name, $subpage=false)
Get a localised Title object for a page name with a possibly unvalidated subpage. ...
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:535
const NS_USER_TALK
Definition: Defines.php:63
$wgNoReplyAddress
Reply-To address for e-mail notifications.
$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...
static singleton()
Get the singleton instance of this class.
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1460
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
const ALL_CHANGES
Notification because user is notified for all changes.