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;
56 /** @var LogEventsList */
57 public $mLogEventsList;
60 * @param LogEventsList $list
61 * @param string|array $types Log types to show
62 * @param string $performer The user who made the log entries
63 * @param string|Title $title The page title the log entries are for
64 * @param bool $pattern Do a prefix search rather than an exact title match
65 * @param array $conds Extra conditions for the query
66 * @param int|bool $year The year to start from. Default: false
67 * @param int|bool $month The month to start from. Default: false
68 * @param int|bool $day The day to start from. Default: false
69 * @param string $tagFilter Tag
70 * @param string $action Specific action (subtype) requested
71 * @param int $logId Log entry ID, to limit to a single log entry.
73 public function __construct( $list, $types = [], $performer = '', $title = '',
74 $pattern = false, $conds = [], $year = false, $month = false, $day = false,
75 $tagFilter = '', $action = '', $logId = 0
77 parent
::__construct( $list->getContext() );
78 $this->mConds
= $conds;
80 $this->mLogEventsList
= $list;
82 $this->limitType( $types ); // also excludes hidden types
83 $this->limitPerformer( $performer );
84 $this->limitTitle( $title, $pattern );
85 $this->limitAction( $action );
86 $this->getDateCond( $year, $month, $day );
87 $this->mTagFilter
= $tagFilter;
88 $this->limitLogId( $logId );
90 $this->mDb
= wfGetDB( DB_REPLICA
, 'logpager' );
93 public function getDefaultQuery() {
94 $query = parent
::getDefaultQuery();
95 $query['type'] = $this->typeCGI
; // arrays won't work here
96 $query['user'] = $this->performer
;
97 $query['day'] = $this->mDay
;
98 $query['month'] = $this->mMonth
;
99 $query['year'] = $this->mYear
;
104 // Call ONLY after calling $this->limitType() already!
105 public function getFilterParams() {
106 global $wgFilterLogTypes;
108 if ( count( $this->types
) ) {
112 $wpfilters = $this->getRequest()->getArray( "wpfilters" );
113 $request_filters = $wpfilters === null ?
[] : $wpfilters;
115 foreach ( $wgFilterLogTypes as $type => $default ) {
116 $hide = !in_array( $type, $request_filters );
118 // Back-compat: Check old URL params if the new param wasn't passed
119 if ( $wpfilters === null ) {
120 $hide = $this->getRequest()->getBool( "hide_{$type}_log", $default );
123 $filters[$type] = $hide;
125 $this->mConds
[] = 'log_type != ' . $this->mDb
->addQuotes( $type );
133 * Set the log reader to return only entries of the given type.
134 * Type restrictions enforced here
136 * @param string|array $types Log types ('upload', 'delete', etc);
137 * empty string means no restriction
139 private function limitType( $types ) {
140 global $wgLogRestrictions;
142 $user = $this->getUser();
143 // If $types is not an array, make it an array
144 $types = ( $types === '' ) ?
[] : (array)$types;
145 // Don't even show header for private logs; don't recognize it...
146 $needReindex = false;
147 foreach ( $types as $type ) {
148 if ( isset( $wgLogRestrictions[$type] )
149 && !MediaWikiServices
::getInstance()
150 ->getPermissionManager()
151 ->userHasRight( $user, $wgLogRestrictions[$type] )
154 $types = array_diff( $types, [ $type ] );
157 if ( $needReindex ) {
158 // Lots of this code makes assumptions that
159 // the first entry in the array is $types[0].
160 $types = array_values( $types );
162 $this->types
= $types;
163 // Don't show private logs to unprivileged users.
164 // Also, only show them upon specific request to avoid suprises.
165 $audience = $types ?
'user' : 'public';
166 $hideLogs = LogEventsList
::getExcludeClause( $this->mDb
, $audience, $user );
167 if ( $hideLogs !== false ) {
168 $this->mConds
[] = $hideLogs;
170 if ( count( $types ) ) {
171 $this->mConds
['log_type'] = $types;
172 // Set typeCGI; used in url param for paging
173 if ( count( $types ) == 1 ) {
174 $this->typeCGI
= $types[0];
180 * Set the log reader to return only entries by the given user.
182 * @param string $name (In)valid user name
185 private function limitPerformer( $name ) {
189 $usertitle = Title
::makeTitleSafe( NS_USER
, $name );
190 if ( is_null( $usertitle ) ) {
193 // Normalize username first so that non-existent users used
194 // in maintenance scripts work
195 $name = $usertitle->getText();
197 // Assume no joins required for log_user
198 $this->mConds
[] = ActorMigration
::newMigration()->getWhere(
199 wfGetDB( DB_REPLICA
), 'log_user', User
::newFromName( $name, false )
202 $this->enforcePerformerRestrictions();
204 $this->performer
= $name;
208 * Set the log reader to return only entries affecting the given page.
209 * (For the block and rights logs, this is a user page.)
211 * @param string|Title $page Title name
212 * @param bool $pattern
215 private function limitTitle( $page, $pattern ) {
216 global $wgMiserMode, $wgUserrightsInterwikiDelimiter;
218 if ( $page instanceof Title
) {
221 $title = Title
::newFromText( $page );
222 if ( strlen( $page ) == 0 ||
!$title instanceof Title
) {
227 $this->title
= $title->getPrefixedText();
228 $ns = $title->getNamespace();
231 $doUserRightsLogLike = false;
232 if ( $this->types
== [ 'rights' ] ) {
233 $parts = explode( $wgUserrightsInterwikiDelimiter, $title->getDBkey() );
234 if ( count( $parts ) == 2 ) {
235 list( $name, $database ) = array_map( 'trim', $parts );
236 if ( strstr( $database, '*' ) ) { // Search for wildcard in database name
237 $doUserRightsLogLike = true;
243 * Using the (log_namespace, log_title, log_timestamp) index with a
244 * range scan (LIKE) on the first two parts, instead of simple equality,
245 * makes it unusable for sorting. Sorted retrieval using another index
246 * would be possible, but then we might have to scan arbitrarily many
247 * nodes of that index. Therefore, we need to avoid this if $wgMiserMode
250 * This is not a problem with simple title matches, because then we can
251 * use the page_time index. That should have no more than a few hundred
252 * log entries for even the busiest pages, so it can be safely scanned
253 * in full to satisfy an impossible condition on user or similar.
255 $this->mConds
['log_namespace'] = $ns;
256 if ( $doUserRightsLogLike ) {
257 $params = [ $name . $wgUserrightsInterwikiDelimiter ];
258 foreach ( explode( '*', $database ) as $databasepart ) {
259 $params[] = $databasepart;
260 $params[] = $db->anyString();
262 array_pop( $params ); // Get rid of the last % we added.
263 $this->mConds
[] = 'log_title' . $db->buildLike( ...$params );
264 } elseif ( $pattern && !$wgMiserMode ) {
265 $this->mConds
[] = 'log_title' . $db->buildLike( $title->getDBkey(), $db->anyString() );
266 $this->pattern
= $pattern;
268 $this->mConds
['log_title'] = $title->getDBkey();
270 $this->enforceActionRestrictions();
274 * Set the log_action field to a specified value (or values)
276 * @param string $action
278 private function limitAction( $action ) {
279 global $wgActionFilteredLogs;
280 // Allow to filter the log by actions
281 $type = $this->typeCGI
;
282 if ( $type === '' ) {
286 $actions = $wgActionFilteredLogs;
287 if ( isset( $actions[$type] ) ) {
288 // log type can be filtered by actions
289 $this->mLogEventsList
->setAllowedActions( array_keys( $actions[$type] ) );
290 if ( $action !== '' && isset( $actions[$type][$action] ) ) {
291 // add condition to query
292 $this->mConds
['log_action'] = $actions[$type][$action];
293 $this->action
= $action;
299 * Limit to the (single) specified log ID.
300 * @param int $logId The log entry ID.
302 protected function limitLogId( $logId ) {
306 $this->mConds
['log_id'] = $logId;
310 * Constructs the most part of the query. Extra conditions are sprinkled in
311 * all over this class.
314 public function getQueryInfo() {
315 $basic = DatabaseLogEntry
::getSelectQueryData();
317 $tables = $basic['tables'];
318 $fields = $basic['fields'];
319 $conds = $basic['conds'];
320 $options = $basic['options'];
321 $joins = $basic['join_conds'];
323 # Add log_search table if there are conditions on it.
324 # This filters the results to only include log rows that have
325 # log_search records with the specified ls_field and ls_value values.
326 if ( array_key_exists( 'ls_field', $this->mConds
) ) {
327 $tables[] = 'log_search';
328 $options['IGNORE INDEX'] = [ 'log_search' => 'ls_log_id' ];
329 $options['USE INDEX'] = [ 'logging' => 'PRIMARY' ];
330 if ( !$this->hasEqualsClause( 'ls_field' )
331 ||
!$this->hasEqualsClause( 'ls_value' )
333 # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
334 # to match a specific (ls_field,ls_value) tuple, then there will be
335 # no duplicate log rows. Otherwise, we need to remove the duplicates.
336 $options[] = 'DISTINCT';
339 # Don't show duplicate rows when using log_search
340 $joins['log_search'] = [ 'JOIN', 'ls_log_id=log_id' ];
342 // T221458: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
343 // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
344 // Tell it not to reorder the query. But not when tag filtering or log_search was used, as it
345 // seems as likely to be harmed as helped in that case.
346 if ( !$this->mTagFilter
&& !array_key_exists( 'ls_field', $this->mConds
) ) {
347 $options[] = 'STRAIGHT_JOIN';
353 'conds' => array_merge( $conds, $this->mConds
),
354 'options' => $options,
355 'join_conds' => $joins,
357 # Add ChangeTags filter query
358 ChangeTags
::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
359 $info['join_conds'], $info['options'], $this->mTagFilter
);
365 * Checks if $this->mConds has $field matched to a *single* value
366 * @param string $field
369 protected function hasEqualsClause( $field ) {
371 array_key_exists( $field, $this->mConds
) &&
372 ( !is_array( $this->mConds
[$field] ) ||
count( $this->mConds
[$field] ) == 1 )
376 function getIndexField() {
377 return 'log_timestamp';
380 protected function getStartBody() {
381 # Do a link batch query
382 if ( $this->getNumRows() > 0 ) {
384 foreach ( $this->mResult
as $row ) {
385 $lb->add( $row->log_namespace
, $row->log_title
);
386 $lb->addObj( Title
::makeTitleSafe( NS_USER
, $row->user_name
) );
387 $lb->addObj( Title
::makeTitleSafe( NS_USER_TALK
, $row->user_name
) );
388 $formatter = LogFormatter
::newFromRow( $row );
389 foreach ( $formatter->getPreloadTitles() as $title ) {
390 $lb->addObj( $title );
394 $this->mResult
->seek( 0 );
400 public function formatRow( $row ) {
401 return $this->mLogEventsList
->logLine( $row );
404 public function getType() {
409 * Guaranteed to either return a valid title string or a Zero-Length String
413 public function getPerformer() {
414 return $this->performer
;
420 public function getPage() {
427 public function getPattern() {
428 return $this->pattern
;
431 public function getYear() {
435 public function getMonth() {
436 return $this->mMonth
;
439 public function getDay() {
443 public function getTagFilter() {
444 return $this->mTagFilter
;
447 public function getAction() {
448 return $this->action
;
451 public function doQuery() {
452 // Workaround MySQL optimizer bug
453 $this->mDb
->setBigSelects();
455 $this->mDb
->setBigSelects( 'default' );
459 * Paranoia: avoid brute force searches (T19342)
461 private function enforceActionRestrictions() {
462 if ( $this->actionRestrictionsEnforced
) {
465 $this->actionRestrictionsEnforced
= true;
466 $user = $this->getUser();
467 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
468 if ( !$permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
469 $this->mConds
[] = $this->mDb
->bitAnd( 'log_deleted', LogPage
::DELETED_ACTION
) . ' = 0';
470 } elseif ( !$permissionManager->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' ) ) {
471 $this->mConds
[] = $this->mDb
->bitAnd( 'log_deleted', LogPage
::SUPPRESSED_ACTION
) .
472 ' != ' . LogPage
::SUPPRESSED_USER
;
477 * Paranoia: avoid brute force searches (T19342)
479 private function enforcePerformerRestrictions() {
480 // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
481 if ( $this->performerRestrictionsEnforced
) {
484 $this->performerRestrictionsEnforced
= true;
485 $user = $this->getUser();
486 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
487 if ( !$permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
488 $this->mConds
[] = $this->mDb
->bitAnd( 'log_deleted', LogPage
::DELETED_USER
) . ' = 0';
489 } elseif ( !$permissionManager->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' ) ) {
490 $this->mConds
[] = $this->mDb
->bitAnd( 'log_deleted', LogPage
::SUPPRESSED_USER
) .
491 ' != ' . LogPage
::SUPPRESSED_ACTION
;