MediaWiki  1.27.2
EmailNotification.php
Go to the documentation of this file.
1 <?php
27 
47 
51  const USER_TALK = 'user_talk';
55  const WATCHLIST = 'watchlist';
59  const ALL_CHANGES = 'all_changes';
60 
61  protected $subject, $body, $replyto, $from;
63  protected $mailTargets = [];
64 
68  protected $title;
69 
73  protected $editor;
74 
85  public static function updateWatchlistTimestamp(
86  User $editor,
87  LinkTarget $linkTarget,
89  ) {
90  // wfDeprecated( __METHOD__, '1.27' );
91  $config = RequestContext::getMain()->getConfig();
92  if ( !$config->get( 'EnotifWatchlist' ) && !$config->get( 'ShowUpdatedMarker' ) ) {
93  return [];
94  }
95  return WatchedItemStore::getDefaultInstance()->updateNotificationTimestamp(
96  $editor,
97  $linkTarget,
99  );
100  }
101 
115  public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
116  $minorEdit, $oldid = false, $pageStatus = 'changed'
117  ) {
119 
120  if ( $title->getNamespace() < 0 ) {
121  return;
122  }
123 
124  // update wl_notificationtimestamp for watchers
125  $config = RequestContext::getMain()->getConfig();
126  $watchers = [];
127  if ( $config->get( 'EnotifWatchlist' ) || $config->get( 'ShowUpdatedMarker' ) ) {
128  $watchers = WatchedItemStore::getDefaultInstance()->updateNotificationTimestamp(
129  $editor,
130  $title,
131  $timestamp
132  );
133  }
134 
135  $sendEmail = true;
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 ) ) {
141  $sendEmail = false;
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
146  && $isUserTalkPage
147  && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
148  ) {
149  $sendEmail = true;
150  }
151  }
152  }
153 
154  if ( $sendEmail ) {
155  JobQueueGroup::singleton()->lazyPush( new EnotifNotifyJob(
156  $title,
157  [
158  'editor' => $editor->getName(),
159  'editorID' => $editor->getId(),
160  'timestamp' => $timestamp,
161  'summary' => $summary,
162  'minorEdit' => $minorEdit,
163  'oldid' => $oldid,
164  'watchers' => $watchers,
165  'pageStatus' => $pageStatus
166  ]
167  ) );
168  }
169  }
170 
187  public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
188  $oldid, $watchers, $pageStatus = 'changed' ) {
189  # we use $wgPasswordSender as sender's address
191  global $wgEnotifWatchlist, $wgBlockDisablesLogin;
193 
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
197 
198  $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
199 
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;
208 
209  $formattedPageStatus = [ 'deleted', 'created', 'moved', 'restored', 'changed' ];
210 
211  Hooks::run( 'UpdateUserMailerFormattedPageStatus', [ &$formattedPageStatus ] );
212  if ( !in_array( $this->pageStatus, $formattedPageStatus ) ) {
213  throw new MWException( 'Not a valid page status!' );
214  }
215 
216  $userTalkId = false;
217 
218  if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
219  if ( $wgEnotifUserTalk
220  && $isUserTalkPage
221  && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
222  ) {
223  $targetUser = User::newFromName( $title->getText() );
224  $this->compose( $targetUser, self::USER_TALK );
225  $userTalkId = $targetUser->getId();
226  }
227 
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() )
239  ) {
240  if ( Hooks::run( 'SendWatchlistEmailNotification', [ $watchingUser, $title, $this ] ) ) {
241  $this->compose( $watchingUser, self::WATCHLIST );
242  }
243  }
244  }
245  }
246  }
247 
248  foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
249  if ( $editor->getName() == $name ) {
250  // No point notifying the user that actually made the change!
251  continue;
252  }
253  $user = User::newFromName( $name );
254  $this->compose( $user, self::ALL_CHANGES );
255  }
256 
257  $this->sendMails();
258  }
259 
266  private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
267  global $wgEnotifUserTalk, $wgBlockDisablesLogin;
268  $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
269 
270  if ( $wgEnotifUserTalk && $isUserTalkPage ) {
271  $targetUser = User::newFromName( $title->getText() );
272 
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' ) )
281  ) {
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" );
286  } else {
287  wfDebug( __METHOD__ . ": sending talk page update notification\n" );
288  return true;
289  }
290  } else {
291  wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
292  }
293  }
294  return false;
295  }
296 
300  private function composeCommonMailtext() {
304 
305  $this->composed_common = true;
306 
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
310 
311  $keys = [];
312  $postTransformKeys = [];
313  $pageTitleUrl = $this->title->getCanonicalURL();
314  $pageTitle = $this->title->getPrefixedText();
315 
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();
321 
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();
328  }
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();
332  } else {
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();
338  }
339 
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' );
345 
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();
351 
352  } else {
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();
357  }
358 
359  $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalURL();
360  $keys['$HELPPAGE'] = wfExpandUrl(
361  Skin::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
362  );
363 
364  # Replace this after transforming the message, bug 35019
365  $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
366 
367  // Now build message's subject and body
368 
369  // Messages:
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();
374 
375  // Messages:
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 )
380  ->text();
381 
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 );
386 
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' )
395  ) {
396  $editorAddress = MailAddress::newFromUser( $this->editor );
397  if ( $wgEnotifFromEditor ) {
398  $this->from = $editorAddress;
399  } else {
400  $this->from = $adminAddress;
401  $this->replyto = $editorAddress;
402  }
403  } else {
404  $this->from = $adminAddress;
405  $this->replyto = new MailAddress( $wgNoReplyAddress );
406  }
407  }
408 
417  function compose( $user, $source ) {
419 
420  if ( !$this->composed_common ) {
421  $this->composeCommonMailtext();
422  }
423 
424  if ( $wgEnotifImpersonal ) {
425  $this->mailTargets[] = MailAddress::newFromUser( $user );
426  } else {
427  $this->sendPersonalised( $user, $source );
428  }
429  }
430 
434  function sendMails() {
436  if ( $wgEnotifImpersonal ) {
437  $this->sendImpersonal( $this->mailTargets );
438  }
439  }
440 
451  function sendPersonalised( $watchingUser, $source ) {
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 );
458 
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
462  $body = str_replace(
463  [ '$WATCHINGUSERNAME',
464  '$PAGEEDITDATE',
465  '$PAGEEDITTIME' ],
466  [ $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
467  ? $watchingUser->getRealName() : $watchingUser->getName(),
468  $wgContLang->userDate( $this->timestamp, $watchingUser ),
469  $wgContLang->userTime( $this->timestamp, $watchingUser ) ],
470  $this->body );
471 
472  $headers = [];
473  if ( $source === self::WATCHLIST ) {
474  $headers['List-Help'] = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Watchlist';
475  }
476 
477  return UserMailer::send( $to, $this->from, $this->subject, $body, [
478  'replyTo' => $this->replyto,
479  'headers' => $headers,
480  ] );
481  }
482 
489  function sendImpersonal( $addresses ) {
491 
492  if ( empty( $addresses ) ) {
493  return null;
494  }
495 
496  $body = str_replace(
497  [ '$WATCHINGUSERNAME',
498  '$PAGEEDITDATE',
499  '$PAGEEDITTIME' ],
500  [ wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
501  $wgContLang->date( $this->timestamp, false, false ),
502  $wgContLang->time( $this->timestamp, false, false ) ],
503  $this->body );
504 
505  return UserMailer::send( $addresses, $this->from, $this->subject, $body, [
506  'replyTo' => $this->replyto,
507  ] );
508  }
509 
510 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:568
This module processes the email notifications when the current page is changed.
composeCommonMailtext()
Generate the generic "this page has been changed" e-mail text.
Job for email notification mails.
getText()
Get the text form (spaces not underscores) of the main part.
Definition: Title.php:893
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
const WATCHLIST
Notification is due to a watchlisted page being edited.
$wgEnotifUseRealName
Use real name instead of username in e-mail "from" field.
canSendUserTalkEmail($editor, $title, $minorEdit)
$source
sendMails()
Send any queued mails.
static updateWatchlistTimestamp(User $editor, LinkTarget $linkTarget, $timestamp)
sendPersonalised($watchingUser, $source)
Does the per-user customizations to a notification e-mail (name, timestamp in proper timezone...
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
wfExpandUrl($url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2086
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
static getSafeTitleFor($name, $subpage=false)
Get a localised Title object for a page name with a possibly unvalidated subpage. ...
Definition: SpecialPage.php:88
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
$wgUsersNotifiedOnAllChanges
Array of usernames who will be sent a notification email for every change which occurs on a wiki...
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:114
$wgEnotifMinorEdits
Send notification mails on minor edits to watchlist pages.
$wgEnotifImpersonal
Send a generic mail instead of a personalised mail for each user.
static getMain()
Static methods.
compose($user, $source)
Compose a mail to a given user and either queue it for sending, or send it now, depending on settings...
isAllowed($action= '')
Internal mechanics of testing a permission.
Definition: User.php:3408
notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid=false, $pageStatus= 'changed')
Send emails corresponding to the user $editor editing the page $title.
Stores a single person's name and email address.
Definition: MailAddress.php:32
actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers, $pageStatus= 'changed')
Immediate version of notifyOnPageChange().
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing 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 unsetoffset-wrap String Wrap the message in html(usually something like"&lt
title
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
getNamespace()
Get the namespace index, i.e.
Definition: Title.php:934
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:12
static newFromUser(User $user)
Create a new MailAddress object for the given user.
Definition: MailAddress.php:59
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
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
$wgPasswordSender
Sender email address for e-mail notifications.
static singleton($wiki=false)
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
$wgEnotifRevealEditorAddress
Set the Reply-to address in notifications to the editor's address, if user allowed this in the prefer...
$wgEnotifFromEditor
True: from page editor if s/he opted-in.
getId()
Get the user's ID.
Definition: User.php:2061
const USER_TALK
Notification is due to user's user talk being edited.
sendImpersonal($addresses)
Same as sendPersonalised but does impersonal mail suitable for bulk mailing.
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:56
static makeInternalOrExternalUrl($name)
If url string starts with http, consider as external URL, else internal.
Definition: Skin.php:1097
static newFromIDs($ids)
Definition: UserArray.php:43
const NS_USER_TALK
Definition: Defines.php:72
$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 signleton instance of this class.
const ALL_CHANGES
Notification because user is notified for all changes.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310