Merge "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 && !MediaWikiServices::getInstance()
150 ->getPermissionManager()
151 ->userHasRight( $user, $wgLogRestrictions[$type] )
152 ) {
153 $needReindex = true;
154 $types = array_diff( $types, [ $type ] );
155 }
156 }
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 );
161 }
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;
169 }
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];
175 }
176 }
177 }
178
179 /**
180 * Set the log reader to return only entries by the given user.
181 *
182 * @param string $name (In)valid user name
183 * @return void
184 */
185 private function limitPerformer( $name ) {
186 if ( $name == '' ) {
187 return;
188 }
189 $usertitle = Title::makeTitleSafe( NS_USER, $name );
190 if ( is_null( $usertitle ) ) {
191 return;
192 }
193 // Normalize username first so that non-existent users used
194 // in maintenance scripts work
195 $name = $usertitle->getText();
196
197 // Assume no joins required for log_user
198 $this->mConds[] = ActorMigration::newMigration()->getWhere(
199 wfGetDB( DB_REPLICA ), 'log_user', User::newFromName( $name, false )
200 )['conds'];
201
202 $this->enforcePerformerRestrictions();
203
204 $this->performer = $name;
205 }
206
207 /**
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.)
210 *
211 * @param string|Title $page Title name
212 * @param bool $pattern
213 * @return void
214 */
215 private function limitTitle( $page, $pattern ) {
216 global $wgMiserMode, $wgUserrightsInterwikiDelimiter;
217
218 if ( $page instanceof Title ) {
219 $title = $page;
220 } else {
221 $title = Title::newFromText( $page );
222 if ( strlen( $page ) == 0 || !$title instanceof Title ) {
223 return;
224 }
225 }
226
227 $this->title = $title->getPrefixedText();
228 $ns = $title->getNamespace();
229 $db = $this->mDb;
230
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;
238 }
239 }
240 }
241
242 /**
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
248 * is on.
249 *
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.
254 */
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();
261 }
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;
267 } else {
268 $this->mConds['log_title'] = $title->getDBkey();
269 }
270 $this->enforceActionRestrictions();
271 }
272
273 /**
274 * Set the log_action field to a specified value (or values)
275 *
276 * @param string $action
277 */
278 private function limitAction( $action ) {
279 global $wgActionFilteredLogs;
280 // Allow to filter the log by actions
281 $type = $this->typeCGI;
282 if ( $type === '' ) {
283 // nothing to do
284 return;
285 }
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;
294 }
295 }
296 }
297
298 /**
299 * Limit to the (single) specified log ID.
300 * @param int $logId The log entry ID.
301 */
302 protected function limitLogId( $logId ) {
303 if ( !$logId ) {
304 return;
305 }
306 $this->mConds['log_id'] = $logId;
307 }
308
309 /**
310 * Constructs the most part of the query. Extra conditions are sprinkled in
311 * all over this class.
312 * @return array
313 */
314 public function getQueryInfo() {
315 $basic = DatabaseLogEntry::getSelectQueryData();
316
317 $tables = $basic['tables'];
318 $fields = $basic['fields'];
319 $conds = $basic['conds'];
320 $options = $basic['options'];
321 $joins = $basic['join_conds'];
322
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' )
332 ) {
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';
337 }
338 }
339 # Don't show duplicate rows when using log_search
340 $joins['log_search'] = [ 'JOIN', 'ls_log_id=log_id' ];
341
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';
348 }
349
350 $info = [
351 'tables' => $tables,
352 'fields' => $fields,
353 'conds' => array_merge( $conds, $this->mConds ),
354 'options' => $options,
355 'join_conds' => $joins,
356 ];
357 # Add ChangeTags filter query
358 ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
359 $info['join_conds'], $info['options'], $this->mTagFilter );
360
361 return $info;
362 }
363
364 /**
365 * Checks if $this->mConds has $field matched to a *single* value
366 * @param string $field
367 * @return bool
368 */
369 protected function hasEqualsClause( $field ) {
370 return (
371 array_key_exists( $field, $this->mConds ) &&
372 ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
373 );
374 }
375
376 function getIndexField() {
377 return 'log_timestamp';
378 }
379
380 protected function getStartBody() {
381 # Do a link batch query
382 if ( $this->getNumRows() > 0 ) {
383 $lb = new LinkBatch;
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 );
391 }
392 }
393 $lb->execute();
394 $this->mResult->seek( 0 );
395 }
396
397 return '';
398 }
399
400 public function formatRow( $row ) {
401 return $this->mLogEventsList->logLine( $row );
402 }
403
404 public function getType() {
405 return $this->types;
406 }
407
408 /**
409 * Guaranteed to either return a valid title string or a Zero-Length String
410 *
411 * @return string
412 */
413 public function getPerformer() {
414 return $this->performer;
415 }
416
417 /**
418 * @return string
419 */
420 public function getPage() {
421 return $this->title;
422 }
423
424 /**
425 * @return bool
426 */
427 public function getPattern() {
428 return $this->pattern;
429 }
430
431 public function getYear() {
432 return $this->mYear;
433 }
434
435 public function getMonth() {
436 return $this->mMonth;
437 }
438
439 public function getDay() {
440 return $this->mDay;
441 }
442
443 public function getTagFilter() {
444 return $this->mTagFilter;
445 }
446
447 public function getAction() {
448 return $this->action;
449 }
450
451 public function doQuery() {
452 // Workaround MySQL optimizer bug
453 $this->mDb->setBigSelects();
454 parent::doQuery();
455 $this->mDb->setBigSelects( 'default' );
456 }
457
458 /**
459 * Paranoia: avoid brute force searches (T19342)
460 */
461 private function enforceActionRestrictions() {
462 if ( $this->actionRestrictionsEnforced ) {
463 return;
464 }
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;
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 $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;
492 }
493 }
494 }