MediaWiki master
LogPager.php
Go to the documentation of this file.
1<?php
26namespace MediaWiki\Pager;
27
30use LogFormatter;
31use LogPage;
40
46 private $types = [];
47
49 private $performer = '';
50
52 private $page = '';
53
55 private $pattern = false;
56
58 private $typeCGI = '';
59
61 private $action = '';
62
64 private $performerRestrictionsEnforced = false;
65
67 private $actionRestrictionsEnforced = false;
68
70 private $mConds;
71
73 private $mTagFilter;
74
76 private $mTagInvert;
77
80
82 private $linkBatchFactory;
83
85 private $actorNormalization;
86
104 public function __construct( $list, $types = [], $performer = '', $page = '',
105 $pattern = false, $conds = [], $year = false, $month = false, $day = false,
106 $tagFilter = '', $action = '', $logId = 0,
107 LinkBatchFactory $linkBatchFactory = null,
108 ActorNormalization $actorNormalization = null,
109 $tagInvert = false
110 ) {
111 parent::__construct( $list->getContext() );
112
113 $services = MediaWikiServices::getInstance();
114 $this->mConds = $conds;
115 $this->mLogEventsList = $list;
116
117 // Class is used directly in extensions - T266480
118 $this->linkBatchFactory = $linkBatchFactory ?? $services->getLinkBatchFactory();
119 $this->actorNormalization = $actorNormalization ?? $services->getActorNormalization();
120
121 $this->limitLogId( $logId ); // set before types per T269761
122 $this->limitType( $types ); // also excludes hidden types
123 $this->limitFilterTypes();
124 $this->limitPerformer( $performer );
125 $this->limitTitle( $page, $pattern );
126 $this->limitAction( $action );
127 $this->getDateCond( $year, $month, $day );
128 $this->mTagFilter = (string)$tagFilter;
129 $this->mTagInvert = (bool)$tagInvert;
130 }
131
132 public function getDefaultQuery() {
133 $query = parent::getDefaultQuery();
134 $query['type'] = $this->typeCGI; // arrays won't work here
135 $query['user'] = $this->performer;
136 $query['day'] = $this->mDay;
137 $query['month'] = $this->mMonth;
138 $query['year'] = $this->mYear;
139
140 return $query;
141 }
142
143 private function limitFilterTypes() {
144 if ( $this->hasEqualsClause( 'log_id' ) ) { // T220834
145 return;
146 }
147 $filterTypes = $this->getFilterParams();
148 $excludeTypes = [];
149 foreach ( $filterTypes as $type => $hide ) {
150 if ( $hide ) {
151 $excludeTypes[] = $type;
152 }
153 }
154 if ( $excludeTypes ) {
155 $this->mConds[] = $this->mDb->expr( 'log_type', '!=', $excludeTypes );
156 }
157 }
158
159 public function getFilterParams() {
160 $filters = [];
161 if ( count( $this->types ) ) {
162 return $filters;
163 }
164
165 // FIXME: This is broken, values from HTMLForm should be used.
166 $wpfilters = $this->getRequest()->getArray( "wpfilters" );
167 $filterLogTypes = $this->getConfig()->get( MainConfigNames::FilterLogTypes );
168
169 foreach ( $filterLogTypes as $type => $default ) {
170 // Back-compat: Check old URL params if the new param wasn't passed
171 if ( $wpfilters === null ) {
172 $hide = $this->getRequest()->getBool( "hide_{$type}_log", $default );
173 } else {
174 $hide = !in_array( $type, $wpfilters );
175 }
176
177 $filters[$type] = $hide;
178 }
179
180 return $filters;
181 }
182
190 private function limitType( $types ) {
191 $restrictions = $this->getConfig()->get( MainConfigNames::LogRestrictions );
192 // If $types is not an array, make it an array
193 $types = ( $types === '' ) ? [] : (array)$types;
194 // Don't even show header for private logs; don't recognize it...
195 $needReindex = false;
196 foreach ( $types as $type ) {
197 if ( isset( $restrictions[$type] )
198 && !$this->getAuthority()->isAllowed( $restrictions[$type] )
199 ) {
200 $needReindex = true;
201 $types = array_diff( $types, [ $type ] );
202 }
203 }
204 if ( $needReindex ) {
205 // Lots of this code makes assumptions that
206 // the first entry in the array is $types[0].
207 $types = array_values( $types );
208 }
209 $this->types = $types;
210 // Don't show private logs to unprivileged users.
211 // Also, only show them upon specific request to avoid surprises.
212 // Exception: if we are showing only a single log entry based on the log id,
213 // we don't require that "specific request" so that the links-in-logs feature
214 // works. See T269761
215 $audience = ( $types || $this->hasEqualsClause( 'log_id' ) ) ? 'user' : 'public';
216 $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience, $this->getAuthority() );
217 if ( $hideLogs !== false ) {
218 $this->mConds[] = $hideLogs;
219 }
220 if ( count( $types ) ) {
221 $this->mConds['log_type'] = $types;
222 // Set typeCGI; used in url param for paging
223 if ( count( $types ) == 1 ) {
224 $this->typeCGI = $types[0];
225 }
226 }
227 }
228
235 private function limitPerformer( $name ) {
236 if ( $name == '' ) {
237 return;
238 }
239
240 $actorId = $this->actorNormalization->findActorIdByName( $name, $this->mDb );
241
242 if ( !$actorId ) {
243 // Unknown user, match nothing.
244 $this->mConds[] = '1 = 0';
245 return;
246 }
247
248 $this->mConds[ 'log_actor' ] = $actorId;
249
250 $this->enforcePerformerRestrictions();
251
252 $this->performer = $name;
253 }
254
263 private function limitTitle( $page, $pattern ) {
264 if ( !$page instanceof PageReference ) {
265 // NOTE: For some types of logs, the title may be something strange, like "User:#12345"!
266 $page = Title::newFromText( $page );
267 if ( !$page ) {
268 return;
269 }
270 }
271
272 $titleFormatter = MediaWikiServices::getInstance()->getTitleFormatter();
273 $this->page = $titleFormatter->getPrefixedDBkey( $page );
274 $ns = $page->getNamespace();
275 $db = $this->mDb;
276
277 $interwikiDelimiter = $this->getConfig()->get( MainConfigNames::UserrightsInterwikiDelimiter );
278
279 $doUserRightsLogLike = false;
280 if ( $this->types == [ 'rights' ] ) {
281 $parts = explode( $interwikiDelimiter, $page->getDBkey() );
282 if ( count( $parts ) == 2 ) {
283 [ $name, $database ] = array_map( 'trim', $parts );
284 if ( str_contains( $database, '*' ) ) {
285 $doUserRightsLogLike = true;
286 }
287 }
288 }
289
303 $this->mConds['log_namespace'] = $ns;
304 if ( $doUserRightsLogLike ) {
305 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable $name is set when reached here
306 $params = [ $name . $interwikiDelimiter ];
307 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable $database is set when reached here
308 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal $database is set when reached here
309 $databaseParts = explode( '*', $database );
310 $databasePartCount = count( $databaseParts );
311 foreach ( $databaseParts as $i => $databasepart ) {
312 $params[] = $databasepart;
313 if ( $i < $databasePartCount - 1 ) {
314 $params[] = $db->anyString();
315 }
316 }
317 $this->mConds[] = $db->expr( 'log_title', IExpression::LIKE, new LikeValue( ...$params ) );
318 } elseif ( $pattern && !$this->getConfig()->get( MainConfigNames::MiserMode ) ) {
319 $this->mConds[] = $db->expr(
320 'log_title',
321 IExpression::LIKE,
322 new LikeValue( $page->getDBkey(), $db->anyString() )
323 );
324 $this->pattern = $pattern;
325 } else {
326 $this->mConds['log_title'] = $page->getDBkey();
327 }
328 $this->enforceActionRestrictions();
329 }
330
336 private function limitAction( $action ) {
337 // Allow to filter the log by actions
338 $type = $this->typeCGI;
339 if ( $type === '' ) {
340 // nothing to do
341 return;
342 }
343 $actions = $this->getConfig()->get( MainConfigNames::ActionFilteredLogs );
344 if ( isset( $actions[$type] ) ) {
345 // log type can be filtered by actions
346 if ( $action !== '' && isset( $actions[$type][$action] ) ) {
347 // add condition to query
348 $this->mConds['log_action'] = $actions[$type][$action];
349 $this->action = $action;
350 }
351 }
352 }
353
358 protected function limitLogId( $logId ) {
359 if ( !$logId ) {
360 return;
361 }
362 $this->mConds['log_id'] = $logId;
363 }
364
370 public function getQueryInfo() {
371 $queryBuilder = DatabaseLogEntry::newSelectQueryBuilder( $this->mDb )
372 ->where( $this->mConds );
373
374 # Add log_search table if there are conditions on it.
375 # This filters the results to only include log rows that have
376 # log_search records with the specified ls_field and ls_value values.
377 if ( array_key_exists( 'ls_field', $this->mConds ) ) {
378 $queryBuilder->join( 'log_search', null, 'ls_log_id=log_id' );
379 $queryBuilder->ignoreIndex( [ 'log_search' => 'ls_log_id' ] );
380 $queryBuilder->useIndex( [ 'logging' => 'PRIMARY' ] );
381 if ( !$this->hasEqualsClause( 'ls_field' )
382 || !$this->hasEqualsClause( 'ls_value' )
383 ) {
384 # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
385 # to match a specific (ls_field,ls_value) tuple, then there will be
386 # no duplicate log rows. Otherwise, we need to remove the duplicates.
387 $queryBuilder->distinct();
388 }
389 } elseif ( array_key_exists( 'log_actor', $this->mConds ) ) {
390 // Optimizer doesn't pick the right index when a user has lots of log actions (T303089)
391 $index = 'log_actor_time';
392 foreach ( $this->getFilterParams() as $hide ) {
393 if ( !$hide ) {
394 $index = 'log_actor_type_time';
395 break;
396 }
397 }
398 $queryBuilder->useIndex( [ 'logging' => $index ] );
399 }
400
401 // T221458: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
402 // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
403 // Tell it not to reorder the query. But not when tag filtering or log_search was used, as it
404 // seems as likely to be harmed as helped in that case.
405 if ( $this->mTagFilter === '' && !array_key_exists( 'ls_field', $this->mConds ) ) {
406 $queryBuilder->straightJoinOption();
407 }
408
410 if ( $maxExecTime ) {
411 $queryBuilder->setMaxExecutionTime( $maxExecTime );
412 }
413
414 # Add ChangeTags filter query
415 MediaWikiServices::getInstance()->getChangeTagsStore()->modifyDisplayQueryBuilder(
416 $queryBuilder,
417 'logging',
418 $this->mTagFilter,
419 $this->mTagInvert
420 );
421
422 return $queryBuilder->getQueryInfo();
423 }
424
430 protected function hasEqualsClause( $field ) {
431 return (
432 array_key_exists( $field, $this->mConds ) &&
433 ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
434 );
435 }
436
437 public function getIndexField() {
438 return [ [ 'log_timestamp', 'log_id' ] ];
439 }
440
441 protected function doBatchLookups() {
442 $lb = $this->linkBatchFactory->newLinkBatch();
443 foreach ( $this->mResult as $row ) {
444 $lb->add( $row->log_namespace, $row->log_title );
445 $lb->add( NS_USER, $row->log_user_text );
446 $lb->add( NS_USER_TALK, $row->log_user_text );
447 $formatter = LogFormatter::newFromRow( $row );
448 foreach ( $formatter->getPreloadTitles() as $title ) {
449 $lb->addObj( $title );
450 }
451 }
452 $lb->execute();
453 }
454
455 public function formatRow( $row ) {
456 return $this->mLogEventsList->logLine( $row );
457 }
458
459 public function getType() {
460 return $this->types;
461 }
462
468 public function getPerformer() {
469 return $this->performer;
470 }
471
475 public function getPage() {
476 return $this->page;
477 }
478
482 public function getPattern() {
483 return $this->pattern;
484 }
485
486 public function getYear() {
487 return $this->mYear;
488 }
489
490 public function getMonth() {
491 return $this->mMonth;
492 }
493
494 public function getDay() {
495 return $this->mDay;
496 }
497
498 public function getTagFilter() {
499 return $this->mTagFilter;
500 }
501
502 public function getTagInvert() {
503 return $this->mTagInvert;
504 }
505
506 public function getAction() {
507 return $this->action;
508 }
509
513 private function enforceActionRestrictions() {
514 if ( $this->actionRestrictionsEnforced ) {
515 return;
516 }
517 $this->actionRestrictionsEnforced = true;
518 if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
519 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_ACTION ) . ' = 0';
520 } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
521 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_ACTION ) .
522 ' != ' . LogPage::SUPPRESSED_USER;
523 }
524 }
525
529 private function enforcePerformerRestrictions() {
530 // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
531 if ( $this->performerRestrictionsEnforced ) {
532 return;
533 }
534 $this->performerRestrictionsEnforced = true;
535 if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
536 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_USER ) . ' = 0';
537 } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
538 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_USER ) .
540 }
541 }
542}
543
545class_alias( LogPager::class, 'LogPager' );
const NS_USER
Definition Defines.php:67
const NS_USER_TALK
Definition Defines.php:68
array $params
The job parameters.
A value class to process existing log entries.
static getExcludeClause( $db, $audience='public', Authority $performer=null)
SQL clause to skip forbidden log types for this user.
Implements the default log formatting.
Class to simplify the use of log pages.
Definition LogPage.php:45
const SUPPRESSED_ACTION
Definition LogPage.php:53
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:437
getDefaultQuery()
Get an array of query parameters that should be put into self-links.
Definition LogPager.php:132
getPerformer()
Guaranteed to either return a valid title string or a Zero-Length String.
Definition LogPager.php:468
__construct( $list, $types=[], $performer='', $page='', $pattern=false, $conds=[], $year=false, $month=false, $day=false, $tagFilter='', $action='', $logId=0, LinkBatchFactory $linkBatchFactory=null, ActorNormalization $actorNormalization=null, $tagInvert=false)
Definition LogPager.php:104
limitLogId( $logId)
Limit to the (single) specified log ID.
Definition LogPager.php:358
formatRow( $row)
Returns an HTML string representing the result row $row.
Definition LogPager.php:455
hasEqualsClause( $field)
Checks if $this->mConds has $field matched to a single value.
Definition LogPager.php:430
LogEventsList $mLogEventsList
Definition LogPager.php:79
doBatchLookups()
Called from getBody(), before getStartBody() is called and after doQuery() was called.
Definition LogPager.php:441
getQueryInfo()
Constructs the most part of the query.
Definition LogPager.php:370
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:79
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.