MediaWiki master
SpecialLog.php
Go to the documentation of this file.
1<?php
6
7namespace MediaWiki\Specials;
8
9use MediaWiki\ChangeTags\ChangeTags;
10use MediaWiki\Exception\PermissionsError;
11use MediaWiki\HookContainer\HookRunner;
12use MediaWiki\Html\FormOptions;
13use MediaWiki\Html\Html;
14use MediaWiki\Html\ListToggle;
15use MediaWiki\Logging\LogEventsList;
16use MediaWiki\Logging\LogFormatterFactory;
17use MediaWiki\Logging\LogPage;
18use MediaWiki\Logging\Pager\LogPager;
19use MediaWiki\MainConfigNames;
20use MediaWiki\MediaWikiServices;
21use MediaWiki\Page\LinkBatchFactory;
22use MediaWiki\SpecialPage\SpecialPage;
23use MediaWiki\Title\Title;
24use MediaWiki\User\ActorNormalization;
25use MediaWiki\User\TempUser\TempUserConfig;
26use MediaWiki\User\UserIdentityLookup;
27use MediaWiki\User\UserNameUtils;
28use MediaWiki\Utils\MWTimestamp;
29use Wikimedia\IPUtils;
30use Wikimedia\Rdbms\IConnectionProvider;
31use Wikimedia\Rdbms\IExpression;
32use Wikimedia\Timestamp\TimestampException;
33
39class SpecialLog extends SpecialPage {
40
41 private readonly TempUserConfig $tempUserConfig;
42
43 public function __construct(
44 private readonly LinkBatchFactory $linkBatchFactory,
45 private readonly IConnectionProvider $dbProvider,
46 private readonly ActorNormalization $actorNormalization,
47 private readonly UserIdentityLookup $userIdentityLookup,
48 private readonly UserNameUtils $userNameUtils,
49 private readonly LogFormatterFactory $logFormatterFactory,
50 ?TempUserConfig $tempUserConfig = null
51 ) {
52 parent::__construct( 'Log' );
53 if ( $tempUserConfig instanceof TempUserConfig ) {
54 $this->tempUserConfig = $tempUserConfig;
55 } else {
56 $this->tempUserConfig = MediaWikiServices::getInstance()->getTempUserConfig();
57 }
58 }
59
61 public function execute( $par ) {
62 $this->setHeaders();
63 $this->outputHeader();
64 $out = $this->getOutput();
65 $out->addModuleStyles( 'mediawiki.interface.helpers.styles' );
66 $this->addHelpLink( 'Help:Log' );
67
68 $opts = new FormOptions;
69 $opts->add( 'type', '' );
70 $opts->add( 'user', '' );
71 $opts->add( 'page', [] );
72 $opts->add( 'pattern', false );
73 $opts->add( 'year', null, FormOptions::INTNULL );
74 $opts->add( 'month', null, FormOptions::INTNULL );
75 $opts->add( 'day', null, FormOptions::INTNULL );
76 $opts->add( 'tagfilter', '' );
77 $opts->add( 'tagInvert', false );
78 $opts->add( 'offset', '' );
79 $opts->add( 'dir', '' );
80 $opts->add( 'offender', '' );
81 $opts->add( 'subtype', '' );
82 $opts->add( 'logid', '' );
83
84 // Set values
85 if ( $par !== null ) {
86 $this->parseParams( (string)$par );
87 }
88 $opts->fetchValuesFromRequest( $this->getRequest() );
89
90 // Set date values
91 $dateString = $this->getRequest()->getVal( 'wpdate' );
92 if ( $dateString ) {
93 try {
94 $dateStamp = MWTimestamp::getInstance( $dateString . ' 00:00:00' );
95 } catch ( TimestampException ) {
96 // If users provide an invalid date, silently ignore it
97 // instead of letting an exception bubble up (T201411)
98 $dateStamp = false;
99 }
100 if ( $dateStamp ) {
101 $opts->setValue( 'year', (int)$dateStamp->format( 'Y' ) );
102 $opts->setValue( 'month', (int)$dateStamp->format( 'm' ) );
103 $opts->setValue( 'day', (int)$dateStamp->format( 'd' ) );
104 }
105 }
106
107 // If the user doesn't have the right permission to view the specific
108 // log type, throw a PermissionsError
109 $logRestrictions = $this->getConfig()->get( MainConfigNames::LogRestrictions );
110 $type = $opts->getValue( 'type' );
111 if ( isset( $logRestrictions[$type] )
112 && !$this->getAuthority()->isAllowed( $logRestrictions[$type] )
113 ) {
114 throw new PermissionsError( $logRestrictions[$type] );
115 }
116
117 # TODO: Move this into LogPager like other query conditions.
118 # Handle type-specific inputs
119 $qc = [];
120 $offenderName = $opts->getValue( 'offender' );
121 if ( $opts->getValue( 'type' ) == 'suppress' && $offenderName !== '' ) {
122 $dbr = $this->dbProvider->getReplicaDatabase();
123 $offenderId = $this->actorNormalization->findActorIdByName( $offenderName, $dbr );
124 if ( $offenderId ) {
125 $qc = [ 'ls_field' => 'target_author_actor', 'ls_value' => strval( $offenderId ) ];
126 } else {
127 // Unknown offender, thus results have to be empty
128 $qc = [ '1=0' ];
129 }
130 } else {
131 if ( $this->tempUserConfig->isKnown() ) {
132 // See T398423
133 // Three cases possible:
134 // 1. Special:Log/newusers is loaded as-is with 'user' field empty or set to non-temp user.
135 // The checkbox will be shown checked by default but have no value and is expected to exclude
136 // temporary accounts.
137 // 2. Special:Log/newusers is loaded as-is with 'user' field set to a temp username.
138 // The checkbox will be shown unchecked and have no value. We expect not to exclude temporary accounts.
139 // 3. form submitted, exclude temp accounts
140 // 4. form submitted, include temp accounts
141 // Check for cases 1 and 3 and omit temporary accounts in the pager query.
142 $formWasSubmitted = $this->getRequest()->getVal( 'wpFormIdentifier' ) === 'logeventslist';
143 if (
144 (
145 !$formWasSubmitted &&
146 !$this->getRequest()->getVal( 'logid' ) &&
147 !$this->getRequest()->getVal( 'excludetempacct' ) &&
148 !$this->tempUserConfig->isTempName( $opts->getValue( 'user' ) )
149 ) ||
150 (
151 $formWasSubmitted &&
152 !$this->getRequest()->getVal( 'logid' ) &&
153 $this->getRequest()->getVal( 'excludetempacct' )
154 )
155 ) {
156 $dbr = $this->dbProvider->getReplicaDatabase();
157 if ( $opts->getValue( 'type' ) === '' ) {
158 // Support excluding temporary account creations on Special:Log
159 $qc = [
160 $dbr->expr( 'log_type', '!=', 'newusers' )->orExpr(
161 $dbr->expr( 'log_type', '=', 'newusers' )
162 ->andExpr( $this->tempUserConfig
163 ->getMatchCondition( $dbr, 'logging_actor.actor_name', IExpression::NOT_LIKE ) )
164 )
165 ];
166 } elseif ( $opts->getValue( 'type' ) === 'newusers' ) {
167 $qc = [
168 $this->tempUserConfig
169 ->getMatchCondition( $dbr, 'logging_actor.actor_name', IExpression::NOT_LIKE )
170 ];
171 }
172 }
173 }
174
175 // Allow extensions to add relations to their search types
176 $this->getHookRunner()->onSpecialLogAddLogSearchRelations(
177 $opts->getValue( 'type' ), $this->getRequest(), $qc );
178 }
179
180 # TODO: Move this into LogEventList and use it as filter-callback in the field descriptor.
181 # Some log types are only for a 'User:' title but we might have been given
182 # only the username instead of the full title 'User:username'. This part try
183 # to lookup for a user by that name and eventually fix user input. See T3697.
184 if ( in_array( $opts->getValue( 'type' ), self::getLogTypesOnUser( $this->getHookRunner() ) ) ) {
185 $pages = [];
186 foreach ( $opts->getValue( 'page' ) as $page ) {
187 $page = $this->normalizeUserPage( $page );
188 if ( $page !== null ) {
189 $pages[] = $page->getPrefixedText();
190 }
191 }
192 $opts->setValue( 'page', $pages );
193 }
194
195 $this->show( $opts, $qc );
196 }
197
204 private function normalizeUserPage( $page ) {
205 $target = Title::newFromText( $page );
206 if ( $target && $target->getNamespace() === NS_MAIN ) {
207 if ( IPUtils::isValidRange( $target->getText() ) ) {
208 $page = IPUtils::sanitizeRange( $target->getText() );
209 }
210 # User forgot to add 'User:', we are adding it for them
211 $target = Title::makeTitleSafe( NS_USER, $page );
212 } elseif ( $target && $target->getNamespace() === NS_USER
213 && IPUtils::isValidRange( $target->getText() )
214 ) {
215 $ipOrRange = IPUtils::sanitizeRange( $target->getText() );
216 if ( $ipOrRange !== $target->getText() ) {
217 $target = Title::makeTitleSafe( NS_USER, $ipOrRange );
218 }
219 }
220 return $target;
221 }
222
234 public static function getLogTypesOnUser( ?HookRunner $runner = null ) {
235 static $types = null;
236 if ( $types !== null ) {
237 return $types;
238 }
239 $types = [
240 'block',
241 'newusers',
242 'rights',
243 'renameuser',
244 ];
245
247 ->onGetLogTypesOnUser( $types );
248 return $types;
249 }
250
256 public function getSubpagesForPrefixSearch() {
257 $subpages = LogPage::validTypes();
258
259 // Mechanism allowing extensions to change the log types listed as
260 // search hints (T398293).
261 $this->getHookRunner()->onSpecialLogGetSubpagesForPrefixSearch(
262 $this->getContext(),
263 $subpages
264 );
265
266 $subpages[] = 'all';
267
268 // Remove duplicates just in case a hook provides the same subpage twice
269 $subpages = array_unique( $subpages );
270 sort( $subpages );
271 return $subpages;
272 }
273
282 private function parseParams( string $par ) {
283 $params = explode( '/', $par, 2 );
284 $logType = $this->resolveLogType( $params );
285
286 if ( $logType ) {
287 $this->getRequest()->setVal( 'type', $logType );
288 if ( count( $params ) === 2 ) {
289 $this->getRequest()->setVal( 'user', $params[1] );
290 }
291 } elseif ( $par !== '' ) {
292 $this->getRequest()->setVal( 'user', $par );
293 }
294 }
295
312 private function resolveLogType( array $params ): string {
313 // Mechanism for changing the parameters of Special:Log
314 // from extensions (T381875)
315 $logType = $params[0] ?? null;
316
317 $this->getHookRunner()->onSpecialLogResolveLogType(
318 $params,
319 $logType
320 );
321
322 if ( $logType !== '' ) {
323 $symsForAll = [ '*', 'all' ];
324 $allowedTypes = array_merge( LogPage::validTypes(), $symsForAll );
325
326 if ( in_array( $logType, $allowedTypes ) ) {
327 return $logType;
328 }
329 }
330
331 return '';
332 }
333
334 private function show( FormOptions $opts, array $extraConds ) {
335 # Create a LogPager item to get the results and a LogEventsList item to format them...
336 $loglist = new LogEventsList(
337 $this->getContext(),
338 $this->getLinkRenderer(),
339 LogEventsList::USE_CHECKBOXES
340 );
341 $pager = new LogPager(
342 $loglist,
343 $opts->getValue( 'type' ),
344 $opts->getValue( 'user' ),
345 $opts->getValue( 'page' ),
346 $opts->getValue( 'pattern' ),
347 $extraConds,
348 $opts->getValue( 'year' ),
349 $opts->getValue( 'month' ),
350 $opts->getValue( 'day' ),
351 $opts->getValue( 'tagfilter' ),
352 $opts->getValue( 'subtype' ),
353 $opts->getValue( 'logid' ),
354 $this->linkBatchFactory,
355 $this->actorNormalization,
356 $this->logFormatterFactory,
357 $opts->getValue( 'tagInvert' )
358 );
359
360 # Set relevant user
361 $performer = $pager->getPerformer();
362 if ( $performer ) {
363 $performerUser = $this->userIdentityLookup->getUserIdentityByName( $performer );
364 // Only set valid local user as the relevant user (T344886)
365 // Uses the same condition as the SpecialContributions class did
366 if ( $performerUser && !IPUtils::isValidRange( $performer ) &&
367 ( $this->userNameUtils->isIP( $performer ) || $performerUser->isRegistered() )
368 ) {
369 $this->getSkin()->setRelevantUser( $performerUser );
370 }
371 }
372
373 # Show form options
374 $succeed = $loglist->showOptions(
375 $opts->getValue( 'type' ),
376 $opts->getValue( 'year' ),
377 $opts->getValue( 'month' ),
378 $opts->getValue( 'day' ),
379 $opts->getValue( 'user' ),
380 );
381 if ( !$succeed ) {
382 return;
383 }
384
385 $this->getOutput()->setPageTitleMsg(
386 ( new LogPage( $opts->getValue( 'type' ) ) )->getName()
387 );
388
389 # Insert list
390 $logBody = $pager->getBody();
391 if ( $logBody ) {
392 $this->getOutput()->addHTML(
393 $pager->getNavigationBar() .
394 $this->getActionButtons(
395 $loglist->beginLogEventsList() .
396 $logBody .
397 $loglist->endLogEventsList()
398 ) .
399 $pager->getNavigationBar()
400 );
401 } else {
402 $this->getOutput()->addWikiMsg( 'logempty' );
403 }
404 }
405
406 private function getActionButtons( string $formcontents ): string {
407 $canRevDelete = $this->getAuthority()
408 ->isAllowedAll( 'deletedhistory', 'deletelogentry' );
409 $showTagEditUI = ChangeTags::showTagEditingUI( $this->getAuthority() );
410 # If the user doesn't have the ability to delete log entries nor edit tags,
411 # don't bother showing them the button(s).
412 if ( !$canRevDelete && !$showTagEditUI ) {
413 return $formcontents;
414 }
415
416 # Show button to hide log entries and/or edit change tags
417 $s = Html::openElement(
418 'form',
419 [ 'action' => wfScript(), 'id' => 'mw-log-deleterevision-submit' ]
420 ) . "\n";
421 $s .= Html::hidden( 'type', 'logging' ) . "\n";
422
423 $buttons = '';
424 if ( $canRevDelete ) {
425 $buttons .= Html::element(
426 'button',
427 [
428 'type' => 'submit',
429 'name' => 'title',
430 'value' => SpecialPage::getTitleFor( 'Revisiondelete' )->getPrefixedDBkey(),
431 'class' => "deleterevision-log-submit mw-log-deleterevision-button mw-ui-button"
432 ],
433 $this->msg( 'showhideselectedlogentries' )->text()
434 ) . "\n";
435 }
436 if ( $showTagEditUI ) {
437 $buttons .= Html::element(
438 'button',
439 [
440 'type' => 'submit',
441 'name' => 'title',
442 'value' => SpecialPage::getTitleFor( 'EditTags' )->getPrefixedDBkey(),
443 'class' => "editchangetags-log-submit mw-log-editchangetags-button mw-ui-button"
444 ],
445 $this->msg( 'log-edit-tags' )->text()
446 ) . "\n";
447 }
448
449 $buttons .= ( new ListToggle( $this->getOutput() ) )->getHTML();
450
451 $s .= $buttons . $formcontents . $buttons;
452 $s .= Html::closeElement( 'form' );
453
454 return $s;
455 }
456
458 protected function getGroupName() {
459 return 'changes';
460 }
461}
462
463// @codeCoverageIgnoreStart
465class_alias( SpecialLog::class, 'SpecialLog' );
466// @codeCoverageIgnoreEnd
const NS_USER
Definition Defines.php:53
const NS_MAIN
Definition Defines.php:51
wfScript( $script='index')
Get the URL path to a MediaWiki entry point.
getContext()
Get the IContextSource in use here.
Definition Action.php:102
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage().
Definition Action.php:205
show()
The main action entry point.
getSkin()
Shortcut to get the Skin being used for this instance.
Definition Action.php:152
getOutput()
Get the OutputPage being used for this instance.
Definition Action.php:122
getAuthority()
Shortcut to get the Authority executing this instance.
Definition Action.php:142
getHTML()
Returns HTML for reporting the HTTP error.
Show an error when a user tries to do something they do not have the necessary permissions for.
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Helper class to keep track of options when mixing links and form elements.
add( $name, $default, $type=self::AUTO)
Add an option to be handled by this FormOptions instance.
Class for generating clickable toggle links for a list of checkboxes.
Class to simplify the use of log pages.
Definition LogPage.php:34
const LogRestrictions
Name constant for the LogRestrictions setting, for use with Config\get().
static getInstance()
Returns the global default instance of the top level service locator.
text()
Returns the message text.
Definition Message.php:1138
Factory for LinkBatch objects to batch query page metadata.
Parent class for all special pages.
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
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.
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 By default the message key is the canonical name of...
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
A special page that lists log entries.
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...
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
__construct(private readonly LinkBatchFactory $linkBatchFactory, private readonly IConnectionProvider $dbProvider, private readonly ActorNormalization $actorNormalization, private readonly UserIdentityLookup $userIdentityLookup, private readonly UserNameUtils $userNameUtils, private readonly LogFormatterFactory $logFormatterFactory, ?TempUserConfig $tempUserConfig=null)
execute( $par)
Default execute method Checks user permissions.This must be overridden by subclasses; it will be made...
getSubpagesForPrefixSearch()
Return an array of subpages that this special page will accept.
getPrefixedDBkey()
Get the prefixed database key form.
Definition Title.php:1802
UserNameUtils service.
$runner
isAllowedAll(... $permissions)
Checks whether this authority has any of the given permissions in general.
Service for dealing with the actor table.
Interface for temporary user creation config and name matching.
Service for looking up UserIdentity.
Provide primary and replica IDatabase connections.
element(SerializerNode $parent, SerializerNode $node, $contents)
array $params
The job parameters.