output: Narrow Title type hint to LinkTarget
[lhc/web/wiklou.git] / includes / logging / LogPager.php
1 <?php
2 /**
3 * Contain classes to list log entries
4 *
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 */
25
26 use MediaWiki\MediaWikiServices;
27
28 /**
29 * @ingroup Pager
30 */
31 class LogPager extends ReverseChronologicalPager {
32 /** @var array Log types */
33 private $types = [];
34
35 /** @var string Events limited to those by performer when set */
36 private $performer = '';
37
38 /** @var string|Title Events limited to those about Title when set */
39 private $title = '';
40
41 /** @var bool */
42 private $pattern = false;
43
44 /** @var string */
45 private $typeCGI = '';
46
47 /** @var string */
48 private $action = '';
49
50 /** @var bool */
51 private $performerRestrictionsEnforced = false;
52
53 /** @var bool */
54 private $actionRestrictionsEnforced = false;
55
56 /** @var LogEventsList */
57 public $mLogEventsList;
58
59 /**
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.
72 */
73 public function __construct( $list, $types = [], $performer = '', $title = '',
74 $pattern = false, $conds = [], $year = false, $month = false, $day = false,
75 $tagFilter = '', $action = '', $logId = 0
76 ) {
77 parent::__construct( $list->getContext() );
78 $this->mConds = $conds;
79
80 $this->mLogEventsList = $list;
81
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 );
89
90 $this->mDb = wfGetDB( DB_REPLICA, 'logpager' );
91 }
92
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;
100
101 return $query;
102 }
103
104 // Call ONLY after calling $this->limitType() already!
105 public function getFilterParams() {
106 global $wgFilterLogTypes;
107 $filters = [];
108 if ( count( $this->types ) ) {
109 return $filters;
110 }
111
112 $wpfilters = $this->getRequest()->getArray( "wpfilters" );
113 $request_filters = $wpfilters === null ? [] : $wpfilters;
114
115 foreach ( $wgFilterLogTypes as $type => $default ) {
116 $hide = !in_array( $type, $request_filters );
117
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 );
121 }
122
123 $filters[$type] = $hide;
124 if ( $hide ) {
125 $this->mConds[] = 'log_type != ' . $this->mDb->addQuotes( $type );
126 }
127 }
128
129 return $filters;
130 }
131
132 /**
133 * Set the log reader to return only entries of the given type.
134 * Type restrictions enforced here
135 *
136 * @param string|array $types Log types ('upload', 'delete', etc);
137 * empty string means no restriction
138 */
139 private function limitType( $types ) {
140 global $wgLogRestrictions;
141
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] )
150 ) {
151 $needReindex = true;
152 $types = array_diff( $types, [ $type ] );
153 }
154 }
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 );
159 }
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;
167 }
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];
173 }
174 }
175 }
176
177 /**
178 * Set the log reader to return only entries by the given user.
179 *
180 * @param string $name (In)valid user name
181 * @return void
182 */
183 private function limitPerformer( $name ) {
184 if ( $name == '' ) {
185 return;
186 }
187 $usertitle = Title::makeTitleSafe( NS_USER, $name );
188 if ( is_null( $usertitle ) ) {
189 return;
190 }
191 // Normalize username first so that non-existent users used
192 // in maintenance scripts work
193 $name = $usertitle->getText();
194
195 // Assume no joins required for log_user
196 $this->mConds[] = ActorMigration::newMigration()->getWhere(
197 wfGetDB( DB_REPLICA ), 'log_user', User::newFromName( $name, false )
198 )['conds'];
199
200 $this->enforcePerformerRestrictions();
201
202 $this->performer = $name;
203 }
204
205 /**
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.)
208 *
209 * @param string|Title $page Title name
210 * @param bool $pattern
211 * @return void
212 */
213 private function limitTitle( $page, $pattern ) {
214 global $wgMiserMode, $wgUserrightsInterwikiDelimiter;
215
216 if ( $page instanceof Title ) {
217 $title = $page;
218 } else {
219 $title = Title::newFromText( $page );
220 if ( strlen( $page ) == 0 || !$title instanceof Title ) {
221 return;
222 }
223 }
224
225 $this->title = $title->getPrefixedText();
226 $ns = $title->getNamespace();
227 $db = $this->mDb;
228
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;
236 }
237 }
238 }
239
240 /**
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
246 * is on.
247 *
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.
252 */
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();
259 }
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;
265 } else {
266 $this->mConds['log_title'] = $title->getDBkey();
267 }
268 $this->enforceActionRestrictions();
269 }
270
271 /**
272 * Set the log_action field to a specified value (or values)
273 *
274 * @param string $action
275 */
276 private function limitAction( $action ) {
277 global $wgActionFilteredLogs;
278 // Allow to filter the log by actions
279 $type = $this->typeCGI;
280 if ( $type === '' ) {
281 // nothing to do
282 return;
283 }
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;
292 }
293 }
294 }
295
296 /**
297 * Limit to the (single) specified log ID.
298 * @param int $logId The log entry ID.
299 */
300 protected function limitLogId( $logId ) {
301 if ( !$logId ) {
302 return;
303 }
304 $this->mConds['log_id'] = $logId;
305 }
306
307 /**
308 * Constructs the most part of the query. Extra conditions are sprinkled in
309 * all over this class.
310 * @return array
311 */
312 public function getQueryInfo() {
313 $basic = DatabaseLogEntry::getSelectQueryData();
314
315 $tables = $basic['tables'];
316 $fields = $basic['fields'];
317 $conds = $basic['conds'];
318 $options = $basic['options'];
319 $joins = $basic['join_conds'];
320
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' )
330 ) {
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';
335 }
336 }
337 # Don't show duplicate rows when using log_search
338 $joins['log_search'] = [ 'JOIN', 'ls_log_id=log_id' ];
339
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';
346 }
347
348 $info = [
349 'tables' => $tables,
350 'fields' => $fields,
351 'conds' => array_merge( $conds, $this->mConds ),
352 'options' => $options,
353 'join_conds' => $joins,
354 ];
355 # Add ChangeTags filter query
356 ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
357 $info['join_conds'], $info['options'], $this->mTagFilter );
358
359 return $info;
360 }
361
362 /**
363 * Checks if $this->mConds has $field matched to a *single* value
364 * @param string $field
365 * @return bool
366 */
367 protected function hasEqualsClause( $field ) {
368 return (
369 array_key_exists( $field, $this->mConds ) &&
370 ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
371 );
372 }
373
374 function getIndexField() {
375 return 'log_timestamp';
376 }
377
378 protected function getStartBody() {
379 # Do a link batch query
380 if ( $this->getNumRows() > 0 ) {
381 $lb = new LinkBatch;
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 );
389 }
390 }
391 $lb->execute();
392 $this->mResult->seek( 0 );
393 }
394
395 return '';
396 }
397
398 public function formatRow( $row ) {
399 return $this->mLogEventsList->logLine( $row );
400 }
401
402 public function getType() {
403 return $this->types;
404 }
405
406 /**
407 * Guaranteed to either return a valid title string or a Zero-Length String
408 *
409 * @return string
410 */
411 public function getPerformer() {
412 return $this->performer;
413 }
414
415 /**
416 * @return string
417 */
418 public function getPage() {
419 return $this->title;
420 }
421
422 /**
423 * @return bool
424 */
425 public function getPattern() {
426 return $this->pattern;
427 }
428
429 public function getYear() {
430 return $this->mYear;
431 }
432
433 public function getMonth() {
434 return $this->mMonth;
435 }
436
437 public function getDay() {
438 return $this->mDay;
439 }
440
441 public function getTagFilter() {
442 return $this->mTagFilter;
443 }
444
445 public function getAction() {
446 return $this->action;
447 }
448
449 public function doQuery() {
450 // Workaround MySQL optimizer bug
451 $this->mDb->setBigSelects();
452 parent::doQuery();
453 $this->mDb->setBigSelects( 'default' );
454 }
455
456 /**
457 * Paranoia: avoid brute force searches (T19342)
458 */
459 private function enforceActionRestrictions() {
460 if ( $this->actionRestrictionsEnforced ) {
461 return;
462 }
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' )
470 ) {
471 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_ACTION ) .
472 ' != ' . LogPage::SUPPRESSED_USER;
473 }
474 }
475
476 /**
477 * Paranoia: avoid brute force searches (T19342)
478 */
479 private function enforcePerformerRestrictions() {
480 // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
481 if ( $this->performerRestrictionsEnforced ) {
482 return;
483 }
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' )
491 ) {
492 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_USER ) .
493 ' != ' . LogPage::SUPPRESSED_ACTION;
494 }
495 }
496 }