MediaWiki master
LogPager.php
Go to the documentation of this file.
1<?php
26namespace MediaWiki\Pager;
27
42
48 private $types = [];
49
51 private $performer = '';
52
57 private $page = '';
58
60 private $pattern = false;
61
63 private $typeCGI = '';
64
66 private $action = '';
67
69 private $performerRestrictionsEnforced = false;
70
72 private $actionRestrictionsEnforced = false;
73
75 private $mConds;
76
78 private $mTagFilter;
79
81 private $mTagInvert;
82
85
87 private $linkBatchFactory;
88
90 private $actorNormalization;
91 private LogFormatterFactory $logFormatterFactory;
92
111 public function __construct( $list, $types = [], $performer = '', $pages = '',
112 $pattern = false, $conds = [], $year = false, $month = false, $day = false,
113 $tagFilter = '', $action = '', $logId = 0,
114 ?LinkBatchFactory $linkBatchFactory = null,
115 ?ActorNormalization $actorNormalization = null,
116 ?LogFormatterFactory $logFormatterFactory = null,
117 $tagInvert = false
118 ) {
119 parent::__construct( $list->getContext() );
120
121 $services = MediaWikiServices::getInstance();
122 $this->mConds = $conds;
123 $this->mLogEventsList = $list;
124
125 // Class is used directly in extensions - T266480
126 $this->linkBatchFactory = $linkBatchFactory ?? $services->getLinkBatchFactory();
127 $this->actorNormalization = $actorNormalization ?? $services->getActorNormalization();
128 $this->logFormatterFactory = $logFormatterFactory ?? $services->getLogFormatterFactory();
129
130 $this->limitLogId( $logId ); // set before types per T269761
131 $this->limitType( $types ); // also excludes hidden types
132 $this->limitFilterTypes();
133 $this->limitPerformer( $performer );
134 $this->limitTitles( $pages, $pattern );
135 $this->limitAction( $action );
136 $this->getDateCond( $year, $month, $day );
137 $this->mTagFilter = (string)$tagFilter;
138 $this->mTagInvert = (bool)$tagInvert;
139 }
140
141 public function getDefaultQuery() {
142 $query = parent::getDefaultQuery();
143 $query['type'] = $this->typeCGI; // arrays won't work here
144 $query['user'] = $this->performer;
145 $query['day'] = $this->mDay;
146 $query['month'] = $this->mMonth;
147 $query['year'] = $this->mYear;
148
149 return $query;
150 }
151
152 private function limitFilterTypes() {
153 if ( $this->hasEqualsClause( 'log_id' ) ) { // T220834
154 return;
155 }
156 $filterTypes = $this->getFilterParams();
157 $excludeTypes = [];
158 foreach ( $filterTypes as $type => $hide ) {
159 if ( $hide ) {
160 $excludeTypes[] = $type;
161 }
162 }
163 if ( $excludeTypes ) {
164 $this->mConds[] = $this->mDb->expr( 'log_type', '!=', $excludeTypes );
165 }
166 }
167
168 public function getFilterParams() {
169 $filters = [];
170 if ( count( $this->types ) ) {
171 return $filters;
172 }
173
174 // FIXME: This is broken, values from HTMLForm should be used.
175 $wpfilters = $this->getRequest()->getArray( "wpfilters" );
176 $filterLogTypes = $this->getConfig()->get( MainConfigNames::FilterLogTypes );
177
178 foreach ( $filterLogTypes as $type => $default ) {
179 // Back-compat: Check old URL params if the new param wasn't passed
180 if ( $wpfilters === null ) {
181 $hide = $this->getRequest()->getBool( "hide_{$type}_log", $default );
182 } else {
183 $hide = !in_array( $type, $wpfilters );
184 }
185
186 $filters[$type] = $hide;
187 }
188
189 return $filters;
190 }
191
199 private function limitType( $types ) {
200 $restrictions = $this->getConfig()->get( MainConfigNames::LogRestrictions );
201 // If $types is not an array, make it an array
202 $types = ( $types === '' ) ? [] : (array)$types;
203 // Don't even show header for private logs; don't recognize it...
204 $needReindex = false;
205 foreach ( $types as $type ) {
206 if ( isset( $restrictions[$type] )
207 && !$this->getAuthority()->isAllowed( $restrictions[$type] )
208 ) {
209 $needReindex = true;
210 $types = array_diff( $types, [ $type ] );
211 }
212 }
213 if ( $needReindex ) {
214 // Lots of this code makes assumptions that
215 // the first entry in the array is $types[0].
216 $types = array_values( $types );
217 }
218 $this->types = $types;
219 // Don't show private logs to unprivileged users.
220 // Also, only show them upon specific request to avoid surprises.
221 // Exception: if we are showing only a single log entry based on the log id,
222 // we don't require that "specific request" so that the links-in-logs feature
223 // works. See T269761
224 $audience = ( $types || $this->hasEqualsClause( 'log_id' ) ) ? 'user' : 'public';
225 $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience, $this->getAuthority() );
226 if ( $hideLogs !== false ) {
227 $this->mConds[] = $hideLogs;
228 }
229 if ( count( $types ) ) {
230 $this->mConds['log_type'] = $types;
231 // Set typeCGI; used in url param for paging
232 if ( count( $types ) == 1 ) {
233 $this->typeCGI = $types[0];
234 }
235 }
236 }
237
244 private function limitPerformer( $name ) {
245 if ( $name == '' ) {
246 return;
247 }
248
249 $actorId = $this->actorNormalization->findActorIdByName( $name, $this->mDb );
250
251 if ( !$actorId ) {
252 // Unknown user, match nothing.
253 $this->mConds[] = '1 = 0';
254 return;
255 }
256
257 $this->mConds[ 'log_actor' ] = $actorId;
258
259 $this->enforcePerformerRestrictions();
260
261 $this->performer = $name;
262 }
263
272 private function limitTitles( $pages, $pattern ) {
273 if ( !is_array( $pages ) ) {
274 $pages = [ $pages ];
275 }
276 $orConds = [];
277 $pattern = $pattern && !$this->getConfig()->get( MainConfigNames::MiserMode );
278 foreach ( $pages as $page ) {
279 if ( (string)$page === '' ) {
280 continue;
281 }
282 if ( !$page instanceof PageReference ) {
283 // NOTE: For some types of logs, the title may be something strange, like "User:#12345"!
284 $page = Title::newFromText( $page );
285 if ( !$page ) {
286 continue;
287 }
288 }
289 $titleFormatter = MediaWikiServices::getInstance()->getTitleFormatter();
290 $this->page = $titleFormatter->getPrefixedDBkey( $page );
291 $orConds[] = $this->mDb->makeList(
292 $this->getTitleConds( $page, $pattern ),
293 ISQLPlatform::LIST_AND
294 );
295 }
296 if ( $orConds ) {
297 $this->mConds[] = $this->mDb->makeList( $orConds, ISQLPlatform::LIST_OR );
298 $this->pattern = $pattern;
299 $this->enforceActionRestrictions();
300 }
301 }
302
310 private function getTitleConds( $page, $pattern ) {
311 $conds = [];
312 $ns = $page->getNamespace();
313 $db = $this->mDb;
314
315 $interwikiDelimiter = $this->getConfig()->get( MainConfigNames::UserrightsInterwikiDelimiter );
316
317 $doUserRightsLogLike = false;
318 if ( $this->types == [ 'rights' ] ) {
319 $parts = explode( $interwikiDelimiter, $page->getDBkey() );
320 if ( count( $parts ) == 2 ) {
321 [ $name, $database ] = array_map( 'trim', $parts );
322 if ( str_contains( $database, '*' ) ) {
323 $doUserRightsLogLike = true;
324 }
325 }
326 }
327
341 $conds['log_namespace'] = $ns;
342 if ( $doUserRightsLogLike ) {
343 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable $name is set when reached here
344 $params = [ $name . $interwikiDelimiter ];
345 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable $database is set when reached here
346 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal $database is set when reached here
347 $databaseParts = explode( '*', $database );
348 $databasePartCount = count( $databaseParts );
349 foreach ( $databaseParts as $i => $databasepart ) {
350 $params[] = $databasepart;
351 if ( $i < $databasePartCount - 1 ) {
352 $params[] = $db->anyString();
353 }
354 }
355 $conds[] = $db->expr( 'log_title', IExpression::LIKE, new LikeValue( ...$params ) );
356 } elseif ( $pattern ) {
357 $conds[] = $db->expr(
358 'log_title',
359 IExpression::LIKE,
360 new LikeValue( $page->getDBkey(), $db->anyString() )
361 );
362 } else {
363 $conds['log_title'] = $page->getDBkey();
364 }
365 return $conds;
366 }
367
373 private function limitAction( $action ) {
374 // Allow to filter the log by actions
375 $type = $this->typeCGI;
376 if ( $type === '' ) {
377 // nothing to do
378 return;
379 }
380 $actions = $this->getConfig()->get( MainConfigNames::ActionFilteredLogs );
381 if ( isset( $actions[$type] ) ) {
382 // log type can be filtered by actions
383 if ( $action !== '' && isset( $actions[$type][$action] ) ) {
384 // add condition to query
385 $this->mConds['log_action'] = $actions[$type][$action];
386 $this->action = $action;
387 }
388 }
389 }
390
395 protected function limitLogId( $logId ) {
396 if ( !$logId ) {
397 return;
398 }
399 $this->mConds['log_id'] = $logId;
400 }
401
407 public function getQueryInfo() {
408 $queryBuilder = DatabaseLogEntry::newSelectQueryBuilder( $this->mDb )
409 ->where( $this->mConds );
410
411 # Add log_search table if there are conditions on it.
412 # This filters the results to only include log rows that have
413 # log_search records with the specified ls_field and ls_value values.
414 if ( array_key_exists( 'ls_field', $this->mConds ) ) {
415 $queryBuilder->join( 'log_search', null, 'ls_log_id=log_id' );
416 $queryBuilder->ignoreIndex( [ 'log_search' => 'ls_log_id' ] );
417 $queryBuilder->useIndex( [ 'logging' => 'PRIMARY' ] );
418 if ( !$this->hasEqualsClause( 'ls_field' )
419 || !$this->hasEqualsClause( 'ls_value' )
420 ) {
421 # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
422 # to match a specific (ls_field,ls_value) tuple, then there will be
423 # no duplicate log rows. Otherwise, we need to remove the duplicates.
424 $queryBuilder->distinct();
425 }
426 } elseif ( array_key_exists( 'log_actor', $this->mConds ) ) {
427 // Optimizer doesn't pick the right index when a user has lots of log actions (T303089)
428 $index = 'log_actor_time';
429 foreach ( $this->getFilterParams() as $hide ) {
430 if ( !$hide ) {
431 $index = 'log_actor_type_time';
432 break;
433 }
434 }
435 $queryBuilder->useIndex( [ 'logging' => $index ] );
436 }
437
438 // T221458: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
439 // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
440 // Tell it not to reorder the query. But not when tag filtering or log_search was used, as it
441 // seems as likely to be harmed as helped in that case.
442 if ( $this->mTagFilter === '' && !array_key_exists( 'ls_field', $this->mConds ) ) {
443 $queryBuilder->straightJoinOption();
444 }
445
447 if ( $maxExecTime ) {
448 $queryBuilder->setMaxExecutionTime( $maxExecTime );
449 }
450
451 # Add ChangeTags filter query
452 MediaWikiServices::getInstance()->getChangeTagsStore()->modifyDisplayQueryBuilder(
453 $queryBuilder,
454 'logging',
455 $this->mTagFilter,
456 $this->mTagInvert
457 );
458
459 return $queryBuilder->getQueryInfo();
460 }
461
467 protected function hasEqualsClause( $field ) {
468 return (
469 array_key_exists( $field, $this->mConds ) &&
470 ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
471 );
472 }
473
474 public function getIndexField() {
475 return [ [ 'log_timestamp', 'log_id' ] ];
476 }
477
478 protected function doBatchLookups() {
479 $lb = $this->linkBatchFactory->newLinkBatch()->setCaller( __METHOD__ );
480 foreach ( $this->mResult as $row ) {
481 $lb->add( $row->log_namespace, $row->log_title );
482 $lb->addUser( new UserIdentityValue( (int)$row->log_user, $row->log_user_text ) );
483 $formatter = $this->logFormatterFactory->newFromRow( $row );
484 foreach ( $formatter->getPreloadTitles() as $title ) {
485 $lb->addObj( $title );
486 }
487 }
488 $lb->execute();
489 }
490
491 public function formatRow( $row ) {
492 return $this->mLogEventsList->logLine( $row );
493 }
494
499 public function getType() {
500 wfDeprecated( __METHOD__, '1.45' );
501 return $this->types;
502 }
503
509 public function getPerformer() {
510 return $this->performer;
511 }
512
517 public function getPage() {
518 wfDeprecated( __METHOD__, '1.45' );
519 return $this->page;
520 }
521
526 public function getPattern() {
527 wfDeprecated( __METHOD__, '1.45' );
528 return $this->pattern;
529 }
530
535 public function getYear() {
536 wfDeprecated( __METHOD__, '1.45' );
537 return $this->mYear;
538 }
539
544 public function getMonth() {
545 wfDeprecated( __METHOD__, '1.45' );
546 return $this->mMonth;
547 }
548
553 public function getDay() {
554 wfDeprecated( __METHOD__, '1.45' );
555 return $this->mDay;
556 }
557
562 public function getTagFilter() {
563 return $this->mTagFilter;
564 }
565
570 public function getTagInvert() {
571 wfDeprecated( __METHOD__, '1.45' );
572 return $this->mTagInvert;
573 }
574
579 public function getAction() {
580 wfDeprecated( __METHOD__, '1.45' );
581 return $this->action;
582 }
583
587 private function enforceActionRestrictions() {
588 if ( $this->actionRestrictionsEnforced ) {
589 return;
590 }
591 $this->actionRestrictionsEnforced = true;
592 if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
593 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_ACTION ) . ' = 0';
594 } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
595 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_ACTION ) .
596 ' != ' . LogPage::SUPPRESSED_ACTION;
597 }
598 }
599
603 private function enforcePerformerRestrictions() {
604 // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
605 if ( $this->performerRestrictionsEnforced ) {
606 return;
607 }
608 $this->performerRestrictionsEnforced = true;
609 if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
610 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_USER ) . ' = 0';
611 } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
612 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_USER ) .
613 ' != ' . LogPage::SUPPRESSED_USER;
614 }
615 }
616}
617
619class_alias( LogPager::class, '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.
Class to simplify the use of log pages.
Definition LogPage.php:50
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.
IReadableDatabase $mDb
getIndexField()
Returns the name of the index field.
Definition LogPager.php:474
getDefaultQuery()
Get an array of query parameters that should be put into self-links.
Definition LogPager.php:141
getPerformer()
Guaranteed to either return a valid title string or a Zero-Length String.
Definition LogPager.php:509
limitLogId( $logId)
Limit to the (single) specified log ID.
Definition LogPager.php:395
formatRow( $row)
Returns an HTML string representing the result row $row.
Definition LogPager.php:491
__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:111
hasEqualsClause( $field)
Checks if $this->mConds has $field matched to a single value.
Definition LogPager.php:467
LogEventsList $mLogEventsList
Definition LogPager.php:84
doBatchLookups()
Called from getBody(), before getStartBody() is called and after doQuery() was called.
Definition LogPager.php:478
getQueryInfo()
Constructs the most part of the query.
Definition LogPager.php:407
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:78
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.