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