MediaWiki REL1_37
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
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 = (string)$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"!
252 $page = Title::newFromText( $page );
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 }
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() {
348 $basic = DatabaseLogEntry::getSelectQueryData();
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
383 $options['MAX_EXECUTION_TIME'] = $this->getConfig()->get( 'MaxExecutionTimeForExpensiveQueries' );
384
385 $info = [
386 'tables' => $tables,
387 'fields' => $fields,
388 'conds' => array_merge( $conds, $this->mConds ),
389 'options' => $options,
390 'join_conds' => $joins,
391 ];
392 # Add ChangeTags filter query
393 ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
394 $info['join_conds'], $info['options'], $this->mTagFilter );
395
396 return $info;
397 }
398
404 protected function hasEqualsClause( $field ) {
405 return (
406 array_key_exists( $field, $this->mConds ) &&
407 ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
408 );
409 }
410
411 public function getIndexField() {
412 return 'log_timestamp';
413 }
414
415 protected function getStartBody() {
416 # Do a link batch query
417 if ( $this->getNumRows() > 0 ) {
418 $lb = $this->linkBatchFactory->newLinkBatch();
419 foreach ( $this->mResult as $row ) {
420 $lb->add( $row->log_namespace, $row->log_title );
421 $lb->add( NS_USER, $row->log_user_text );
422 $lb->add( NS_USER_TALK, $row->log_user_text );
423 $formatter = LogFormatter::newFromRow( $row );
424 foreach ( $formatter->getPreloadTitles() as $title ) {
425 $lb->addObj( $title );
426 }
427 }
428 $lb->execute();
429 $this->mResult->seek( 0 );
430 }
431
432 return '';
433 }
434
435 public function formatRow( $row ) {
436 return $this->mLogEventsList->logLine( $row );
437 }
438
439 public function getType() {
440 return $this->types;
441 }
442
448 public function getPerformer() {
449 return $this->performer;
450 }
451
455 public function getPage() {
456 return $this->page;
457 }
458
462 public function getPattern() {
463 return $this->pattern;
464 }
465
466 public function getYear() {
467 return $this->mYear;
468 }
469
470 public function getMonth() {
471 return $this->mMonth;
472 }
473
474 public function getDay() {
475 return $this->mDay;
476 }
477
478 public function getTagFilter() {
479 return $this->mTagFilter;
480 }
481
482 public function getAction() {
483 return $this->action;
484 }
485
486 public function doQuery() {
487 // Workaround MySQL optimizer bug
488 $this->mDb->setBigSelects();
489 parent::doQuery();
490 $this->mDb->setBigSelects( 'default' );
491 }
492
496 private function enforceActionRestrictions() {
497 if ( $this->actionRestrictionsEnforced ) {
498 return;
499 }
500 $this->actionRestrictionsEnforced = true;
501 if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
502 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_ACTION ) . ' = 0';
503 } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
504 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_ACTION ) .
506 }
507 }
508
512 private function enforcePerformerRestrictions() {
513 // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
514 if ( $this->performerRestrictionsEnforced ) {
515 return;
516 }
517 $this->performerRestrictionsEnforced = true;
518 if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
519 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_USER ) . ' = 0';
520 } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
521 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_USER ) .
523 }
524 }
525}
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='')
Applies all tags-related changes to a query.
IDatabase $mDb
getNumRows()
Get the number of rows in the result set.
static newFromRow( $row)
Handy shortcut for constructing a formatter directly from database row.
const SUPPRESSED_USER
Definition LogPage.php:45
const DELETED_USER
Definition LogPage.php:41
const DELETED_ACTION
Definition LogPage.php:39
const SUPPRESSED_ACTION
Definition LogPage.php:46
hasEqualsClause( $field)
Checks if $this->mConds has $field matched to a single value.
Definition LogPager.php:404
bool $actionRestrictionsEnforced
Definition LogPager.php:58
bool $performerRestrictionsEnforced
Definition LogPager.php:55
ActorNormalization $actorNormalization
Definition LogPager.php:73
formatRow( $row)
Returns an HTML string representing the result row $row.
Definition LogPager.php:435
limitType( $types)
Set the log reader to return only entries of the given type.
Definition LogPager.php:175
getStartBody()
Hook into getBody(), allows text to be inserted at the start.
Definition LogPager.php:415
limitLogId( $logId)
Limit to the (single) specified log ID.
Definition LogPager.php:335
string $performer
Events limited to those by performer when set.
Definition LogPager.php:40
array $mConds
Definition LogPager.php:61
bool $pattern
Definition LogPager.php:46
getFilterParams()
Definition LogPager.php:145
limitFilterTypes()
Definition LogPager.php:133
enforcePerformerRestrictions()
Paranoia: avoid brute force searches (T19342)
Definition LogPager.php:512
LinkBatchFactory $linkBatchFactory
Definition LogPager.php:70
enforceActionRestrictions()
Paranoia: avoid brute force searches (T19342)
Definition LogPager.php:496
getDefaultQuery()
Get an array of query parameters that should be put into self-links.
Definition LogPager.php:122
limitTitle( $page, $pattern)
Set the log reader to return only entries affecting the given page.
Definition LogPager.php:249
string $mTagFilter
Definition LogPager.php:64
string $action
Definition LogPager.php:52
getTagFilter()
Definition LogPager.php:478
LogEventsList $mLogEventsList
Definition LogPager.php:67
getQueryInfo()
Constructs the most part of the query.
Definition LogPager.php:347
doQuery()
Do the query, using information from the object context.
Definition LogPager.php:486
getPerformer()
Guaranteed to either return a valid title string or a Zero-Length String.
Definition LogPager.php:448
string $typeCGI
Definition LogPager.php:49
limitPerformer( $name)
Set the log reader to return only entries by the given user.
Definition LogPager.php:221
array $types
Log types.
Definition LogPager.php:37
getIndexField()
Returns the name of the index field.
Definition LogPager.php:411
limitAction( $action)
Set the log_action field to a specified value (or values)
Definition LogPager.php:312
__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
string $page
Events limited to those about this page when set.
Definition LogPager.php:43
MediaWikiServices is the service locator for the application scope of MediaWiki.
Efficient paging for SQL queries.
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...
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
Service for dealing with the actor table.
Database cluster connection, tracking, load balancing, and transaction manager interface.