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 && !$user->isAllowed( $wgLogRestrictions[$type] )
152 $types = array_diff( $types, [ $type ] );
155 if ( $needReindex ) {
156 // Lots of this code makes assumptions that
157 // the first entry in the array is $types[0].
158 $types = array_values( $types );
160 $this->types
= $types;
161 // Don't show private logs to unprivileged users.
162 // Also, only show them upon specific request to avoid suprises.
163 $audience = $types ?
'user' : 'public';
164 $hideLogs = LogEventsList
::getExcludeClause( $this->mDb
, $audience, $user );
165 if ( $hideLogs !== false ) {
166 $this->mConds
[] = $hideLogs;
168 if ( count( $types ) ) {
169 $this->mConds
['log_type'] = $types;
170 // Set typeCGI; used in url param for paging
171 if ( count( $types ) == 1 ) {
172 $this->typeCGI
= $types[0];
178 * Set the log reader to return only entries by the given user.
180 * @param string $name (In)valid user name
183 private function limitPerformer( $name ) {
187 $usertitle = Title
::makeTitleSafe( NS_USER
, $name );
188 if ( is_null( $usertitle ) ) {
191 // Normalize username first so that non-existent users used
192 // in maintenance scripts work
193 $name = $usertitle->getText();
195 // Assume no joins required for log_user
196 $this->mConds
[] = ActorMigration
::newMigration()->getWhere(
197 wfGetDB( DB_REPLICA
), 'log_user', User
::newFromName( $name, false )
200 $this->enforcePerformerRestrictions();
202 $this->performer
= $name;
206 * Set the log reader to return only entries affecting the given page.
207 * (For the block and rights logs, this is a user page.)
209 * @param string|Title $page Title name
210 * @param bool $pattern
213 private function limitTitle( $page, $pattern ) {
214 global $wgMiserMode, $wgUserrightsInterwikiDelimiter;
216 if ( $page instanceof Title
) {
219 $title = Title
::newFromText( $page );
220 if ( strlen( $page ) == 0 ||
!$title instanceof Title
) {
225 $this->title
= $title->getPrefixedText();
226 $ns = $title->getNamespace();
229 $doUserRightsLogLike = false;
230 if ( $this->types
== [ 'rights' ] ) {
231 $parts = explode( $wgUserrightsInterwikiDelimiter, $title->getDBkey() );
232 if ( count( $parts ) == 2 ) {
233 list( $name, $database ) = array_map( 'trim', $parts );
234 if ( strstr( $database, '*' ) ) { // Search for wildcard in database name
235 $doUserRightsLogLike = true;
241 * Using the (log_namespace, log_title, log_timestamp) index with a
242 * range scan (LIKE) on the first two parts, instead of simple equality,
243 * makes it unusable for sorting. Sorted retrieval using another index
244 * would be possible, but then we might have to scan arbitrarily many
245 * nodes of that index. Therefore, we need to avoid this if $wgMiserMode
248 * This is not a problem with simple title matches, because then we can
249 * use the page_time index. That should have no more than a few hundred
250 * log entries for even the busiest pages, so it can be safely scanned
251 * in full to satisfy an impossible condition on user or similar.
253 $this->mConds
['log_namespace'] = $ns;
254 if ( $doUserRightsLogLike ) {
255 $params = [ $name . $wgUserrightsInterwikiDelimiter ];
256 foreach ( explode( '*', $database ) as $databasepart ) {
257 $params[] = $databasepart;
258 $params[] = $db->anyString();
260 array_pop( $params ); // Get rid of the last % we added.
261 $this->mConds
[] = 'log_title' . $db->buildLike( $params );
262 } elseif ( $pattern && !$wgMiserMode ) {
263 $this->mConds
[] = 'log_title' . $db->buildLike( $title->getDBkey(), $db->anyString() );
264 $this->pattern
= $pattern;
266 $this->mConds
['log_title'] = $title->getDBkey();
268 $this->enforceActionRestrictions();
272 * Set the log_action field to a specified value (or values)
274 * @param string $action
276 private function limitAction( $action ) {
277 global $wgActionFilteredLogs;
278 // Allow to filter the log by actions
279 $type = $this->typeCGI
;
280 if ( $type === '' ) {
284 $actions = $wgActionFilteredLogs;
285 if ( isset( $actions[$type] ) ) {
286 // log type can be filtered by actions
287 $this->mLogEventsList
->setAllowedActions( array_keys( $actions[$type] ) );
288 if ( $action !== '' && isset( $actions[$type][$action] ) ) {
289 // add condition to query
290 $this->mConds
['log_action'] = $actions[$type][$action];
291 $this->action
= $action;
297 * Limit to the (single) specified log ID.
298 * @param int $logId The log entry ID.
300 protected function limitLogId( $logId ) {
304 $this->mConds
['log_id'] = $logId;
308 * Constructs the most part of the query. Extra conditions are sprinkled in
309 * all over this class.
312 public function getQueryInfo() {
313 $basic = DatabaseLogEntry
::getSelectQueryData();
315 $tables = $basic['tables'];
316 $fields = $basic['fields'];
317 $conds = $basic['conds'];
318 $options = $basic['options'];
319 $joins = $basic['join_conds'];
321 # Add log_search table if there are conditions on it.
322 # This filters the results to only include log rows that have
323 # log_search records with the specified ls_field and ls_value values.
324 if ( array_key_exists( 'ls_field', $this->mConds
) ) {
325 $tables[] = 'log_search';
326 $options['IGNORE INDEX'] = [ 'log_search' => 'ls_log_id' ];
327 $options['USE INDEX'] = [ 'logging' => 'PRIMARY' ];
328 if ( !$this->hasEqualsClause( 'ls_field' )
329 ||
!$this->hasEqualsClause( 'ls_value' )
331 # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
332 # to match a specific (ls_field,ls_value) tuple, then there will be
333 # no duplicate log rows. Otherwise, we need to remove the duplicates.
334 $options[] = 'DISTINCT';
337 # Don't show duplicate rows when using log_search
338 $joins['log_search'] = [ 'JOIN', 'ls_log_id=log_id' ];
340 // T221458: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
341 // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
342 // Tell it not to reorder the query. But not when tag filtering or log_search was used, as it
343 // seems as likely to be harmed as helped in that case.
344 if ( !$this->mTagFilter
&& !array_key_exists( 'ls_field', $this->mConds
) ) {
345 $options[] = 'STRAIGHT_JOIN';
351 'conds' => array_merge( $conds, $this->mConds
),
352 'options' => $options,
353 'join_conds' => $joins,
355 # Add ChangeTags filter query
356 ChangeTags
::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
357 $info['join_conds'], $info['options'], $this->mTagFilter
);
363 * Checks if $this->mConds has $field matched to a *single* value
364 * @param string $field
367 protected function hasEqualsClause( $field ) {
369 array_key_exists( $field, $this->mConds
) &&
370 ( !is_array( $this->mConds
[$field] ) ||
count( $this->mConds
[$field] ) == 1 )
374 function getIndexField() {
375 return 'log_timestamp';
378 protected function getStartBody() {
379 # Do a link batch query
380 if ( $this->getNumRows() > 0 ) {
382 foreach ( $this->mResult
as $row ) {
383 $lb->add( $row->log_namespace
, $row->log_title
);
384 $lb->addObj( Title
::makeTitleSafe( NS_USER
, $row->user_name
) );
385 $lb->addObj( Title
::makeTitleSafe( NS_USER_TALK
, $row->user_name
) );
386 $formatter = LogFormatter
::newFromRow( $row );
387 foreach ( $formatter->getPreloadTitles() as $title ) {
388 $lb->addObj( $title );
392 $this->mResult
->seek( 0 );
398 public function formatRow( $row ) {
399 return $this->mLogEventsList
->logLine( $row );
402 public function getType() {
407 * Guaranteed to either return a valid title string or a Zero-Length String
411 public function getPerformer() {
412 return $this->performer
;
418 public function getPage() {
425 public function getPattern() {
426 return $this->pattern
;
429 public function getYear() {
433 public function getMonth() {
434 return $this->mMonth
;
437 public function getDay() {
441 public function getTagFilter() {
442 return $this->mTagFilter
;
445 public function getAction() {
446 return $this->action
;
449 public function doQuery() {
450 // Workaround MySQL optimizer bug
451 $this->mDb
->setBigSelects();
453 $this->mDb
->setBigSelects( 'default' );
457 * Paranoia: avoid brute force searches (T19342)
459 private function enforceActionRestrictions() {
460 if ( $this->actionRestrictionsEnforced
) {
463 $this->actionRestrictionsEnforced
= true;
464 $user = $this->getUser();
465 if ( !$user->isAllowed( 'deletedhistory' ) ) {
466 $this->mConds
[] = $this->mDb
->bitAnd( 'log_deleted', LogPage
::DELETED_ACTION
) . ' = 0';
467 } elseif ( !MediaWikiServices
::getInstance()
468 ->getPermissionManager()
469 ->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 if ( !$user->isAllowed( 'deletedhistory' ) ) {
487 $this->mConds
[] = $this->mDb
->bitAnd( 'log_deleted', LogPage
::DELETED_USER
) . ' = 0';
488 } elseif ( !MediaWikiServices
::getInstance()
489 ->getPermissionManager()
490 ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
492 $this->mConds
[] = $this->mDb
->bitAnd( 'log_deleted', LogPage
::SUPPRESSED_USER
) .
493 ' != ' . LogPage
::SUPPRESSED_ACTION
;