MediaWiki  master
LogPager.php
Go to the documentation of this file.
1 <?php
27 
33  private $types = [];
34 
36  private $performer = '';
37 
39  private $title = '';
40 
42  private $pattern = false;
43 
45  private $typeCGI = '';
46 
48  private $action = '';
49 
52 
54  private $actionRestrictionsEnforced = false;
55 
57  private $mConds;
58 
60  private $mTagFilter;
61 
64 
79  public function __construct( $list, $types = [], $performer = '', $title = '',
80  $pattern = false, $conds = [], $year = false, $month = false, $day = false,
81  $tagFilter = '', $action = '', $logId = 0
82  ) {
83  parent::__construct( $list->getContext() );
84  $this->mConds = $conds;
85 
86  $this->mLogEventsList = $list;
87 
88  $this->limitType( $types ); // also excludes hidden types
89  $this->limitLogId( $logId );
90  $this->limitFilterTypes();
91  $this->limitPerformer( $performer );
92  $this->limitTitle( $title, $pattern );
93  $this->limitAction( $action );
94  $this->getDateCond( $year, $month, $day );
95  $this->mTagFilter = $tagFilter;
96 
97  $this->mDb = wfGetDB( DB_REPLICA, 'logpager' );
98  }
99 
100  public function getDefaultQuery() {
101  $query = parent::getDefaultQuery();
102  $query['type'] = $this->typeCGI; // arrays won't work here
103  $query['user'] = $this->performer;
104  $query['day'] = $this->mDay;
105  $query['month'] = $this->mMonth;
106  $query['year'] = $this->mYear;
107 
108  return $query;
109  }
110 
111  private function limitFilterTypes() {
112  if ( $this->hasEqualsClause( 'log_id' ) ) { // T220834
113  return;
114  }
115  $filterTypes = $this->getFilterParams();
116  foreach ( $filterTypes as $type => $hide ) {
117  if ( $hide ) {
118  $this->mConds[] = 'log_type != ' . $this->mDb->addQuotes( $type );
119  }
120  }
121  }
122 
123  public function getFilterParams() {
124  global $wgFilterLogTypes;
125  $filters = [];
126  if ( count( $this->types ) ) {
127  return $filters;
128  }
129 
130  $wpfilters = $this->getRequest()->getArray( "wpfilters" );
131  $request_filters = $wpfilters === null ? [] : $wpfilters;
132 
133  foreach ( $wgFilterLogTypes as $type => $default ) {
134  $hide = !in_array( $type, $request_filters );
135 
136  // Back-compat: Check old URL params if the new param wasn't passed
137  if ( $wpfilters === null ) {
138  $hide = $this->getRequest()->getBool( "hide_{$type}_log", $default );
139  }
140 
141  $filters[$type] = $hide;
142  }
143 
144  return $filters;
145  }
146 
154  private function limitType( $types ) {
155  global $wgLogRestrictions;
156 
157  $user = $this->getUser();
158  // If $types is not an array, make it an array
159  $types = ( $types === '' ) ? [] : (array)$types;
160  // Don't even show header for private logs; don't recognize it...
161  $needReindex = false;
162  foreach ( $types as $type ) {
163  if ( isset( $wgLogRestrictions[$type] )
164  && !MediaWikiServices::getInstance()
165  ->getPermissionManager()
166  ->userHasRight( $user, $wgLogRestrictions[$type] )
167  ) {
168  $needReindex = true;
169  $types = array_diff( $types, [ $type ] );
170  }
171  }
172  if ( $needReindex ) {
173  // Lots of this code makes assumptions that
174  // the first entry in the array is $types[0].
175  $types = array_values( $types );
176  }
177  $this->types = $types;
178  // Don't show private logs to unprivileged users.
179  // Also, only show them upon specific request to avoid suprises.
180  $audience = $types ? 'user' : 'public';
181  $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience, $user );
182  if ( $hideLogs !== false ) {
183  $this->mConds[] = $hideLogs;
184  }
185  if ( count( $types ) ) {
186  $this->mConds['log_type'] = $types;
187  // Set typeCGI; used in url param for paging
188  if ( count( $types ) == 1 ) {
189  $this->typeCGI = $types[0];
190  }
191  }
192  }
193 
200  private function limitPerformer( $name ) {
201  if ( $name == '' ) {
202  return;
203  }
204  $usertitle = Title::makeTitleSafe( NS_USER, $name );
205  if ( is_null( $usertitle ) ) {
206  return;
207  }
208  // Normalize username first so that non-existent users used
209  // in maintenance scripts work
210  $name = $usertitle->getText();
211 
212  // Assume no joins required for log_user
213  $this->mConds[] = ActorMigration::newMigration()->getWhere(
214  wfGetDB( DB_REPLICA ), 'log_user', User::newFromName( $name, false )
215  )['conds'];
216 
218 
219  $this->performer = $name;
220  }
221 
230  private function limitTitle( $page, $pattern ) {
232 
233  if ( $page instanceof Title ) {
234  $title = $page;
235  } else {
236  $title = Title::newFromText( $page );
237  if ( strlen( $page ) == 0 || !$title instanceof Title ) {
238  return;
239  }
240  }
241 
242  $this->title = $title->getPrefixedText();
243  $ns = $title->getNamespace();
244  $db = $this->mDb;
245 
246  $doUserRightsLogLike = false;
247  if ( $this->types == [ 'rights' ] ) {
248  $parts = explode( $wgUserrightsInterwikiDelimiter, $title->getDBkey() );
249  if ( count( $parts ) == 2 ) {
250  list( $name, $database ) = array_map( 'trim', $parts );
251  if ( strstr( $database, '*' ) ) { // Search for wildcard in database name
252  $doUserRightsLogLike = true;
253  }
254  }
255  }
256 
270  $this->mConds['log_namespace'] = $ns;
271  if ( $doUserRightsLogLike ) {
272  $params = [ $name . $wgUserrightsInterwikiDelimiter ];
273  foreach ( explode( '*', $database ) as $databasepart ) {
274  $params[] = $databasepart;
275  $params[] = $db->anyString();
276  }
277  array_pop( $params ); // Get rid of the last % we added.
278  $this->mConds[] = 'log_title' . $db->buildLike( ...$params );
279  } elseif ( $pattern && !$wgMiserMode ) {
280  $this->mConds[] = 'log_title' . $db->buildLike( $title->getDBkey(), $db->anyString() );
281  $this->pattern = $pattern;
282  } else {
283  $this->mConds['log_title'] = $title->getDBkey();
284  }
285  $this->enforceActionRestrictions();
286  }
287 
293  private function limitAction( $action ) {
294  global $wgActionFilteredLogs;
295  // Allow to filter the log by actions
297  if ( $type === '' ) {
298  // nothing to do
299  return;
300  }
301  $actions = $wgActionFilteredLogs;
302  if ( isset( $actions[$type] ) ) {
303  // log type can be filtered by actions
304  $this->mLogEventsList->setAllowedActions( array_keys( $actions[$type] ) );
305  if ( $action !== '' && isset( $actions[$type][$action] ) ) {
306  // add condition to query
307  $this->mConds['log_action'] = $actions[$type][$action];
308  $this->action = $action;
309  }
310  }
311  }
312 
317  protected function limitLogId( $logId ) {
318  if ( !$logId ) {
319  return;
320  }
321  $this->mConds['log_id'] = $logId;
322  }
323 
329  public function getQueryInfo() {
331 
332  $tables = $basic['tables'];
333  $fields = $basic['fields'];
334  $conds = $basic['conds'];
335  $options = $basic['options'];
336  $joins = $basic['join_conds'];
337 
338  # Add log_search table if there are conditions on it.
339  # This filters the results to only include log rows that have
340  # log_search records with the specified ls_field and ls_value values.
341  if ( array_key_exists( 'ls_field', $this->mConds ) ) {
342  $tables[] = 'log_search';
343  $options['IGNORE INDEX'] = [ 'log_search' => 'ls_log_id' ];
344  $options['USE INDEX'] = [ 'logging' => 'PRIMARY' ];
345  if ( !$this->hasEqualsClause( 'ls_field' )
346  || !$this->hasEqualsClause( 'ls_value' )
347  ) {
348  # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
349  # to match a specific (ls_field,ls_value) tuple, then there will be
350  # no duplicate log rows. Otherwise, we need to remove the duplicates.
351  $options[] = 'DISTINCT';
352  }
353  }
354  # Don't show duplicate rows when using log_search
355  $joins['log_search'] = [ 'JOIN', 'ls_log_id=log_id' ];
356 
357  // T221458: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
358  // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
359  // Tell it not to reorder the query. But not when tag filtering or log_search was used, as it
360  // seems as likely to be harmed as helped in that case.
361  if ( !$this->mTagFilter && !array_key_exists( 'ls_field', $this->mConds ) ) {
362  $options[] = 'STRAIGHT_JOIN';
363  }
364  if ( $this->performer !== '' ) {
365  // T223151: MariaDB's optimizer, at least 10.1, likes to choose a wildly bad plan for
366  // some reason for this code path. Tell it not to use the wrong index it wants to pick.
367  $options['IGNORE INDEX'] = [ 'logging' => [ 'times' ] ];
368  }
369 
370  $info = [
371  'tables' => $tables,
372  'fields' => $fields,
373  'conds' => array_merge( $conds, $this->mConds ),
374  'options' => $options,
375  'join_conds' => $joins,
376  ];
377  # Add ChangeTags filter query
378  ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
379  $info['join_conds'], $info['options'], $this->mTagFilter );
380 
381  return $info;
382  }
383 
389  protected function hasEqualsClause( $field ) {
390  return (
391  array_key_exists( $field, $this->mConds ) &&
392  ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
393  );
394  }
395 
396  function getIndexField() {
397  return 'log_timestamp';
398  }
399 
400  protected function getStartBody() {
401  # Do a link batch query
402  if ( $this->getNumRows() > 0 ) {
403  $lb = new LinkBatch;
404  foreach ( $this->mResult as $row ) {
405  $lb->add( $row->log_namespace, $row->log_title );
406  $lb->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) );
407  $lb->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->user_name ) );
408  $formatter = LogFormatter::newFromRow( $row );
409  foreach ( $formatter->getPreloadTitles() as $title ) {
410  $lb->addObj( $title );
411  }
412  }
413  $lb->execute();
414  $this->mResult->seek( 0 );
415  }
416 
417  return '';
418  }
419 
420  public function formatRow( $row ) {
421  return $this->mLogEventsList->logLine( $row );
422  }
423 
424  public function getType() {
425  return $this->types;
426  }
427 
433  public function getPerformer() {
434  return $this->performer;
435  }
436 
440  public function getPage() {
441  return $this->title;
442  }
443 
447  public function getPattern() {
448  return $this->pattern;
449  }
450 
451  public function getYear() {
452  return $this->mYear;
453  }
454 
455  public function getMonth() {
456  return $this->mMonth;
457  }
458 
459  public function getDay() {
460  return $this->mDay;
461  }
462 
463  public function getTagFilter() {
464  return $this->mTagFilter;
465  }
466 
467  public function getAction() {
468  return $this->action;
469  }
470 
471  public function doQuery() {
472  // Workaround MySQL optimizer bug
473  $this->mDb->setBigSelects();
474  parent::doQuery();
475  $this->mDb->setBigSelects( 'default' );
476  }
477 
481  private function enforceActionRestrictions() {
482  if ( $this->actionRestrictionsEnforced ) {
483  return;
484  }
485  $this->actionRestrictionsEnforced = true;
486  $user = $this->getUser();
487  $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
488  if ( !$permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
489  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_ACTION ) . ' = 0';
490  } elseif ( !$permissionManager->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' ) ) {
491  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_ACTION ) .
492  ' != ' . LogPage::SUPPRESSED_USER;
493  }
494  }
495 
499  private function enforcePerformerRestrictions() {
500  // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
501  if ( $this->performerRestrictionsEnforced ) {
502  return;
503  }
504  $this->performerRestrictionsEnforced = true;
505  $user = $this->getUser();
506  $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
507  if ( !$permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
508  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_USER ) . ' = 0';
509  } elseif ( !$permissionManager->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' ) ) {
510  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_USER ) .
512  }
513  }
514 }
getPerformer()
Guaranteed to either return a valid title string or a Zero-Length String.
Definition: LogPager.php:433
static modifyDisplayQuery(&$tables, &$fields, &$conds, &$join_conds, &$options, $filter_tag='')
Applies all tags-related changes to a query.
Definition: ChangeTags.php:772
add( $ns, $dbkey)
Definition: LinkBatch.php:83
getFilterParams()
Definition: LogPager.php:123
bool $pattern
Definition: LogPager.php:42
bool $performerRestrictionsEnforced
Definition: LogPager.php:51
getPattern()
Definition: LogPager.php:447
bool $actionRestrictionsEnforced
Definition: LogPager.php:54
getQueryInfo()
Constructs the most part of the query.
Definition: LogPager.php:329
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Efficient paging for SQL queries.
string $action
Definition: LogPager.php:48
getDefaultQuery()
Definition: LogPager.php:100
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1858
$wgLogRestrictions
This restricts log access to those who have a certain right Users without this will not see it in the...
const SUPPRESSED_ACTION
Definition: LogPage.php:41
limitPerformer( $name)
Set the log reader to return only entries by the given user.
Definition: LogPager.php:200
LogEventsList $mLogEventsList
Definition: LogPager.php:63
getAction()
Definition: LogPager.php:467
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:34
__construct( $list, $types=[], $performer='', $title='', $pattern=false, $conds=[], $year=false, $month=false, $day=false, $tagFilter='', $action='', $logId=0)
Definition: LogPager.php:79
string Title $title
Events limited to those about Title when set.
Definition: LogPager.php:39
static newMigration()
Static constructor.
IDatabase $mDb
Definition: IndexPager.php:96
getDBkey()
Get the main part with underscores.
Definition: Title.php:1016
$wgActionFilteredLogs
List of log types that can be filtered by action types.
limitAction( $action)
Set the log_action field to a specified value (or values)
Definition: LogPager.php:293
formatRow( $row)
Definition: LogPager.php:420
getIndexField()
Definition: LogPager.php:396
$wgMiserMode
Disable database-intensive features.
getStartBody()
Definition: LogPager.php:400
getNamespace()
Get the namespace index, i.e.
Definition: Title.php:1040
static newFromRow( $row)
Handy shortcut for constructing a formatter directly from database row.
getTagFilter()
Definition: LogPager.php:463
static getSelectQueryData()
Returns array of information that is needed for querying log entries.
limitTitle( $page, $pattern)
Set the log reader to return only entries affecting the given page.
Definition: LogPager.php:230
const DELETED_USER
Definition: LogPage.php:36
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:612
const SUPPRESSED_USER
Definition: LogPage.php:40
limitType( $types)
Set the log reader to return only entries of the given type.
Definition: LogPager.php:154
array $mConds
Definition: LogPager.php:57
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...
enforceActionRestrictions()
Paranoia: avoid brute force searches (T19342)
Definition: LogPager.php:481
static getExcludeClause( $db, $audience='public', User $user=null)
SQL clause to skip forbidden log types for this user.
string $mTagFilter
Definition: LogPager.php:60
string $performer
Events limited to those by performer when set.
Definition: LogPager.php:36
limitFilterTypes()
Definition: LogPager.php:111
const DB_REPLICA
Definition: defines.php:25
hasEqualsClause( $field)
Checks if $this->mConds has $field matched to a single value.
Definition: LogPager.php:389
string $typeCGI
Definition: LogPager.php:45
$wgUserrightsInterwikiDelimiter
Character used as a delimiter when testing for interwiki userrights (In Special:UserRights, it is possible to modify users on different databases if the delimiter is used, e.g.
const DELETED_ACTION
Definition: LogPage.php:34
limitLogId( $logId)
Limit to the (single) specified log ID.
Definition: LogPager.php:317
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:515
enforcePerformerRestrictions()
Paranoia: avoid brute force searches (T19342)
Definition: LogPager.php:499
const NS_USER_TALK
Definition: Defines.php:63
getMonth()
Definition: LogPager.php:455
array $types
Log types.
Definition: LogPager.php:33
$wgFilterLogTypes
Show/hide links on Special:Log will be shown for these log types.
getNumRows()
Get the number of rows in the result set.
Definition: IndexPager.php:607
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:319