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->limitPerformer( $performer );
90 $this->limitTitle( $title, $pattern );
91 $this->limitAction( $action );
92 $this->getDateCond( $year, $month, $day );
93 $this->mTagFilter
= $tagFilter;
94 $this->limitLogId( $logId );
96 $this->mDb
= wfGetDB( DB_REPLICA
, 'logpager' );
99 public function getDefaultQuery() {
100 $query = parent
::getDefaultQuery();
101 $query['type'] = $this->typeCGI
; // arrays won't work here
102 $query['user'] = $this->performer
;
103 $query['day'] = $this->mDay
;
104 $query['month'] = $this->mMonth
;
105 $query['year'] = $this->mYear
;
110 // Call ONLY after calling $this->limitType() already!
111 public function getFilterParams() {
112 global $wgFilterLogTypes;
114 if ( count( $this->types
) ) {
118 $wpfilters = $this->getRequest()->getArray( "wpfilters" );
119 $request_filters = $wpfilters === null ?
[] : $wpfilters;
121 foreach ( $wgFilterLogTypes as $type => $default ) {
122 $hide = !in_array( $type, $request_filters );
124 // Back-compat: Check old URL params if the new param wasn't passed
125 if ( $wpfilters === null ) {
126 $hide = $this->getRequest()->getBool( "hide_{$type}_log", $default );
129 $filters[$type] = $hide;
131 $this->mConds
[] = 'log_type != ' . $this->mDb
->addQuotes( $type );
139 * Set the log reader to return only entries of the given type.
140 * Type restrictions enforced here
142 * @param string|array $types Log types ('upload', 'delete', etc);
143 * empty string means no restriction
145 private function limitType( $types ) {
146 global $wgLogRestrictions;
148 $user = $this->getUser();
149 // If $types is not an array, make it an array
150 $types = ( $types === '' ) ?
[] : (array)$types;
151 // Don't even show header for private logs; don't recognize it...
152 $needReindex = false;
153 foreach ( $types as $type ) {
154 if ( isset( $wgLogRestrictions[$type] )
155 && !$user->isAllowed( $wgLogRestrictions[$type] )
158 $types = array_diff( $types, [ $type ] );
161 if ( $needReindex ) {
162 // Lots of this code makes assumptions that
163 // the first entry in the array is $types[0].
164 $types = array_values( $types );
166 $this->types
= $types;
167 // Don't show private logs to unprivileged users.
168 // Also, only show them upon specific request to avoid suprises.
169 $audience = $types ?
'user' : 'public';
170 $hideLogs = LogEventsList
::getExcludeClause( $this->mDb
, $audience, $user );
171 if ( $hideLogs !== false ) {
172 $this->mConds
[] = $hideLogs;
174 if ( count( $types ) ) {
175 $this->mConds
['log_type'] = $types;
176 // Set typeCGI; used in url param for paging
177 if ( count( $types ) == 1 ) {
178 $this->typeCGI
= $types[0];
184 * Set the log reader to return only entries by the given user.
186 * @param string $name (In)valid user name
189 private function limitPerformer( $name ) {
193 $usertitle = Title
::makeTitleSafe( NS_USER
, $name );
194 if ( is_null( $usertitle ) ) {
197 // Normalize username first so that non-existent users used
198 // in maintenance scripts work
199 $name = $usertitle->getText();
201 // Assume no joins required for log_user
202 $this->mConds
[] = ActorMigration
::newMigration()->getWhere(
203 wfGetDB( DB_REPLICA
), 'log_user', User
::newFromName( $name, false )
206 $this->enforcePerformerRestrictions();
208 $this->performer
= $name;
212 * Set the log reader to return only entries affecting the given page.
213 * (For the block and rights logs, this is a user page.)
215 * @param string|Title $page Title name
216 * @param bool $pattern
219 private function limitTitle( $page, $pattern ) {
220 global $wgMiserMode, $wgUserrightsInterwikiDelimiter;
222 if ( $page instanceof Title
) {
225 $title = Title
::newFromText( $page );
226 if ( strlen( $page ) == 0 ||
!$title instanceof Title
) {
231 $this->title
= $title->getPrefixedText();
232 $ns = $title->getNamespace();
235 $doUserRightsLogLike = false;
236 if ( $this->types
== [ 'rights' ] ) {
237 $parts = explode( $wgUserrightsInterwikiDelimiter, $title->getDBkey() );
238 if ( count( $parts ) == 2 ) {
239 list( $name, $database ) = array_map( 'trim', $parts );
240 if ( strstr( $database, '*' ) ) { // Search for wildcard in database name
241 $doUserRightsLogLike = true;
247 * Using the (log_namespace, log_title, log_timestamp) index with a
248 * range scan (LIKE) on the first two parts, instead of simple equality,
249 * makes it unusable for sorting. Sorted retrieval using another index
250 * would be possible, but then we might have to scan arbitrarily many
251 * nodes of that index. Therefore, we need to avoid this if $wgMiserMode
254 * This is not a problem with simple title matches, because then we can
255 * use the page_time index. That should have no more than a few hundred
256 * log entries for even the busiest pages, so it can be safely scanned
257 * in full to satisfy an impossible condition on user or similar.
259 $this->mConds
['log_namespace'] = $ns;
260 if ( $doUserRightsLogLike ) {
261 $params = [ $name . $wgUserrightsInterwikiDelimiter ];
262 foreach ( explode( '*', $database ) as $databasepart ) {
263 $params[] = $databasepart;
264 $params[] = $db->anyString();
266 array_pop( $params ); // Get rid of the last % we added.
267 $this->mConds
[] = 'log_title' . $db->buildLike( ...$params );
268 } elseif ( $pattern && !$wgMiserMode ) {
269 $this->mConds
[] = 'log_title' . $db->buildLike( $title->getDBkey(), $db->anyString() );
270 $this->pattern
= $pattern;
272 $this->mConds
['log_title'] = $title->getDBkey();
274 $this->enforceActionRestrictions();
278 * Set the log_action field to a specified value (or values)
280 * @param string $action
282 private function limitAction( $action ) {
283 global $wgActionFilteredLogs;
284 // Allow to filter the log by actions
285 $type = $this->typeCGI
;
286 if ( $type === '' ) {
290 $actions = $wgActionFilteredLogs;
291 if ( isset( $actions[$type] ) ) {
292 // log type can be filtered by actions
293 $this->mLogEventsList
->setAllowedActions( array_keys( $actions[$type] ) );
294 if ( $action !== '' && isset( $actions[$type][$action] ) ) {
295 // add condition to query
296 $this->mConds
['log_action'] = $actions[$type][$action];
297 $this->action
= $action;
303 * Limit to the (single) specified log ID.
304 * @param int $logId The log entry ID.
306 protected function limitLogId( $logId ) {
310 $this->mConds
['log_id'] = $logId;
314 * Constructs the most part of the query. Extra conditions are sprinkled in
315 * all over this class.
318 public function getQueryInfo() {
319 $basic = DatabaseLogEntry
::getSelectQueryData();
321 $tables = $basic['tables'];
322 $fields = $basic['fields'];
323 $conds = $basic['conds'];
324 $options = $basic['options'];
325 $joins = $basic['join_conds'];
327 # Add log_search table if there are conditions on it.
328 # This filters the results to only include log rows that have
329 # log_search records with the specified ls_field and ls_value values.
330 if ( array_key_exists( 'ls_field', $this->mConds
) ) {
331 $tables[] = 'log_search';
332 $options['IGNORE INDEX'] = [ 'log_search' => 'ls_log_id' ];
333 $options['USE INDEX'] = [ 'logging' => 'PRIMARY' ];
334 if ( !$this->hasEqualsClause( 'ls_field' )
335 ||
!$this->hasEqualsClause( 'ls_value' )
337 # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
338 # to match a specific (ls_field,ls_value) tuple, then there will be
339 # no duplicate log rows. Otherwise, we need to remove the duplicates.
340 $options[] = 'DISTINCT';
343 # Don't show duplicate rows when using log_search
344 $joins['log_search'] = [ 'JOIN', 'ls_log_id=log_id' ];
346 // T221458: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
347 // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
348 // Tell it not to reorder the query. But not when tag filtering or log_search was used, as it
349 // seems as likely to be harmed as helped in that case.
350 if ( !$this->mTagFilter
&& !array_key_exists( 'ls_field', $this->mConds
) ) {
351 $options[] = 'STRAIGHT_JOIN';
357 'conds' => array_merge( $conds, $this->mConds
),
358 'options' => $options,
359 'join_conds' => $joins,
361 # Add ChangeTags filter query
362 ChangeTags
::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
363 $info['join_conds'], $info['options'], $this->mTagFilter
);
369 * Checks if $this->mConds has $field matched to a *single* value
370 * @param string $field
373 protected function hasEqualsClause( $field ) {
375 array_key_exists( $field, $this->mConds
) &&
376 ( !is_array( $this->mConds
[$field] ) ||
count( $this->mConds
[$field] ) == 1 )
380 function getIndexField() {
381 return 'log_timestamp';
384 protected function getStartBody() {
385 # Do a link batch query
386 if ( $this->getNumRows() > 0 ) {
388 foreach ( $this->mResult
as $row ) {
389 $lb->add( $row->log_namespace
, $row->log_title
);
390 $lb->addObj( Title
::makeTitleSafe( NS_USER
, $row->user_name
) );
391 $lb->addObj( Title
::makeTitleSafe( NS_USER_TALK
, $row->user_name
) );
392 $formatter = LogFormatter
::newFromRow( $row );
393 foreach ( $formatter->getPreloadTitles() as $title ) {
394 $lb->addObj( $title );
398 $this->mResult
->seek( 0 );
404 public function formatRow( $row ) {
405 return $this->mLogEventsList
->logLine( $row );
408 public function getType() {
413 * Guaranteed to either return a valid title string or a Zero-Length String
417 public function getPerformer() {
418 return $this->performer
;
424 public function getPage() {
431 public function getPattern() {
432 return $this->pattern
;
435 public function getYear() {
439 public function getMonth() {
440 return $this->mMonth
;
443 public function getDay() {
447 public function getTagFilter() {
448 return $this->mTagFilter
;
451 public function getAction() {
452 return $this->action
;
455 public function doQuery() {
456 // Workaround MySQL optimizer bug
457 $this->mDb
->setBigSelects();
459 $this->mDb
->setBigSelects( 'default' );
463 * Paranoia: avoid brute force searches (T19342)
465 private function enforceActionRestrictions() {
466 if ( $this->actionRestrictionsEnforced
) {
469 $this->actionRestrictionsEnforced
= true;
470 $user = $this->getUser();
471 if ( !$user->isAllowed( 'deletedhistory' ) ) {
472 $this->mConds
[] = $this->mDb
->bitAnd( 'log_deleted', LogPage
::DELETED_ACTION
) . ' = 0';
473 } elseif ( !MediaWikiServices
::getInstance()
474 ->getPermissionManager()
475 ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
477 $this->mConds
[] = $this->mDb
->bitAnd( 'log_deleted', LogPage
::SUPPRESSED_ACTION
) .
478 ' != ' . LogPage
::SUPPRESSED_USER
;
483 * Paranoia: avoid brute force searches (T19342)
485 private function enforcePerformerRestrictions() {
486 // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
487 if ( $this->performerRestrictionsEnforced
) {
490 $this->performerRestrictionsEnforced
= true;
491 $user = $this->getUser();
492 if ( !$user->isAllowed( 'deletedhistory' ) ) {
493 $this->mConds
[] = $this->mDb
->bitAnd( 'log_deleted', LogPage
::DELETED_USER
) . ' = 0';
494 } elseif ( !MediaWikiServices
::getInstance()
495 ->getPermissionManager()
496 ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
498 $this->mConds
[] = $this->mDb
->bitAnd( 'log_deleted', LogPage
::SUPPRESSED_USER
) .
499 ' != ' . LogPage
::SUPPRESSED_ACTION
;