3 * Contain classes to list log entries
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 use MediaWiki\MediaWikiServices
;
31 class LogPager
extends ReverseChronologicalPager
{
32 /** @var array Log types */
35 /** @var string Events limited to those by performer when set */
36 private $performer = '';
38 /** @var string|Title Events limited to those about Title when set */
42 private $pattern = false;
45 private $typeCGI = '';
51 private $performerRestrictionsEnforced = false;
54 private $actionRestrictionsEnforced = false;
62 /** @var LogEventsList */
63 public $mLogEventsList;
66 * @param LogEventsList $list
67 * @param string|array $types Log types to show
68 * @param string $performer The user who made the log entries
69 * @param string|Title $title The page title the log entries are for
70 * @param bool $pattern Do a prefix search rather than an exact title match
71 * @param array $conds Extra conditions for the query
72 * @param int|bool $year The year to start from. Default: false
73 * @param int|bool $month The month to start from. Default: false
74 * @param int|bool $day The day to start from. Default: false
75 * @param string $tagFilter Tag
76 * @param string $action Specific action (subtype) requested
77 * @param int $logId Log entry ID, to limit to a single log entry.
79 public function __construct( $list, $types = [], $performer = '', $title = '',
80 $pattern = false, $conds = [], $year = false, $month = false, $day = false,
81 $tagFilter = '', $action = '', $logId = 0
83 parent
::__construct( $list->getContext() );
84 $this->mConds
= $conds;
86 $this->mLogEventsList
= $list;
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;
97 $this->mDb
= wfGetDB( DB_REPLICA
, 'logpager' );
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
;
111 private function limitFilterTypes() {
112 if ( $this->hasEqualsClause( 'log_id' ) ) { // T220834
115 $filterTypes = $this->getFilterParams();
116 foreach ( $filterTypes as $type => $hide ) {
118 $this->mConds
[] = 'log_type != ' . $this->mDb
->addQuotes( $type );
123 public function getFilterParams() {
124 global $wgFilterLogTypes;
126 if ( count( $this->types
) ) {
130 $wpfilters = $this->getRequest()->getArray( "wpfilters" );
131 $request_filters = $wpfilters === null ?
[] : $wpfilters;
133 foreach ( $wgFilterLogTypes as $type => $default ) {
134 $hide = !in_array( $type, $request_filters );
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 );
141 $filters[$type] = $hide;
148 * Set the log reader to return only entries of the given type.
149 * Type restrictions enforced here
151 * @param string|array $types Log types ('upload', 'delete', etc);
152 * empty string means no restriction
154 private function limitType( $types ) {
155 global $wgLogRestrictions;
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] )
169 $types = array_diff( $types, [ $type ] );
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 );
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;
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];
195 * Set the log reader to return only entries by the given user.
197 * @param string $name (In)valid user name
200 private function limitPerformer( $name ) {
204 $usertitle = Title
::makeTitleSafe( NS_USER
, $name );
205 if ( is_null( $usertitle ) ) {
208 // Normalize username first so that non-existent users used
209 // in maintenance scripts work
210 $name = $usertitle->getText();
212 // Assume no joins required for log_user
213 $this->mConds
[] = ActorMigration
::newMigration()->getWhere(
214 wfGetDB( DB_REPLICA
), 'log_user', User
::newFromName( $name, false )
217 $this->enforcePerformerRestrictions();
219 $this->performer
= $name;
223 * Set the log reader to return only entries affecting the given page.
224 * (For the block and rights logs, this is a user page.)
226 * @param string|Title $page Title name
227 * @param bool $pattern
230 private function limitTitle( $page, $pattern ) {
231 global $wgMiserMode, $wgUserrightsInterwikiDelimiter;
233 if ( $page instanceof Title
) {
236 $title = Title
::newFromText( $page );
237 if ( strlen( $page ) == 0 ||
!$title instanceof Title
) {
242 $this->title
= $title->getPrefixedText();
243 $ns = $title->getNamespace();
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;
258 * Using the (log_namespace, log_title, log_timestamp) index with a
259 * range scan (LIKE) on the first two parts, instead of simple equality,
260 * makes it unusable for sorting. Sorted retrieval using another index
261 * would be possible, but then we might have to scan arbitrarily many
262 * nodes of that index. Therefore, we need to avoid this if $wgMiserMode
265 * This is not a problem with simple title matches, because then we can
266 * use the page_time index. That should have no more than a few hundred
267 * log entries for even the busiest pages, so it can be safely scanned
268 * in full to satisfy an impossible condition on user or similar.
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();
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;
283 $this->mConds
['log_title'] = $title->getDBkey();
285 $this->enforceActionRestrictions();
289 * Set the log_action field to a specified value (or values)
291 * @param string $action
293 private function limitAction( $action ) {
294 global $wgActionFilteredLogs;
295 // Allow to filter the log by actions
296 $type = $this->typeCGI
;
297 if ( $type === '' ) {
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;
314 * Limit to the (single) specified log ID.
315 * @param int $logId The log entry ID.
317 protected function limitLogId( $logId ) {
321 $this->mConds
['log_id'] = $logId;
325 * Constructs the most part of the query. Extra conditions are sprinkled in
326 * all over this class.
329 public function getQueryInfo() {
330 $basic = DatabaseLogEntry
::getSelectQueryData();
332 $tables = $basic['tables'];
333 $fields = $basic['fields'];
334 $conds = $basic['conds'];
335 $options = $basic['options'];
336 $joins = $basic['join_conds'];
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' )
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';
354 # Don't show duplicate rows when using log_search
355 $joins['log_search'] = [ 'JOIN', 'ls_log_id=log_id' ];
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';
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' ] ];
373 'conds' => array_merge( $conds, $this->mConds
),
374 'options' => $options,
375 'join_conds' => $joins,
377 # Add ChangeTags filter query
378 ChangeTags
::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
379 $info['join_conds'], $info['options'], $this->mTagFilter
);
385 * Checks if $this->mConds has $field matched to a *single* value
386 * @param string $field
389 protected function hasEqualsClause( $field ) {
391 array_key_exists( $field, $this->mConds
) &&
392 ( !is_array( $this->mConds
[$field] ) ||
count( $this->mConds
[$field] ) == 1 )
396 function getIndexField() {
397 return 'log_timestamp';
400 protected function getStartBody() {
401 # Do a link batch query
402 if ( $this->getNumRows() > 0 ) {
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 );
414 $this->mResult
->seek( 0 );
420 public function formatRow( $row ) {
421 return $this->mLogEventsList
->logLine( $row );
424 public function getType() {
429 * Guaranteed to either return a valid title string or a Zero-Length String
433 public function getPerformer() {
434 return $this->performer
;
440 public function getPage() {
447 public function getPattern() {
448 return $this->pattern
;
451 public function getYear() {
455 public function getMonth() {
456 return $this->mMonth
;
459 public function getDay() {
463 public function getTagFilter() {
464 return $this->mTagFilter
;
467 public function getAction() {
468 return $this->action
;
471 public function doQuery() {
472 // Workaround MySQL optimizer bug
473 $this->mDb
->setBigSelects();
475 $this->mDb
->setBigSelects( 'default' );
479 * Paranoia: avoid brute force searches (T19342)
481 private function enforceActionRestrictions() {
482 if ( $this->actionRestrictionsEnforced
) {
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
;
497 * Paranoia: avoid brute force searches (T19342)
499 private function enforcePerformerRestrictions() {
500 // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
501 if ( $this->performerRestrictionsEnforced
) {
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
) .
511 ' != ' . LogPage
::SUPPRESSED_ACTION
;