MediaWiki  master
LogPager.php
Go to the documentation of this file.
1 <?php
31  private $types = [];
32 
34  private $performer = '';
35 
37  private $title = '';
38 
40  private $pattern = false;
41 
43  private $typeCGI = '';
44 
46  private $action = '';
47 
50 
52  private $actionRestrictionsEnforced = false;
53 
56 
71  public function __construct( $list, $types = [], $performer = '', $title = '',
72  $pattern = false, $conds = [], $year = false, $month = false, $day = false,
73  $tagFilter = '', $action = '', $logId = 0
74  ) {
75  parent::__construct( $list->getContext() );
76  $this->mConds = $conds;
77 
78  $this->mLogEventsList = $list;
79 
80  $this->limitType( $types ); // also excludes hidden types
81  $this->limitPerformer( $performer );
82  $this->limitTitle( $title, $pattern );
83  $this->limitAction( $action );
84  $this->getDateCond( $year, $month, $day );
85  $this->mTagFilter = $tagFilter;
86  $this->limitLogId( $logId );
87 
88  $this->mDb = wfGetDB( DB_REPLICA, 'logpager' );
89  }
90 
91  public function getDefaultQuery() {
92  $query = parent::getDefaultQuery();
93  $query['type'] = $this->typeCGI; // arrays won't work here
94  $query['user'] = $this->performer;
95  $query['day'] = $this->mDay;
96  $query['month'] = $this->mMonth;
97  $query['year'] = $this->mYear;
98 
99  return $query;
100  }
101 
102  // Call ONLY after calling $this->limitType() already!
103  public function getFilterParams() {
104  global $wgFilterLogTypes;
105  $filters = [];
106  if ( count( $this->types ) ) {
107  return $filters;
108  }
109 
110  $wpfilters = $this->getRequest()->getArray( "wpfilters" );
111  $request_filters = $wpfilters === null ? [] : $wpfilters;
112 
113  foreach ( $wgFilterLogTypes as $type => $default ) {
114  $hide = !in_array( $type, $request_filters );
115 
116  // Back-compat: Check old URL params if the new param wasn't passed
117  if ( $wpfilters === null ) {
118  $hide = $this->getRequest()->getBool( "hide_{$type}_log", $default );
119  }
120 
121  $filters[$type] = $hide;
122  if ( $hide ) {
123  $this->mConds[] = 'log_type != ' . $this->mDb->addQuotes( $type );
124  }
125  }
126 
127  return $filters;
128  }
129 
137  private function limitType( $types ) {
138  global $wgLogRestrictions;
139 
140  $user = $this->getUser();
141  // If $types is not an array, make it an array
142  $types = ( $types === '' ) ? [] : (array)$types;
143  // Don't even show header for private logs; don't recognize it...
144  $needReindex = false;
145  foreach ( $types as $type ) {
146  if ( isset( $wgLogRestrictions[$type] )
147  && !$user->isAllowed( $wgLogRestrictions[$type] )
148  ) {
149  $needReindex = true;
150  $types = array_diff( $types, [ $type ] );
151  }
152  }
153  if ( $needReindex ) {
154  // Lots of this code makes assumptions that
155  // the first entry in the array is $types[0].
156  $types = array_values( $types );
157  }
158  $this->types = $types;
159  // Don't show private logs to unprivileged users.
160  // Also, only show them upon specific request to avoid suprises.
161  $audience = $types ? 'user' : 'public';
162  $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience, $user );
163  if ( $hideLogs !== false ) {
164  $this->mConds[] = $hideLogs;
165  }
166  if ( count( $types ) ) {
167  $this->mConds['log_type'] = $types;
168  // Set typeCGI; used in url param for paging
169  if ( count( $types ) == 1 ) {
170  $this->typeCGI = $types[0];
171  }
172  }
173  }
174 
181  private function limitPerformer( $name ) {
182  if ( $name == '' ) {
183  return;
184  }
185  $usertitle = Title::makeTitleSafe( NS_USER, $name );
186  if ( is_null( $usertitle ) ) {
187  return;
188  }
189  // Normalize username first so that non-existent users used
190  // in maintenance scripts work
191  $name = $usertitle->getText();
192 
193  // Assume no joins required for log_user
194  $this->mConds[] = ActorMigration::newMigration()->getWhere(
195  wfGetDB( DB_REPLICA ), 'log_user', User::newFromName( $name, false )
196  )['conds'];
197 
199 
200  $this->performer = $name;
201  }
202 
211  private function limitTitle( $page, $pattern ) {
213 
214  if ( $page instanceof Title ) {
215  $title = $page;
216  } else {
217  $title = Title::newFromText( $page );
218  if ( strlen( $page ) == 0 || !$title instanceof Title ) {
219  return;
220  }
221  }
222 
223  $this->title = $title->getPrefixedText();
224  $ns = $title->getNamespace();
225  $db = $this->mDb;
226 
227  $doUserRightsLogLike = false;
228  if ( $this->types == [ 'rights' ] ) {
229  $parts = explode( $wgUserrightsInterwikiDelimiter, $title->getDBkey() );
230  if ( count( $parts ) == 2 ) {
231  list( $name, $database ) = array_map( 'trim', $parts );
232  if ( strstr( $database, '*' ) ) { // Search for wildcard in database name
233  $doUserRightsLogLike = true;
234  }
235  }
236  }
237 
251  $this->mConds['log_namespace'] = $ns;
252  if ( $doUserRightsLogLike ) {
254  foreach ( explode( '*', $database ) as $databasepart ) {
255  $params[] = $databasepart;
256  $params[] = $db->anyString();
257  }
258  array_pop( $params ); // Get rid of the last % we added.
259  $this->mConds[] = 'log_title' . $db->buildLike( $params );
260  } elseif ( $pattern && !$wgMiserMode ) {
261  $this->mConds[] = 'log_title' . $db->buildLike( $title->getDBkey(), $db->anyString() );
262  $this->pattern = $pattern;
263  } else {
264  $this->mConds['log_title'] = $title->getDBkey();
265  }
266  $this->enforceActionRestrictions();
267  }
268 
274  private function limitAction( $action ) {
275  global $wgActionFilteredLogs;
276  // Allow to filter the log by actions
278  if ( $type === '' ) {
279  // nothing to do
280  return;
281  }
282  $actions = $wgActionFilteredLogs;
283  if ( isset( $actions[$type] ) ) {
284  // log type can be filtered by actions
285  $this->mLogEventsList->setAllowedActions( array_keys( $actions[$type] ) );
286  if ( $action !== '' && isset( $actions[$type][$action] ) ) {
287  // add condition to query
288  $this->mConds['log_action'] = $actions[$type][$action];
289  $this->action = $action;
290  }
291  }
292  }
293 
298  protected function limitLogId( $logId ) {
299  if ( !$logId ) {
300  return;
301  }
302  $this->mConds['log_id'] = $logId;
303  }
304 
310  public function getQueryInfo() {
312 
313  $tables = $basic['tables'];
314  $fields = $basic['fields'];
315  $conds = $basic['conds'];
316  $options = $basic['options'];
317  $joins = $basic['join_conds'];
318 
319  # Add log_search table if there are conditions on it.
320  # This filters the results to only include log rows that have
321  # log_search records with the specified ls_field and ls_value values.
322  if ( array_key_exists( 'ls_field', $this->mConds ) ) {
323  $tables[] = 'log_search';
324  $options['IGNORE INDEX'] = [ 'log_search' => 'ls_log_id' ];
325  $options['USE INDEX'] = [ 'logging' => 'PRIMARY' ];
326  if ( !$this->hasEqualsClause( 'ls_field' )
327  || !$this->hasEqualsClause( 'ls_value' )
328  ) {
329  # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
330  # to match a specific (ls_field,ls_value) tuple, then there will be
331  # no duplicate log rows. Otherwise, we need to remove the duplicates.
332  $options[] = 'DISTINCT';
333  }
334  }
335  # Don't show duplicate rows when using log_search
336  $joins['log_search'] = [ 'JOIN', 'ls_log_id=log_id' ];
337 
338  // T221458: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
339  // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
340  // Tell it not to reorder the query. But not when tag filtering or log_search was used, as it
341  // seems as likely to be harmed as helped in that case.
342  if ( !$this->mTagFilter && !array_key_exists( 'ls_field', $this->mConds ) ) {
343  $options[] = 'STRAIGHT_JOIN';
344  }
345 
346  $info = [
347  'tables' => $tables,
348  'fields' => $fields,
349  'conds' => array_merge( $conds, $this->mConds ),
350  'options' => $options,
351  'join_conds' => $joins,
352  ];
353  # Add ChangeTags filter query
354  ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
355  $info['join_conds'], $info['options'], $this->mTagFilter );
356 
357  return $info;
358  }
359 
365  protected function hasEqualsClause( $field ) {
366  return (
367  array_key_exists( $field, $this->mConds ) &&
368  ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
369  );
370  }
371 
372  function getIndexField() {
373  return 'log_timestamp';
374  }
375 
376  protected function getStartBody() {
377  # Do a link batch query
378  if ( $this->getNumRows() > 0 ) {
379  $lb = new LinkBatch;
380  foreach ( $this->mResult as $row ) {
381  $lb->add( $row->log_namespace, $row->log_title );
382  $lb->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) );
383  $lb->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->user_name ) );
384  $formatter = LogFormatter::newFromRow( $row );
385  foreach ( $formatter->getPreloadTitles() as $title ) {
386  $lb->addObj( $title );
387  }
388  }
389  $lb->execute();
390  $this->mResult->seek( 0 );
391  }
392 
393  return '';
394  }
395 
396  public function formatRow( $row ) {
397  return $this->mLogEventsList->logLine( $row );
398  }
399 
400  public function getType() {
401  return $this->types;
402  }
403 
409  public function getPerformer() {
410  return $this->performer;
411  }
412 
416  public function getPage() {
417  return $this->title;
418  }
419 
423  public function getPattern() {
424  return $this->pattern;
425  }
426 
427  public function getYear() {
428  return $this->mYear;
429  }
430 
431  public function getMonth() {
432  return $this->mMonth;
433  }
434 
435  public function getDay() {
436  return $this->mDay;
437  }
438 
439  public function getTagFilter() {
440  return $this->mTagFilter;
441  }
442 
443  public function getAction() {
444  return $this->action;
445  }
446 
447  public function doQuery() {
448  // Workaround MySQL optimizer bug
449  $this->mDb->setBigSelects();
450  parent::doQuery();
451  $this->mDb->setBigSelects( 'default' );
452  }
453 
457  private function enforceActionRestrictions() {
458  if ( $this->actionRestrictionsEnforced ) {
459  return;
460  }
461  $this->actionRestrictionsEnforced = true;
462  $user = $this->getUser();
463  if ( !$user->isAllowed( 'deletedhistory' ) ) {
464  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_ACTION ) . ' = 0';
465  } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
466  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_ACTION ) .
467  ' != ' . LogPage::SUPPRESSED_USER;
468  }
469  }
470 
474  private function enforcePerformerRestrictions() {
475  // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
476  if ( $this->performerRestrictionsEnforced ) {
477  return;
478  }
479  $this->performerRestrictionsEnforced = true;
480  $user = $this->getUser();
481  if ( !$user->isAllowed( 'deletedhistory' ) ) {
482  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_USER ) . ' = 0';
483  } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
484  $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_USER ) .
486  }
487  }
488 }
getPerformer()
Guaranteed to either return a valid title string or a Zero-Length String.
Definition: LogPager.php:409
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:103
bool $pattern
Definition: LogPager.php:40
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used $groups Array of ChangesListFilterGroup objects(added in 1.34) 'FileDeleteComplete' null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1529
bool $performerRestrictionsEnforced
Definition: LogPager.php:49
getPattern()
Definition: LogPager.php:423
bool $actionRestrictionsEnforced
Definition: LogPager.php:52
getQueryInfo()
Constructs the most part of the query.
Definition: LogPager.php:310
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Efficient paging for SQL queries.
string $action
Definition: LogPager.php:46
getDefaultQuery()
Definition: LogPager.php:91
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1724
$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:181
title
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition: hooks.txt:960
LogEventsList $mLogEventsList
Definition: LogPager.php:55
getAction()
Definition: LogPager.php:443
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:71
string Title $title
Events limited to those about Title when set.
Definition: LogPager.php:37
static newMigration()
Static constructor.
IDatabase $mDb
Definition: IndexPager.php:95
getDBkey()
Get the main part with underscores.
Definition: Title.php:1021
$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:274
formatRow( $row)
Definition: LogPager.php:396
getIndexField()
Definition: LogPager.php:372
$wgMiserMode
Disable database-intensive features.
$params
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1972
getStartBody()
Definition: LogPager.php:376
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
getNamespace()
Get the namespace index, i.e.
Definition: Title.php:1045
static newFromRow( $row)
Handy shortcut for constructing a formatter directly from database row.
getTagFilter()
Definition: LogPager.php:439
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
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:211
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:620
const SUPPRESSED_USER
Definition: LogPage.php:40
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
limitType( $types)
Set the log reader to return only entries of the given type.
Definition: LogPager.php:137
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:457
static getExcludeClause( $db, $audience='public', User $user=null)
SQL clause to skip forbidden log types for this user.
string $performer
Events limited to those by performer when set.
Definition: LogPager.php:34
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
const DB_REPLICA
Definition: defines.php:25
hasEqualsClause( $field)
Checks if $this->mConds has $field matched to a single value.
Definition: LogPager.php:365
string $typeCGI
Definition: LogPager.php:43
$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:298
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:535
enforcePerformerRestrictions()
Paranoia: avoid brute force searches (T19342)
Definition: LogPager.php:474
const NS_USER_TALK
Definition: Defines.php:63
getMonth()
Definition: LogPager.php:431
array $types
Log types.
Definition: LogPager.php:31
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1454
$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:602
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:322