MediaWiki  master
LogPager.php
Go to the documentation of this file.
1 <?php
31 
37  private $types = [];
38 
40  private $performer = '';
41 
43  private $page = '';
44 
46  private $pattern = false;
47 
49  private $typeCGI = '';
50 
52  private $action = '';
53 
56 
58  private $actionRestrictionsEnforced = false;
59 
61  private $mConds;
62 
64  private $mTagFilter;
65 
68 
71 
74 
92  public function __construct( $list, $types = [], $performer = '', $page = '',
93  $pattern = false, $conds = [], $year = false, $month = false, $day = false,
94  $tagFilter = '', $action = '', $logId = 0,
96  ILoadBalancer $loadBalancer = null,
98  ) {
99  $services = MediaWikiServices::getInstance();
100  // Set database before parent constructor to avoid setting it there with wfGetDB
101  $this->mDb = ( $loadBalancer ?? $services->getDBLoadBalancer() )
102  ->getConnectionRef( ILoadBalancer::DB_REPLICA, 'logpager' );
103  parent::__construct( $list->getContext() );
104  $this->mConds = $conds;
105 
106  $this->mLogEventsList = $list;
107 
108  // Class is used directly in extensions - T266480
109  $this->linkBatchFactory = $linkBatchFactory ?? $services->getLinkBatchFactory();
110  $this->actorNormalization = $actorNormalization ?? $services->getActorNormalization();
111 
112  $this->limitLogId( $logId ); // set before types per T269761
113  $this->limitType( $types ); // also excludes hidden types
114  $this->limitFilterTypes();
115  $this->limitPerformer( $performer );
116  $this->limitTitle( $page, $pattern );
117  $this->limitAction( $action );
118  $this->getDateCond( $year, $month, $day );
119  $this->mTagFilter = $tagFilter;
120  }
121 
122  public function getDefaultQuery() {
123  $query = parent::getDefaultQuery();
124  $query['type'] = $this->typeCGI; // arrays won't work here
125  $query['user'] = $this->performer;
126  $query['day'] = $this->mDay;
127  $query['month'] = $this->mMonth;
128  $query['year'] = $this->mYear;
129 
130  return $query;
131  }
132 
133  private function limitFilterTypes() {
134  if ( $this->hasEqualsClause( 'log_id' ) ) { // T220834
135  return;
136  }
137  $filterTypes = $this->getFilterParams();
138  foreach ( $filterTypes as $type => $hide ) {
139  if ( $hide ) {
140  $this->mConds[] = 'log_type != ' . $this->mDb->addQuotes( $type );
141  }
142  }
143  }
144 
145  public function getFilterParams() {
146  $filters = [];
147  if ( count( $this->types ) ) {
148  return $filters;
149  }
150 
151  $wpfilters = $this->getRequest()->getArray( "wpfilters" );
152  $filterLogTypes = $this->getConfig()->get( 'FilterLogTypes' );
153 
154  foreach ( $filterLogTypes as $type => $default ) {
155  // Back-compat: Check old URL params if the new param wasn't passed
156  if ( $wpfilters === null ) {
157  $hide = $this->getRequest()->getBool( "hide_{$type}_log", $default );
158  } else {
159  $hide = !in_array( $type, $wpfilters );
160  }
161 
162  $filters[$type] = $hide;
163  }
164 
165  return $filters;
166  }
167 
175  private function limitType( $types ) {
176  $user = $this->getUser();
177  $restrictions = $this->getConfig()->get( '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 suprises.
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, $user );
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 
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"!
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( '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  $params = [ $name . $interwikiDelimiter ];
292  foreach ( explode( '*', $database ) as $databasepart ) {
293  $params[] = $databasepart;
294  $params[] = $db->anyString();
295  }
296  array_pop( $params ); // Get rid of the last % we added.
297  $this->mConds[] = 'log_title' . $db->buildLike( ...$params );
298  } elseif ( $pattern && !$this->getConfig()->get( 'MiserMode' ) ) {
299  $this->mConds[] = 'log_title' . $db->buildLike( $page->getDBkey(), $db->anyString() );
300  $this->pattern = $pattern;
301  } else {
302  $this->mConds['log_title'] = $page->getDBkey();
303  }
304  $this->enforceActionRestrictions();
305  }
306 
312  private function limitAction( $action ) {
313  // Allow to filter the log by actions
315  if ( $type === '' ) {
316  // nothing to do
317  return;
318  }
319  $actions = $this->getConfig()->get( 'ActionFilteredLogs' );
320  if ( isset( $actions[$type] ) ) {
321  // log type can be filtered by actions
322  $this->mLogEventsList->setAllowedActions( array_keys( $actions[$type] ) );
323  if ( $action !== '' && isset( $actions[$type][$action] ) ) {
324  // add condition to query
325  $this->mConds['log_action'] = $actions[$type][$action];
326  $this->action = $action;
327  }
328  }
329  }
330 
335  protected function limitLogId( $logId ) {
336  if ( !$logId ) {
337  return;
338  }
339  $this->mConds['log_id'] = $logId;
340  }
341 
347  public function getQueryInfo() {
349 
350  $tables = $basic['tables'];
351  $fields = $basic['fields'];
352  $conds = $basic['conds'];
353  $options = $basic['options'];
354  $joins = $basic['join_conds'];
355 
356  # Add log_search table if there are conditions on it.
357  # This filters the results to only include log rows that have
358  # log_search records with the specified ls_field and ls_value values.
359  if ( array_key_exists( 'ls_field', $this->mConds ) ) {
360  $tables[] = 'log_search';
361  $options['IGNORE INDEX'] = [ 'log_search' => 'ls_log_id' ];
362  $options['USE INDEX'] = [ 'logging' => 'PRIMARY' ];
363  if ( !$this->hasEqualsClause( 'ls_field' )
364  || !$this->hasEqualsClause( 'ls_value' )
365  ) {
366  # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
367  # to match a specific (ls_field,ls_value) tuple, then there will be
368  # no duplicate log rows. Otherwise, we need to remove the duplicates.
369  $options[] = 'DISTINCT';
370  }
371  }
372  # Don't show duplicate rows when using log_search
373  $joins['log_search'] = [ 'JOIN', 'ls_log_id=log_id' ];
374 
375  // T221458: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
376  // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
377  // Tell it not to reorder the query. But not when tag filtering or log_search was used, as it
378  // seems as likely to be harmed as helped in that case.
379  if ( !$this->mTagFilter && !array_key_exists( 'ls_field', $this->mConds ) ) {
380  $options[] = 'STRAIGHT_JOIN';
381  }
382  if ( $this->performer !== '' || $this->types !== [] ) {
383  // Index being renamed
384  $index = $this->mDb->indexExists( 'logging', 'times', __METHOD__ ) ? 'times' : 'log_times';
385 
386  // T223151, T237026: MariaDB's optimizer, at least 10.1, likes to choose a wildly bad plan for
387  // some reason for these code paths. Tell it not to use the wrong index it wants to pick.
388  $options['IGNORE INDEX'] = [ 'logging' => [ $index ] ];
389  }
390 
391  $info = [
392  'tables' => $tables,
393  'fields' => $fields,
394  'conds' => array_merge( $conds, $this->mConds ),
395  'options' => $options,
396  'join_conds' => $joins,
397  ];
398  # Add ChangeTags filter query
399  ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
400  $info['join_conds'], $info['options'], $this->mTagFilter );
401 
402  return $info;
403  }
404 
410  protected function hasEqualsClause( $field ) {
411  return (
412  array_key_exists( $field, $this->mConds ) &&
413  ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
414  );
415  }
416 
417  public function getIndexField() {
418  return 'log_timestamp';
419  }
420 
421  protected function getStartBody() {
422  # Do a link batch query
423  if ( $this->getNumRows() > 0 ) {
424  $lb = $this->linkBatchFactory->newLinkBatch();
425  foreach ( $this->mResult as $row ) {
426  $lb->add( $row->log_namespace, $row->log_title );
427  $lb->add( NS_USER, $row->log_user_text );
428  $lb->add( NS_USER_TALK, $row->log_user_text );
429  $formatter = LogFormatter::newFromRow( $row );
430  foreach ( $formatter->getPreloadTitles() as $title ) {
431  $lb->addObj( $title );
432  }
433  }
434  $lb->execute();
435  $this->mResult->seek( 0 );
436  }
437 
438  return '';
439  }
440 
441  public function formatRow( $row ) {
442  return $this->mLogEventsList->logLine( $row );
443  }
444 
445  public function getType() {
446  return $this->types;
447  }
448 
454  public function getPerformer() {
455  return $this->performer;
456  }
457 
461  public function getPage() {
462  return $this->page;
463  }
464 
468  public function getPattern() {
469  return $this->pattern;
470  }
471 
472  public function getYear() {
473  return $this->mYear;
474  }
475 
476  public function getMonth() {
477  return $this->mMonth;
478  }
479 
480  public function getDay() {
481  return $this->mDay;
482  }
483 
484  public function getTagFilter() {
485  return $this->mTagFilter;
486  }
487 
488  public function getAction() {
489  return $this->action;
490  }
491 
492  public function doQuery() {
493  // Workaround MySQL optimizer bug
494  $this->mDb->setBigSelects();
495  parent::doQuery();
496  $this->mDb->setBigSelects( 'default' );
497  }
498 
502  private function enforceActionRestrictions() {
503  if ( $this->actionRestrictionsEnforced ) {
504  return;
505  }
506  $this->actionRestrictionsEnforced = true;
507  if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
508  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_ACTION ) . ' = 0';
509  } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
510  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_ACTION ) .
511  ' != ' . LogPage::SUPPRESSED_USER;
512  }
513  }
514 
518  private function enforcePerformerRestrictions() {
519  // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
520  if ( $this->performerRestrictionsEnforced ) {
521  return;
522  }
523  $this->performerRestrictionsEnforced = true;
524  if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
525  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_USER ) . ' = 0';
526  } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
527  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_USER ) .
529  }
530  }
531 }
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:72
ReverseChronologicalPager\getDateCond
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...
Definition: ReverseChronologicalPager.php:84
LogPage\SUPPRESSED_ACTION
const SUPPRESSED_ACTION
Definition: LogPage.php:46
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:385
LogPage\SUPPRESSED_USER
const SUPPRESSED_USER
Definition: LogPage.php:45
LogPager\$actorNormalization
ActorNormalization $actorNormalization
Definition: LogPager.php:73
LogPager\getPattern
getPattern()
Definition: LogPager.php:468
LogPager\getType
getType()
Definition: LogPager.php:445
LogPager\getPerformer
getPerformer()
Guaranteed to either return a valid title string or a Zero-Length String.
Definition: LogPager.php:454
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:180
LogPager\limitTitle
limitTitle( $page, $pattern)
Set the log reader to return only entries affecting the given page.
Definition: LogPager.php:249
LogPager\__construct
__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:92
ReverseChronologicalPager\$mMonth
int $mMonth
Definition: ReverseChronologicalPager.php:35
LogPager\getMonth
getMonth()
Definition: LogPager.php:476
LogPager\getFilterParams
getFilterParams()
Definition: LogPager.php:145
LogPager\$types
array $types
Log types.
Definition: LogPager.php:37
DatabaseLogEntry\getSelectQueryData
static getSelectQueryData()
Returns array of information that is needed for querying log entries.
Definition: DatabaseLogEntry.php:51
LogPager\getQueryInfo
getQueryInfo()
Constructs the most part of the query.
Definition: LogPager.php:347
LogPager\$performerRestrictionsEnforced
bool $performerRestrictionsEnforced
Definition: LogPager.php:55
LogPager
Definition: LogPager.php:35
LogEventsList\getExcludeClause
static getExcludeClause( $db, $audience='public', Authority $performer=null)
SQL clause to skip forbidden log types for this user.
Definition: LogEventsList.php:795
LogPager\$mConds
array $mConds
Definition: LogPager.php:61
ContextSource\getRequest
getRequest()
Definition: ContextSource.php:81
ContextSource\getUser
getUser()
Definition: ContextSource.php:136
Page\PageReference
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
Definition: PageReference.php:49
LogPager\$linkBatchFactory
LinkBatchFactory $linkBatchFactory
Definition: LogPager.php:70
LogPager\getPage
getPage()
Definition: LogPager.php:461
ChangeTags\modifyDisplayQuery
static modifyDisplayQuery(&$tables, &$fields, &$conds, &$join_conds, &$options, $filter_tag='')
Applies all tags-related changes to a query.
Definition: ChangeTags.php:878
LogPager\$action
string $action
Definition: LogPager.php:52
LogPager\formatRow
formatRow( $row)
Returns an HTML string representing the result row $row.
Definition: LogPager.php:441
LogFormatter\newFromRow
static newFromRow( $row)
Handy shortcut for constructing a formatter directly from database row.
Definition: LogFormatter.php:74
LogPager\getIndexField
getIndexField()
Returns the name of the index field.
Definition: LogPager.php:417
LogPager\limitFilterTypes
limitFilterTypes()
Definition: LogPager.php:133
LogPage\DELETED_USER
const DELETED_USER
Definition: LogPage.php:41
MediaWiki\Cache\LinkBatchFactory
Definition: LinkBatchFactory.php:39
IndexPager\$mDb
IDatabase $mDb
Definition: IndexPager.php:100
LogPager\$pattern
bool $pattern
Definition: LogPager.php:46
$title
$title
Definition: testCompression.php:38
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
LogPager\$actionRestrictionsEnforced
bool $actionRestrictionsEnforced
Definition: LogPager.php:58
LogEventsList
Definition: LogEventsList.php:33
LogPage\DELETED_ACTION
const DELETED_ACTION
Definition: LogPage.php:39
LogPager\$page
string $page
Events limited to those about this page when set.
Definition: LogPager.php:43
LogPager\getStartBody
getStartBody()
Hook into getBody(), allows text to be inserted at the start.
Definition: LogPager.php:421
ContextSource\getAuthority
getAuthority()
Definition: ContextSource.php:144
ReverseChronologicalPager\$mYear
int $mYear
Definition: ReverseChronologicalPager.php:33
LogPager\$mLogEventsList
LogEventsList $mLogEventsList
Definition: LogPager.php:67
LogPager\$typeCGI
string $typeCGI
Definition: LogPager.php:49
LogPager\doQuery
doQuery()
Do the query, using information from the object context.
Definition: LogPager.php:492
LogPager\getAction
getAction()
Definition: LogPager.php:488
LogPager\getTagFilter
getTagFilter()
Definition: LogPager.php:484
LogPager\$mTagFilter
string $mTagFilter
Definition: LogPager.php:64
NS_USER
const NS_USER
Definition: Defines.php:66
LogPager\$performer
string $performer
Events limited to those by performer when set.
Definition: LogPager.php:40
LogPager\limitType
limitType( $types)
Set the log reader to return only entries of the given type.
Definition: LogPager.php:175
LogPager\limitPerformer
limitPerformer( $name)
Set the log reader to return only entries by the given user.
Definition: LogPager.php:221
LogPager\hasEqualsClause
hasEqualsClause( $field)
Checks if $this->mConds has $field matched to a single value.
Definition: LogPager.php:410
LogPager\enforceActionRestrictions
enforceActionRestrictions()
Paranoia: avoid brute force searches (T19342)
Definition: LogPager.php:502
LogPager\getDefaultQuery
getDefaultQuery()
Get an array of query parameters that should be put into self-links.
Definition: LogPager.php:122
ReverseChronologicalPager\$mDay
int $mDay
Definition: ReverseChronologicalPager.php:37
LogPager\enforcePerformerRestrictions
enforcePerformerRestrictions()
Paranoia: avoid brute force searches (T19342)
Definition: LogPager.php:518
NS_USER_TALK
const NS_USER_TALK
Definition: Defines.php:67
LogPager\getDay
getDay()
Definition: LogPager.php:480
ReverseChronologicalPager
Efficient paging for SQL queries.
Definition: ReverseChronologicalPager.php:29
LogPager\limitAction
limitAction( $action)
Set the log_action field to a specified value (or values)
Definition: LogPager.php:312
Wikimedia\Rdbms\ILoadBalancer
Database cluster connection, tracking, load balancing, and transaction manager interface.
Definition: ILoadBalancer.php:81
IndexPager\getNumRows
getNumRows()
Get the number of rows in the result set.
Definition: IndexPager.php:731
LogPager\limitLogId
limitLogId( $logId)
Limit to the (single) specified log ID.
Definition: LogPager.php:335
MediaWiki\User\ActorNormalization
Service for dealing with the actor table.
Definition: ActorNormalization.php:32
LogPager\getYear
getYear()
Definition: LogPager.php:472
$type
$type
Definition: testCompression.php:52