MediaWiki master
LogPager.php
Go to the documentation of this file.
1<?php
13
29
35 private $types = [];
36
38 private $performer = '';
39
44 private $page = '';
45
47 private $pattern = false;
48
50 private $typeCGI = '';
51
53 private $action = '';
54
56 private $performerRestrictionsEnforced = false;
57
59 private $actionRestrictionsEnforced = false;
60
62 private $mConds;
63
65 private $mTagFilter;
66
68 private $mTagInvert;
69
72
74 private $linkBatchFactory;
75
77 private $actorNormalization;
78 private LogFormatterFactory $logFormatterFactory;
79
98 public function __construct( $list, $types = [], $performer = '', $pages = '',
99 $pattern = false, $conds = [], $year = false, $month = false, $day = false,
100 $tagFilter = '', $action = '', $logId = 0,
101 ?LinkBatchFactory $linkBatchFactory = null,
102 ?ActorNormalization $actorNormalization = null,
103 ?LogFormatterFactory $logFormatterFactory = null,
104 $tagInvert = false
105 ) {
106 parent::__construct( $list->getContext() );
107
108 $services = MediaWikiServices::getInstance();
109 $this->mConds = $conds;
110 $this->mLogEventsList = $list;
111
112 // Class is used directly in extensions - T266480
113 $this->linkBatchFactory = $linkBatchFactory ?? $services->getLinkBatchFactory();
114 $this->actorNormalization = $actorNormalization ?? $services->getActorNormalization();
115 $this->logFormatterFactory = $logFormatterFactory ?? $services->getLogFormatterFactory();
116
117 $this->limitLogId( $logId ); // set before types per T269761
118 $this->limitType( $types ); // also excludes hidden types
119 $this->limitFilterTypes();
120 $this->limitPerformer( $performer );
121 $this->limitTitles( $pages, $pattern );
122 $this->limitAction( $action );
123 $this->getDateCond( $year, $month, $day );
124 $this->mTagFilter = (string)$tagFilter;
125 $this->mTagInvert = (bool)$tagInvert;
126 }
127
129 public function getDefaultQuery() {
130 $query = parent::getDefaultQuery();
131 $query['type'] = $this->typeCGI; // arrays won't work here
132 $query['user'] = $this->performer;
133 $query['day'] = $this->mDay;
134 $query['month'] = $this->mMonth;
135 $query['year'] = $this->mYear;
136
137 return $query;
138 }
139
140 private function limitFilterTypes() {
141 if ( $this->hasEqualsClause( 'log_id' ) ) { // T220834
142 return;
143 }
144 $filterTypes = $this->getFilterParams();
145 $excludeTypes = [];
146 foreach ( $filterTypes as $type => $hide ) {
147 if ( $hide ) {
148 $excludeTypes[] = $type;
149 }
150 }
151 if ( $excludeTypes ) {
152 $this->mConds[] = $this->mDb->expr( 'log_type', '!=', $excludeTypes );
153 }
154 }
155
156 public function getFilterParams(): array {
157 $filters = [];
158 if ( count( $this->types ) ) {
159 return $filters;
160 }
161
162 // FIXME: This is broken, values from HTMLForm should be used.
163 $wpfilters = $this->getRequest()->getArray( "wpfilters" );
164 $filterLogTypes = $this->getConfig()->get( MainConfigNames::FilterLogTypes );
165
166 foreach ( $filterLogTypes as $type => $default ) {
167 // Back-compat: Check old URL params if the new param wasn't passed
168 if ( $wpfilters === null ) {
169 $hide = $this->getRequest()->getBool( "hide_{$type}_log", $default );
170 } else {
171 $hide = !in_array( $type, $wpfilters );
172 }
173
174 $filters[$type] = $hide;
175 }
176
177 return $filters;
178 }
179
187 private function limitType( $types ) {
188 $restrictions = $this->getConfig()->get( MainConfigNames::LogRestrictions );
189 // If $types is not an array, make it an array
190 $types = ( $types === '' ) ? [] : (array)$types;
191 // Don't even show header for private logs; don't recognize it...
192 $needReindex = false;
193 foreach ( $types as $type ) {
194 if ( isset( $restrictions[$type] )
195 && !$this->getAuthority()->isAllowed( $restrictions[$type] )
196 ) {
197 $needReindex = true;
198 $types = array_diff( $types, [ $type ] );
199 }
200 }
201 if ( $needReindex ) {
202 // Lots of this code makes assumptions that
203 // the first entry in the array is $types[0].
204 $types = array_values( $types );
205 }
206 $this->types = $types;
207 // Don't show private logs to unprivileged users.
208 // Also, only show them upon specific request to avoid surprises.
209 // Exception: if we are showing only a single log entry based on the log id,
210 // we don't require that "specific request" so that the links-in-logs feature
211 // works. See T269761
212 $audience = ( $types || $this->hasEqualsClause( 'log_id' ) ) ? 'user' : 'public';
213 $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience, $this->getAuthority() );
214 if ( $hideLogs !== false ) {
215 $this->mConds[] = $hideLogs;
216 }
217 if ( count( $types ) ) {
218 $this->mConds['log_type'] = $types;
219 // Set typeCGI; used in url param for paging
220 if ( count( $types ) == 1 ) {
221 $this->typeCGI = $types[0];
222 }
223 }
224 }
225
232 private function limitPerformer( $name ) {
233 if ( $name == '' ) {
234 return;
235 }
236
237 $actorId = $this->actorNormalization->findActorIdByName( $name, $this->mDb );
238
239 if ( !$actorId ) {
240 // Unknown user, match nothing.
241 $this->mConds[] = '1 = 0';
242 return;
243 }
244
245 $this->mConds[ 'log_actor' ] = $actorId;
246
247 $this->enforcePerformerRestrictions();
248
249 $this->performer = $name;
250 }
251
260 private function limitTitles( $pages, $pattern ) {
261 if ( !is_array( $pages ) ) {
262 $pages = [ $pages ];
263 }
264 $orConds = [];
265 $pattern = $pattern && !$this->getConfig()->get( MainConfigNames::MiserMode );
266 foreach ( $pages as $page ) {
267 if ( (string)$page === '' ) {
268 continue;
269 }
270 if ( !$page instanceof PageReference ) {
271 // NOTE: For some types of logs, the title may be something strange, like "User:#12345"!
272 $page = Title::newFromText( $page );
273 if ( !$page ) {
274 continue;
275 }
276 }
277 $titleFormatter = MediaWikiServices::getInstance()->getTitleFormatter();
278 $this->page = $titleFormatter->getPrefixedDBkey( $page );
279 $orConds[] = $this->mDb->makeList(
280 $this->getTitleConds( $page, $pattern ),
281 ISQLPlatform::LIST_AND
282 );
283 }
284 if ( $orConds ) {
285 $this->mConds[] = $this->mDb->makeList( $orConds, ISQLPlatform::LIST_OR );
286 $this->pattern = $pattern;
287 $this->enforceActionRestrictions();
288 }
289 }
290
298 private function getTitleConds( $page, $pattern ) {
299 $conds = [];
300 $ns = $page->getNamespace();
301 $db = $this->mDb;
302
303 $interwikiDelimiter = $this->getConfig()->get( MainConfigNames::UserrightsInterwikiDelimiter );
304
305 $doUserRightsLogLike = false;
306 if ( $this->types == [ 'rights' ] ) {
307 $parts = explode( $interwikiDelimiter, $page->getDBkey() );
308 if ( count( $parts ) == 2 ) {
309 [ $name, $database ] = array_map( 'trim', $parts );
310 if ( str_contains( $database, '*' ) ) {
311 $doUserRightsLogLike = true;
312 }
313 }
314 }
315
329 $conds['log_namespace'] = $ns;
330 if ( $doUserRightsLogLike ) {
331 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable $name is set when reached here
332 $params = [ $name . $interwikiDelimiter ];
333 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable $database is set when reached here
334 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal $database is set when reached here
335 $databaseParts = explode( '*', $database );
336 $databasePartCount = count( $databaseParts );
337 foreach ( $databaseParts as $i => $databasepart ) {
338 $params[] = $databasepart;
339 if ( $i < $databasePartCount - 1 ) {
340 $params[] = $db->anyString();
341 }
342 }
343 $conds[] = $db->expr( 'log_title', IExpression::LIKE, new LikeValue( ...$params ) );
344 } elseif ( $pattern ) {
345 $conds[] = $db->expr(
346 'log_title',
347 IExpression::LIKE,
348 new LikeValue( $page->getDBkey(), $db->anyString() )
349 );
350 } else {
351 $conds['log_title'] = $page->getDBkey();
352 }
353 return $conds;
354 }
355
361 private function limitAction( $action ) {
362 // Allow to filter the log by actions
363 $type = $this->typeCGI;
364 if ( $type === '' ) {
365 // nothing to do
366 return;
367 }
368 $actions = $this->getConfig()->get( MainConfigNames::ActionFilteredLogs );
369 if ( isset( $actions[$type] ) ) {
370 // log type can be filtered by actions
371 if ( $action !== '' && isset( $actions[$type][$action] ) ) {
372 // add condition to query
373 $this->mConds['log_action'] = $actions[$type][$action];
374 $this->action = $action;
375 }
376 }
377 }
378
383 protected function limitLogId( $logId ) {
384 if ( !$logId ) {
385 return;
386 }
387 $this->mConds['log_id'] = $logId;
388 }
389
395 public function getQueryInfo() {
396 $queryBuilder = DatabaseLogEntry::newSelectQueryBuilder( $this->mDb )
397 ->where( $this->mConds );
398
399 # Add log_search table if there are conditions on it.
400 # This filters the results to only include log rows that have
401 # log_search records with the specified ls_field and ls_value values.
402 if ( array_key_exists( 'ls_field', $this->mConds ) ) {
403 $queryBuilder->join( 'log_search', null, 'ls_log_id=log_id' );
404 $queryBuilder->ignoreIndex( [ 'log_search' => 'ls_log_id' ] );
405 $queryBuilder->useIndex( [ 'logging' => 'PRIMARY' ] );
406 if ( !$this->hasEqualsClause( 'ls_field' )
407 || !$this->hasEqualsClause( 'ls_value' )
408 ) {
409 # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
410 # to match a specific (ls_field,ls_value) tuple, then there will be
411 # no duplicate log rows. Otherwise, we need to remove the duplicates.
412 $queryBuilder->distinct();
413 }
414 } elseif ( array_key_exists( 'log_actor', $this->mConds ) ) {
415 // Optimizer doesn't pick the right index when a user has lots of log actions (T303089)
416 $index = 'log_actor_time';
417 foreach ( $this->getFilterParams() as $hide ) {
418 if ( !$hide ) {
419 $index = 'log_actor_type_time';
420 break;
421 }
422 }
423 $queryBuilder->useIndex( [ 'logging' => $index ] );
424 }
425
426 // T221458: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
427 // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
428 // Tell it not to reorder the query. But not when tag filtering or log_search was used, as it
429 // seems as likely to be harmed as helped in that case.
430 if ( $this->mTagFilter === '' && !array_key_exists( 'ls_field', $this->mConds ) ) {
431 $queryBuilder->straightJoinOption();
432 }
433
434 $maxExecTime = $this->getConfig()->get( MainConfigNames::MaxExecutionTimeForExpensiveQueries );
435 if ( $maxExecTime ) {
436 $queryBuilder->setMaxExecutionTime( $maxExecTime );
437 }
438
439 # Add ChangeTags filter query
440 MediaWikiServices::getInstance()->getChangeTagsStore()->modifyDisplayQueryBuilder(
441 $queryBuilder,
442 'logging',
443 $this->mTagFilter,
444 $this->mTagInvert
445 );
446
447 return $queryBuilder->getQueryInfo();
448 }
449
455 protected function hasEqualsClause( $field ) {
456 return (
457 array_key_exists( $field, $this->mConds ) &&
458 ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
459 );
460 }
461
463 public function getIndexField() {
464 return [ [ 'log_timestamp', 'log_id' ] ];
465 }
466
467 protected function doBatchLookups() {
468 $lb = $this->linkBatchFactory->newLinkBatch()->setCaller( __METHOD__ );
469 foreach ( $this->mResult as $row ) {
470 $lb->add( $row->log_namespace, $row->log_title );
471 $lb->addUser( new UserIdentityValue( (int)$row->log_user, $row->log_user_text ) );
472 $formatter = $this->logFormatterFactory->newFromRow( $row );
473 foreach ( $formatter->getPreloadTitles() as $title ) {
474 $lb->addObj( $title );
475 }
476 }
477 $lb->execute();
478 }
479
481 public function formatRow( $row ) {
482 return $this->mLogEventsList->logLine( $row );
483 }
484
489 public function getType() {
490 wfDeprecated( __METHOD__, '1.45' );
491 return $this->types;
492 }
493
499 public function getPerformer() {
500 return $this->performer;
501 }
502
507 public function getPage() {
508 wfDeprecated( __METHOD__, '1.45' );
509 return $this->page;
510 }
511
516 public function getPattern() {
517 wfDeprecated( __METHOD__, '1.45' );
518 return $this->pattern;
519 }
520
525 public function getYear() {
526 wfDeprecated( __METHOD__, '1.45' );
527 return $this->mYear;
528 }
529
534 public function getMonth() {
535 wfDeprecated( __METHOD__, '1.45' );
536 return $this->mMonth;
537 }
538
543 public function getDay() {
544 wfDeprecated( __METHOD__, '1.45' );
545 return $this->mDay;
546 }
547
552 public function getTagFilter() {
553 return $this->mTagFilter;
554 }
555
560 public function getTagInvert() {
561 wfDeprecated( __METHOD__, '1.45' );
562 return $this->mTagInvert;
563 }
564
569 public function getAction() {
570 wfDeprecated( __METHOD__, '1.45' );
571 return $this->action;
572 }
573
577 private function enforceActionRestrictions() {
578 if ( $this->actionRestrictionsEnforced ) {
579 return;
580 }
581 $this->actionRestrictionsEnforced = true;
582 if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
583 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_ACTION ) . ' = 0';
584 } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
585 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_ACTION ) .
587 }
588 }
589
593 private function enforcePerformerRestrictions() {
594 // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
595 if ( $this->performerRestrictionsEnforced ) {
596 return;
597 }
598 $this->performerRestrictionsEnforced = true;
599 if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
600 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_USER ) . ' = 0';
601 } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
602 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_USER ) .
604 }
605 }
606}
607
609class_alias( LogPager::class, 'LogPager' );
610
612class_alias( LogPager::class, 'MediaWiki\\Pager\\LogPager' );
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
A value class to process existing log entries.
static newSelectQueryBuilder(IReadableDatabase $db)
static getExcludeClause( $db, $audience='public', ?Authority $performer=null)
SQL clause to skip forbidden log types for this user.
Class to simplify the use of log pages.
Definition LogPage.php:35
getDefaultQuery()
Get an array of query parameters that should be put into self-links.By default, all parameters passed...
Definition LogPager.php:129
getIndexField()
Returns the name of the index field.If the pager supports multiple orders, it may return an array of ...
Definition LogPager.php:463
getPerformer()
Guaranteed to either return a valid title string or a Zero-Length String.
Definition LogPager.php:499
formatRow( $row)
Returns an HTML string representing the result row $row.Rows will be concatenated and returned by get...
Definition LogPager.php:481
doBatchLookups()
Called from getBody(), before getStartBody() is called and after doQuery() was called.
Definition LogPager.php:467
__construct( $list, $types=[], $performer='', $pages='', $pattern=false, $conds=[], $year=false, $month=false, $day=false, $tagFilter='', $action='', $logId=0, ?LinkBatchFactory $linkBatchFactory=null, ?ActorNormalization $actorNormalization=null, ?LogFormatterFactory $logFormatterFactory=null, $tagInvert=false)
Definition LogPager.php:98
getQueryInfo()
Constructs the most part of the query.
Definition LogPager.php:395
hasEqualsClause( $field)
Checks if $this->mConds has $field matched to a single value.
Definition LogPager.php:455
limitLogId( $logId)
Limit to the (single) specified log ID.
Definition LogPager.php:383
A class containing constants representing the names of configuration variables.
const LogRestrictions
Name constant for the LogRestrictions setting, for use with Config::get()
const ActionFilteredLogs
Name constant for the ActionFilteredLogs setting, for use with Config::get()
const MaxExecutionTimeForExpensiveQueries
Name constant for the MaxExecutionTimeForExpensiveQueries setting, for use with Config::get()
const FilterLogTypes
Name constant for the FilterLogTypes setting, for use with Config::get()
const UserrightsInterwikiDelimiter
Name constant for the UserrightsInterwikiDelimiter setting, for use with Config::get()
const MiserMode
Name constant for the MiserMode 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.
Factory for LinkBatch objects to batch query page metadata.
IndexPager with a formatted navigation bar.
getDateCond( $year, $month, $day=-1)
Set and return the offset timestamp such that we can get all revisions with a timestamp up to the spe...
Represents a title within MediaWiki.
Definition Title.php:69
Value object representing a user's identity.
Content of like value.
Definition LikeValue.php:14
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
Service for dealing with the actor table.
Interface for query language.
array $params
The job parameters.