MediaWiki  master
SpecialLog.php
Go to the documentation of this file.
1 <?php
24 namespace MediaWiki\Specials;
25 
26 use ChangeTags;
27 use LogEventsList;
28 use LogPage;
44 use Wikimedia\IPUtils;
46 use Wikimedia\Timestamp\TimestampException;
47 
53 class SpecialLog extends SpecialPage {
54 
55  private LinkBatchFactory $linkBatchFactory;
56 
57  private IConnectionProvider $dbProvider;
58 
59  private ActorNormalization $actorNormalization;
60 
61  private UserIdentityLookup $userIdentityLookup;
62 
63  private UserNameUtils $userNameUtils;
64 
72  public function __construct(
73  LinkBatchFactory $linkBatchFactory,
74  IConnectionProvider $dbProvider,
75  ActorNormalization $actorNormalization,
76  UserIdentityLookup $userIdentityLookup,
77  UserNameUtils $userNameUtils
78  ) {
79  parent::__construct( 'Log' );
80  $this->linkBatchFactory = $linkBatchFactory;
81  $this->dbProvider = $dbProvider;
82  $this->actorNormalization = $actorNormalization;
83  $this->userIdentityLookup = $userIdentityLookup;
84  $this->userNameUtils = $userNameUtils;
85  }
86 
87  public function execute( $par ) {
88  $this->setHeaders();
89  $this->outputHeader();
90  $out = $this->getOutput();
91  $out->addModules( 'mediawiki.userSuggest' );
92  $out->addModuleStyles( 'mediawiki.interface.helpers.styles' );
93  $this->addHelpLink( 'Help:Log' );
94 
95  $opts = new FormOptions;
96  $opts->add( 'type', '' );
97  $opts->add( 'user', '' );
98  $opts->add( 'page', '' );
99  $opts->add( 'pattern', false );
100  $opts->add( 'year', null, FormOptions::INTNULL );
101  $opts->add( 'month', null, FormOptions::INTNULL );
102  $opts->add( 'day', null, FormOptions::INTNULL );
103  $opts->add( 'tagfilter', '' );
104  $opts->add( 'tagInvert', false );
105  $opts->add( 'offset', '' );
106  $opts->add( 'dir', '' );
107  $opts->add( 'offender', '' );
108  $opts->add( 'subtype', '' );
109  $opts->add( 'logid', '' );
110 
111  // Set values
112  if ( $par !== null ) {
113  $this->parseParams( (string)$par );
114  }
115  $opts->fetchValuesFromRequest( $this->getRequest() );
116 
117  // Set date values
118  $dateString = $this->getRequest()->getVal( 'wpdate' );
119  if ( $dateString ) {
120  try {
121  $dateStamp = MWTimestamp::getInstance( $dateString . ' 00:00:00' );
122  } catch ( TimestampException $e ) {
123  // If users provide an invalid date, silently ignore it
124  // instead of letting an exception bubble up (T201411)
125  $dateStamp = false;
126  }
127  if ( $dateStamp ) {
128  $opts->setValue( 'year', (int)$dateStamp->format( 'Y' ) );
129  $opts->setValue( 'month', (int)$dateStamp->format( 'm' ) );
130  $opts->setValue( 'day', (int)$dateStamp->format( 'd' ) );
131  }
132  }
133 
134  // If the user doesn't have the right permission to view the specific
135  // log type, throw a PermissionsError
136  $logRestrictions = $this->getConfig()->get( MainConfigNames::LogRestrictions );
137  $type = $opts->getValue( 'type' );
138  if ( isset( $logRestrictions[$type] )
139  && !$this->getAuthority()->isAllowed( $logRestrictions[$type] )
140  ) {
141  throw new PermissionsError( $logRestrictions[$type] );
142  }
143 
144  # TODO: Move this into LogPager like other query conditions.
145  # Handle type-specific inputs
146  $qc = [];
147  $offenderName = $opts->getValue( 'offender' );
148  if ( $opts->getValue( 'type' ) == 'suppress' && $offenderName !== '' ) {
149  $dbr = $this->dbProvider->getReplicaDatabase();
150  $offenderId = $this->actorNormalization->findActorIdByName( $offenderName, $dbr );
151  if ( $offenderId ) {
152  $qc = [ 'ls_field' => 'target_author_actor', 'ls_value' => strval( $offenderId ) ];
153  } else {
154  // Unknown offender, thus results have to be empty
155  $qc = [ '1=0' ];
156  }
157  } else {
158  // Allow extensions to add relations to their search types
159  $this->getHookRunner()->onSpecialLogAddLogSearchRelations(
160  $opts->getValue( 'type' ), $this->getRequest(), $qc );
161  }
162 
163  # TODO: Move this into LogEventList and use it as filter-callback in the field descriptor.
164  # Some log types are only for a 'User:' title but we might have been given
165  # only the username instead of the full title 'User:username'. This part try
166  # to lookup for a user by that name and eventually fix user input. See T3697.
167  if ( in_array( $opts->getValue( 'type' ), self::getLogTypesOnUser( $this->getHookRunner() ) ) ) {
168  # ok we have a type of log which expect a user title.
169  $page = $opts->getValue( 'page' );
170  $target = Title::newFromText( $page );
171  if ( $target && $target->getNamespace() === NS_MAIN ) {
172  if ( IPUtils::isValidRange( $target->getText() ) ) {
173  $page = IPUtils::sanitizeRange( $target->getText() );
174  }
175  # User forgot to add 'User:', we are adding it for him
176  $target = Title::makeTitleSafe( NS_USER, $page );
177  } elseif ( $target && $target->getNamespace() === NS_USER
178  && IPUtils::isValidRange( $target->getText() )
179  ) {
180  $ipOrRange = IPUtils::sanitizeRange( $target->getText() );
181  if ( $ipOrRange !== $target->getText() ) {
182  $target = Title::makeTitleSafe( NS_USER, $ipOrRange );
183  }
184  }
185  if ( $target !== null ) {
186  $page = $target->getPrefixedText();
187  $opts->setValue( 'page', $page );
188  $this->getRequest()->setVal( 'page', $page );
189  }
190  }
191 
192  $this->show( $opts, $qc );
193  }
194 
206  public static function getLogTypesOnUser( HookRunner $runner = null ) {
207  static $types = null;
208  if ( $types !== null ) {
209  return $types;
210  }
211  $types = [
212  'block',
213  'newusers',
214  'rights',
215  'renameuser',
216  ];
217 
219  ->onGetLogTypesOnUser( $types );
220  return $types;
221  }
222 
228  public function getSubpagesForPrefixSearch() {
229  $subpages = LogPage::validTypes();
230  $subpages[] = 'all';
231  sort( $subpages );
232  return $subpages;
233  }
234 
243  private function parseParams( string $par ) {
244  # Get parameters
245  $parms = explode( '/', $par, 2 );
246  $symsForAll = [ '*', 'all' ];
247  if ( $parms[0] !== '' &&
248  ( in_array( $parms[0], LogPage::validTypes() ) || in_array( $parms[0], $symsForAll ) )
249  ) {
250  $this->getRequest()->setVal( 'type', $parms[0] );
251  if ( count( $parms ) === 2 ) {
252  $this->getRequest()->setVal( 'user', $parms[1] );
253  }
254  } elseif ( $par !== '' ) {
255  $this->getRequest()->setVal( 'user', $par );
256  }
257  }
258 
259  private function show( FormOptions $opts, array $extraConds ) {
260  # Create a LogPager item to get the results and a LogEventsList item to format them...
261  $loglist = new LogEventsList(
262  $this->getContext(),
263  $this->getLinkRenderer(),
265  );
266  $pager = new LogPager(
267  $loglist,
268  $opts->getValue( 'type' ),
269  $opts->getValue( 'user' ),
270  $opts->getValue( 'page' ),
271  $opts->getValue( 'pattern' ),
272  $extraConds,
273  $opts->getValue( 'year' ),
274  $opts->getValue( 'month' ),
275  $opts->getValue( 'day' ),
276  $opts->getValue( 'tagfilter' ),
277  $opts->getValue( 'subtype' ),
278  $opts->getValue( 'logid' ),
279  $this->linkBatchFactory,
280  $this->actorNormalization,
281  $opts->getValue( 'tagInvert' )
282  );
283 
284  # Set relevant user
285  $performer = $pager->getPerformer();
286  if ( $performer ) {
287  $performerUser = $this->userIdentityLookup->getUserIdentityByName( $performer );
288  // Only set valid local user as the relevant user (T344886)
289  // Uses the same condition as the SpecialContributions class did
290  if ( $performerUser && !IPUtils::isValidRange( $performer ) &&
291  ( $this->userNameUtils->isIP( $performer ) || $performerUser->isRegistered() )
292  ) {
293  $this->getSkin()->setRelevantUser( $performerUser );
294  }
295  }
296 
297  # Show form options
298  $succeed = $loglist->showOptions(
299  $opts->getValue( 'type' ),
300  $opts->getValue( 'year' ),
301  $opts->getValue( 'month' ),
302  $opts->getValue( 'day' )
303  );
304  if ( !$succeed ) {
305  return;
306  }
307 
308  $this->getOutput()->setPageTitleMsg(
309  ( new LogPage( $opts->getValue( 'type' ) ) )->getName()
310  );
311 
312  # Insert list
313  $logBody = $pager->getBody();
314  if ( $logBody ) {
315  $this->getOutput()->addHTML(
316  $pager->getNavigationBar() .
317  $this->getActionButtons(
318  $loglist->beginLogEventsList() .
319  $logBody .
320  $loglist->endLogEventsList()
321  ) .
322  $pager->getNavigationBar()
323  );
324  } else {
325  $this->getOutput()->addWikiMsg( 'logempty' );
326  }
327  }
328 
329  private function getActionButtons( $formcontents ) {
330  $canRevDelete = $this->getAuthority()
331  ->isAllowedAll( 'deletedhistory', 'deletelogentry' );
332  $showTagEditUI = ChangeTags::showTagEditingUI( $this->getAuthority() );
333  # If the user doesn't have the ability to delete log entries nor edit tags,
334  # don't bother showing them the button(s).
335  if ( !$canRevDelete && !$showTagEditUI ) {
336  return $formcontents;
337  }
338 
339  # Show button to hide log entries and/or edit change tags
340  $s = Html::openElement(
341  'form',
342  [ 'action' => wfScript(), 'id' => 'mw-log-deleterevision-submit' ]
343  ) . "\n";
344  $s .= Html::hidden( 'type', 'logging' ) . "\n";
345 
346  $buttons = '';
347  if ( $canRevDelete ) {
348  $buttons .= Html::element(
349  'button',
350  [
351  'type' => 'submit',
352  'name' => 'title',
353  'value' => SpecialPage::getTitleFor( 'Revisiondelete' )->getPrefixedDBkey(),
354  'class' => "deleterevision-log-submit mw-log-deleterevision-button mw-ui-button"
355  ],
356  $this->msg( 'showhideselectedlogentries' )->text()
357  ) . "\n";
358  }
359  if ( $showTagEditUI ) {
360  $buttons .= Html::element(
361  'button',
362  [
363  'type' => 'submit',
364  'name' => 'title',
365  'value' => SpecialPage::getTitleFor( 'EditTags' )->getPrefixedDBkey(),
366  'class' => "editchangetags-log-submit mw-log-editchangetags-button mw-ui-button"
367  ],
368  $this->msg( 'log-edit-tags' )->text()
369  ) . "\n";
370  }
371 
372  $buttons .= ( new ListToggle( $this->getOutput() ) )->getHTML();
373 
374  $s .= $buttons . $formcontents . $buttons;
375  $s .= Html::closeElement( 'form' );
376 
377  return $s;
378  }
379 
380  protected function getGroupName() {
381  return 'changes';
382  }
383 }
384 
388 class_alias( SpecialLog::class, 'SpecialLog' );
const NS_USER
Definition: Defines.php:66
const NS_MAIN
Definition: Defines.php:64
wfScript( $script='index')
Get the URL path to a MediaWiki entry point.
static showTagEditingUI(Authority $performer)
Indicate whether change tag editing UI is relevant.
const USE_CHECKBOXES
Class to simplify the use of log pages.
Definition: LogPage.php:43
static validTypes()
Get the list of valid log types.
Definition: LogPage.php:211
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:568
Helper class to keep track of options when mixing links and form elements.
Definition: FormOptions.php:41
add( $name, $default, $type=self::AUTO)
Add an option to be handled by this FormOptions instance.
Definition: FormOptions.php:89
const INTNULL
Integer type or null, maps to WebRequest::getIntOrNull() This is useful for the namespace selector.
Definition: FormOptions.php:61
This class is a collection of static functions that serve two purposes:
Definition: Html.php:57
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:280
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:889
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:344
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:256
Class for generating clickable toggle links for a list of checkboxes.
Definition: ListToggle.php:35
A class containing constants representing the names of configuration variables.
const LogRestrictions
Name constant for the LogRestrictions setting, for use with Config::get()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Parent class for all special pages.
Definition: SpecialPage.php:66
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
getSkin()
Shortcut to get the skin being used for this instance.
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
getConfig()
Shortcut to get main config object.
getContext()
Gets the context this SpecialPage is executed in.
getRequest()
Get the WebRequest being used for this instance.
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
getOutput()
Get the OutputPage being used for this instance.
getAuthority()
Shortcut to get the Authority executing this instance.
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
A special page that lists log entries.
Definition: SpecialLog.php:53
static getLogTypesOnUser(HookRunner $runner=null)
List log type for which the target is a user Thus if the given target is in NS_MAIN we can alter it t...
Definition: SpecialLog.php:206
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
Definition: SpecialLog.php:380
__construct(LinkBatchFactory $linkBatchFactory, IConnectionProvider $dbProvider, ActorNormalization $actorNormalization, UserIdentityLookup $userIdentityLookup, UserNameUtils $userNameUtils)
Definition: SpecialLog.php:72
execute( $par)
Default execute method Checks user permissions.
Definition: SpecialLog.php:87
getSubpagesForPrefixSearch()
Return an array of subpages that this special page will accept.
Definition: SpecialLog.php:228
Represents a title within MediaWiki.
Definition: Title.php:76
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:400
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:650
UserNameUtils service.
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:48
static getInstance( $ts=false)
Get a timestamp instance in GMT.
Definition: MWTimestamp.php:55
Show an error when a user tries to do something they do not have the necessary permissions for.
$runner
Service for dealing with the actor table.
Provide primary and replica IDatabase connections.