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