MediaWiki REL1_39
LogPager.php
Go to the documentation of this file.
1<?php
32
38 private $types = [];
39
41 private $performer = '';
42
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
69
71 private $linkBatchFactory;
72
74 private $actorNormalization;
75
93 public function __construct( $list, $types = [], $performer = '', $page = '',
94 $pattern = false, $conds = [], $year = false, $month = false, $day = false,
95 $tagFilter = '', $action = '', $logId = 0,
96 LinkBatchFactory $linkBatchFactory = null,
97 ILoadBalancer $loadBalancer = null,
98 ActorNormalization $actorNormalization = null
99 ) {
100 $services = MediaWikiServices::getInstance();
101 // Set database before parent constructor to avoid setting it there with wfGetDB
102 $this->mDb = ( $loadBalancer ?? $services->getDBLoadBalancer() )
103 ->getConnectionRef( ILoadBalancer::DB_REPLICA, 'logpager' );
104 parent::__construct( $list->getContext() );
105 $this->mConds = $conds;
106
107 $this->mLogEventsList = $list;
108
109 // Class is used directly in extensions - T266480
110 $this->linkBatchFactory = $linkBatchFactory ?? $services->getLinkBatchFactory();
111 $this->actorNormalization = $actorNormalization ?? $services->getActorNormalization();
112
113 $this->limitLogId( $logId ); // set before types per T269761
114 $this->limitType( $types ); // also excludes hidden types
115 $this->limitFilterTypes();
116 $this->limitPerformer( $performer );
117 $this->limitTitle( $page, $pattern );
118 $this->limitAction( $action );
119 $this->getDateCond( $year, $month, $day );
120 $this->mTagFilter = (string)$tagFilter;
121 }
122
123 public function getDefaultQuery() {
124 $query = parent::getDefaultQuery();
125 $query['type'] = $this->typeCGI; // arrays won't work here
126 $query['user'] = $this->performer;
127 $query['day'] = $this->mDay;
128 $query['month'] = $this->mMonth;
129 $query['year'] = $this->mYear;
130
131 return $query;
132 }
133
134 private function limitFilterTypes() {
135 if ( $this->hasEqualsClause( 'log_id' ) ) { // T220834
136 return;
137 }
138 $filterTypes = $this->getFilterParams();
139 foreach ( $filterTypes as $type => $hide ) {
140 if ( $hide ) {
141 $this->mConds[] = 'log_type != ' . $this->mDb->addQuotes( $type );
142 }
143 }
144 }
145
146 public function getFilterParams() {
147 $filters = [];
148 if ( count( $this->types ) ) {
149 return $filters;
150 }
151
152 $wpfilters = $this->getRequest()->getArray( "wpfilters" );
153 $filterLogTypes = $this->getConfig()->get( MainConfigNames::FilterLogTypes );
154
155 foreach ( $filterLogTypes as $type => $default ) {
156 // Back-compat: Check old URL params if the new param wasn't passed
157 if ( $wpfilters === null ) {
158 $hide = $this->getRequest()->getBool( "hide_{$type}_log", $default );
159 } else {
160 $hide = !in_array( $type, $wpfilters );
161 }
162
163 $filters[$type] = $hide;
164 }
165
166 return $filters;
167 }
168
176 private function limitType( $types ) {
177 $restrictions = $this->getConfig()->get( MainConfigNames::LogRestrictions );
178 // If $types is not an array, make it an array
179 $types = ( $types === '' ) ? [] : (array)$types;
180 // Don't even show header for private logs; don't recognize it...
181 $needReindex = false;
182 foreach ( $types as $type ) {
183 if ( isset( $restrictions[$type] )
184 && !$this->getAuthority()->isAllowed( $restrictions[$type] )
185 ) {
186 $needReindex = true;
187 $types = array_diff( $types, [ $type ] );
188 }
189 }
190 if ( $needReindex ) {
191 // Lots of this code makes assumptions that
192 // the first entry in the array is $types[0].
193 $types = array_values( $types );
194 }
195 $this->types = $types;
196 // Don't show private logs to unprivileged users.
197 // Also, only show them upon specific request to avoid surprises.
198 // Exception: if we are showing only a single log entry based on the log id,
199 // we don't require that "specific request" so that the links-in-logs feature
200 // works. See T269761
201 $audience = ( $types || $this->hasEqualsClause( 'log_id' ) ) ? 'user' : 'public';
202 $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience, $this->getAuthority() );
203 if ( $hideLogs !== false ) {
204 $this->mConds[] = $hideLogs;
205 }
206 if ( count( $types ) ) {
207 $this->mConds['log_type'] = $types;
208 // Set typeCGI; used in url param for paging
209 if ( count( $types ) == 1 ) {
210 $this->typeCGI = $types[0];
211 }
212 }
213 }
214
221 private function limitPerformer( $name ) {
222 if ( $name == '' ) {
223 return;
224 }
225
226 $actorId = $this->actorNormalization->findActorIdByName( $name, $this->mDb );
227
228 if ( !$actorId ) {
229 // Unknown user, match nothing.
230 $this->mConds[] = '1 = 0';
231 return;
232 }
233
234 $this->mConds[ 'log_actor' ] = $actorId;
235
236 $this->enforcePerformerRestrictions();
237
238 $this->performer = $name;
239 }
240
249 private function limitTitle( $page, $pattern ) {
250 if ( !$page instanceof PageReference ) {
251 // NOTE: For some types of logs, the title may be something strange, like "User:#12345"!
252 $page = Title::newFromText( $page );
253 if ( !$page ) {
254 return;
255 }
256 }
257
258 $titleFormatter = MediaWikiServices::getInstance()->getTitleFormatter();
259 $this->page = $titleFormatter->getPrefixedDBkey( $page );
260 $ns = $page->getNamespace();
261 $db = $this->mDb;
262
263 $interwikiDelimiter = $this->getConfig()->get( MainConfigNames::UserrightsInterwikiDelimiter );
264
265 $doUserRightsLogLike = false;
266 if ( $this->types == [ 'rights' ] ) {
267 $parts = explode( $interwikiDelimiter, $page->getDBkey() );
268 if ( count( $parts ) == 2 ) {
269 list( $name, $database ) = array_map( 'trim', $parts );
270 if ( strstr( $database, '*' ) ) { // Search for wildcard in database name
271 $doUserRightsLogLike = true;
272 }
273 }
274 }
275
289 $this->mConds['log_namespace'] = $ns;
290 if ( $doUserRightsLogLike ) {
291 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable $name is set when reached here
292 $params = [ $name . $interwikiDelimiter ];
293 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable $database is set when reached here
294 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal $database is set when reached here
295 $databaseParts = explode( '*', $database );
296 $databasePartCount = count( $databaseParts );
297 foreach ( $databaseParts as $i => $databasepart ) {
298 $params[] = $databasepart;
299 if ( $i < $databasePartCount - 1 ) {
300 $params[] = $db->anyString();
301 }
302 }
303 $this->mConds[] = 'log_title' . $db->buildLike( ...$params );
304 } elseif ( $pattern && !$this->getConfig()->get( MainConfigNames::MiserMode ) ) {
305 $this->mConds[] = 'log_title' . $db->buildLike( $page->getDBkey(), $db->anyString() );
306 $this->pattern = $pattern;
307 } else {
308 $this->mConds['log_title'] = $page->getDBkey();
309 }
310 $this->enforceActionRestrictions();
311 }
312
318 private function limitAction( $action ) {
319 // Allow to filter the log by actions
320 $type = $this->typeCGI;
321 if ( $type === '' ) {
322 // nothing to do
323 return;
324 }
325 $actions = $this->getConfig()->get( MainConfigNames::ActionFilteredLogs );
326 if ( isset( $actions[$type] ) ) {
327 // log type can be filtered by actions
328 $this->mLogEventsList->setAllowedActions( array_keys( $actions[$type] ) );
329 if ( $action !== '' && isset( $actions[$type][$action] ) ) {
330 // add condition to query
331 $this->mConds['log_action'] = $actions[$type][$action];
332 $this->action = $action;
333 }
334 }
335 }
336
341 protected function limitLogId( $logId ) {
342 if ( !$logId ) {
343 return;
344 }
345 $this->mConds['log_id'] = $logId;
346 }
347
353 public function getQueryInfo() {
354 $basic = DatabaseLogEntry::getSelectQueryData();
355
356 $tables = $basic['tables'];
357 $fields = $basic['fields'];
358 $conds = $basic['conds'];
359 $options = $basic['options'];
360 $joins = $basic['join_conds'];
361
362 # Add log_search table if there are conditions on it.
363 # This filters the results to only include log rows that have
364 # log_search records with the specified ls_field and ls_value values.
365 if ( array_key_exists( 'ls_field', $this->mConds ) ) {
366 $tables[] = 'log_search';
367 $options['IGNORE INDEX'] = [ 'log_search' => 'ls_log_id' ];
368 $options['USE INDEX'] = [ 'logging' => 'PRIMARY' ];
369 if ( !$this->hasEqualsClause( 'ls_field' )
370 || !$this->hasEqualsClause( 'ls_value' )
371 ) {
372 # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
373 # to match a specific (ls_field,ls_value) tuple, then there will be
374 # no duplicate log rows. Otherwise, we need to remove the duplicates.
375 $options[] = 'DISTINCT';
376 }
377 } elseif ( array_key_exists( 'log_actor', $this->mConds ) ) {
378 // Optimizer doesn't pick the right index when a user has lots of log actions (T303089)
379 $index = 'log_actor_time';
380 foreach ( $this->getFilterParams() as $type => $hide ) {
381 if ( !$hide ) {
382 $index = 'log_actor_type_time';
383 break;
384 }
385 }
386 $options['USE INDEX'] = [ 'logging' => $index ];
387 }
388 # Don't show duplicate rows when using log_search
389 $joins['log_search'] = [ 'JOIN', 'ls_log_id=log_id' ];
390
391 // T221458: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
392 // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
393 // Tell it not to reorder the query. But not when tag filtering or log_search was used, as it
394 // seems as likely to be harmed as helped in that case.
395 if ( $this->mTagFilter === '' && !array_key_exists( 'ls_field', $this->mConds ) ) {
396 $options[] = 'STRAIGHT_JOIN';
397 }
398
399 $options['MAX_EXECUTION_TIME'] = $this->getConfig()
400 ->get( MainConfigNames::MaxExecutionTimeForExpensiveQueries );
401
402 $info = [
403 'tables' => $tables,
404 'fields' => $fields,
405 'conds' => array_merge( $conds, $this->mConds ),
406 'options' => $options,
407 'join_conds' => $joins,
408 ];
409 # Add ChangeTags filter query
410 ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
411 $info['join_conds'], $info['options'], $this->mTagFilter );
412
413 return $info;
414 }
415
421 protected function hasEqualsClause( $field ) {
422 return (
423 array_key_exists( $field, $this->mConds ) &&
424 ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
425 );
426 }
427
428 public function getIndexField() {
429 return 'log_timestamp';
430 }
431
432 protected function getStartBody() {
433 # Do a link batch query
434 if ( $this->getNumRows() > 0 ) {
435 $lb = $this->linkBatchFactory->newLinkBatch();
436 foreach ( $this->mResult as $row ) {
437 $lb->add( $row->log_namespace, $row->log_title );
438 $lb->add( NS_USER, $row->log_user_text );
439 $lb->add( NS_USER_TALK, $row->log_user_text );
440 $formatter = LogFormatter::newFromRow( $row );
441 foreach ( $formatter->getPreloadTitles() as $title ) {
442 $lb->addObj( $title );
443 }
444 }
445 $lb->execute();
446 $this->mResult->seek( 0 );
447 }
448
449 return '';
450 }
451
452 public function formatRow( $row ) {
453 return $this->mLogEventsList->logLine( $row );
454 }
455
456 public function getType() {
457 return $this->types;
458 }
459
465 public function getPerformer() {
466 return $this->performer;
467 }
468
472 public function getPage() {
473 return $this->page;
474 }
475
479 public function getPattern() {
480 return $this->pattern;
481 }
482
483 public function getYear() {
484 return $this->mYear;
485 }
486
487 public function getMonth() {
488 return $this->mMonth;
489 }
490
491 public function getDay() {
492 return $this->mDay;
493 }
494
495 public function getTagFilter() {
496 return $this->mTagFilter;
497 }
498
499 public function getAction() {
500 return $this->action;
501 }
502
503 public function doQuery() {
504 // Workaround MySQL optimizer bug
505 $this->mDb->setBigSelects();
506 parent::doQuery();
507 $this->mDb->setBigSelects( 'default' );
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 ) .
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}
const NS_USER
Definition Defines.php:66
const NS_USER_TALK
Definition Defines.php:67
static modifyDisplayQuery(&$tables, &$fields, &$conds, &$join_conds, &$options, $filter_tag='', bool $exclude=false)
Applies all tags-related changes to a query.
IDatabase $mDb
getNumRows()
Get the number of rows in the result set.
static getExcludeClause( $db, $audience='public', Authority $performer=null)
SQL clause to skip forbidden log types for this user.
const SUPPRESSED_USER
Definition LogPage.php:46
const DELETED_USER
Definition LogPage.php:42
const DELETED_ACTION
Definition LogPage.php:40
const SUPPRESSED_ACTION
Definition LogPage.php:47
hasEqualsClause( $field)
Checks if $this->mConds has $field matched to a single value.
Definition LogPager.php:421
formatRow( $row)
Returns an HTML string representing the result row $row.
Definition LogPager.php:452
getStartBody()
Hook into getBody(), allows text to be inserted at the start.
Definition LogPager.php:432
limitLogId( $logId)
Limit to the (single) specified log ID.
Definition LogPager.php:341
getFilterParams()
Definition LogPager.php:146
getDefaultQuery()
Get an array of query parameters that should be put into self-links.
Definition LogPager.php:123
getTagFilter()
Definition LogPager.php:495
LogEventsList $mLogEventsList
Definition LogPager.php:68
getQueryInfo()
Constructs the most part of the query.
Definition LogPager.php:353
doQuery()
Do the query, using information from the object context.
Definition LogPager.php:503
getPerformer()
Guaranteed to either return a valid title string or a Zero-Length String.
Definition LogPager.php:465
getIndexField()
Returns the name of the index field.
Definition LogPager.php:428
__construct( $list, $types=[], $performer='', $page='', $pattern=false, $conds=[], $year=false, $month=false, $day=false, $tagFilter='', $action='', $logId=0, LinkBatchFactory $linkBatchFactory=null, ILoadBalancer $loadBalancer=null, ActorNormalization $actorNormalization=null)
Definition LogPager.php:93
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Efficient paging for SQL queries.
getDateCond( $year, $month, $day=-1)
Set and return the mOffset timestamp such that we can get all revisions with a timestamp up to the sp...
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition Title.php:370
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
Service for dealing with the actor table.
Create and track the database connections and transactions for a given database cluster.