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