Merge "Add .pipeline/ with dev image variant"
[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 array */
57 private $mConds;
58
59 /** @var string */
60 private $mTagFilter;
61
62 /** @var LogEventsList */
63 public $mLogEventsList;
64
65 /**
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.
78 */
79 public function __construct( $list, $types = [], $performer = '', $title = '',
80 $pattern = false, $conds = [], $year = false, $month = false, $day = false,
81 $tagFilter = '', $action = '', $logId = 0
82 ) {
83 parent::__construct( $list->getContext() );
84 $this->mConds = $conds;
85
86 $this->mLogEventsList = $list;
87
88 $this->limitType( $types ); // also excludes hidden types
89 $this->limitLogId( $logId );
90 $this->limitFilterTypes();
91 $this->limitPerformer( $performer );
92 $this->limitTitle( $title, $pattern );
93 $this->limitAction( $action );
94 $this->getDateCond( $year, $month, $day );
95 $this->mTagFilter = $tagFilter;
96
97 $this->mDb = wfGetDB( DB_REPLICA, 'logpager' );
98 }
99
100 public function getDefaultQuery() {
101 $query = parent::getDefaultQuery();
102 $query['type'] = $this->typeCGI; // arrays won't work here
103 $query['user'] = $this->performer;
104 $query['day'] = $this->mDay;
105 $query['month'] = $this->mMonth;
106 $query['year'] = $this->mYear;
107
108 return $query;
109 }
110
111 private function limitFilterTypes() {
112 if ( $this->hasEqualsClause( 'log_id' ) ) { // T220834
113 return;
114 }
115 $filterTypes = $this->getFilterParams();
116 foreach ( $filterTypes as $type => $hide ) {
117 if ( $hide ) {
118 $this->mConds[] = 'log_type != ' . $this->mDb->addQuotes( $type );
119 }
120 }
121 }
122
123 public function getFilterParams() {
124 global $wgFilterLogTypes;
125 $filters = [];
126 if ( count( $this->types ) ) {
127 return $filters;
128 }
129
130 $wpfilters = $this->getRequest()->getArray( "wpfilters" );
131 $request_filters = $wpfilters === null ? [] : $wpfilters;
132
133 foreach ( $wgFilterLogTypes as $type => $default ) {
134 $hide = !in_array( $type, $request_filters );
135
136 // Back-compat: Check old URL params if the new param wasn't passed
137 if ( $wpfilters === null ) {
138 $hide = $this->getRequest()->getBool( "hide_{$type}_log", $default );
139 }
140
141 $filters[$type] = $hide;
142 }
143
144 return $filters;
145 }
146
147 /**
148 * Set the log reader to return only entries of the given type.
149 * Type restrictions enforced here
150 *
151 * @param string|array $types Log types ('upload', 'delete', etc);
152 * empty string means no restriction
153 */
154 private function limitType( $types ) {
155 global $wgLogRestrictions;
156
157 $user = $this->getUser();
158 // If $types is not an array, make it an array
159 $types = ( $types === '' ) ? [] : (array)$types;
160 // Don't even show header for private logs; don't recognize it...
161 $needReindex = false;
162 foreach ( $types as $type ) {
163 if ( isset( $wgLogRestrictions[$type] )
164 && !MediaWikiServices::getInstance()
165 ->getPermissionManager()
166 ->userHasRight( $user, $wgLogRestrictions[$type] )
167 ) {
168 $needReindex = true;
169 $types = array_diff( $types, [ $type ] );
170 }
171 }
172 if ( $needReindex ) {
173 // Lots of this code makes assumptions that
174 // the first entry in the array is $types[0].
175 $types = array_values( $types );
176 }
177 $this->types = $types;
178 // Don't show private logs to unprivileged users.
179 // Also, only show them upon specific request to avoid suprises.
180 $audience = $types ? 'user' : 'public';
181 $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience, $user );
182 if ( $hideLogs !== false ) {
183 $this->mConds[] = $hideLogs;
184 }
185 if ( count( $types ) ) {
186 $this->mConds['log_type'] = $types;
187 // Set typeCGI; used in url param for paging
188 if ( count( $types ) == 1 ) {
189 $this->typeCGI = $types[0];
190 }
191 }
192 }
193
194 /**
195 * Set the log reader to return only entries by the given user.
196 *
197 * @param string $name (In)valid user name
198 * @return void
199 */
200 private function limitPerformer( $name ) {
201 if ( $name == '' ) {
202 return;
203 }
204 $usertitle = Title::makeTitleSafe( NS_USER, $name );
205 if ( is_null( $usertitle ) ) {
206 return;
207 }
208 // Normalize username first so that non-existent users used
209 // in maintenance scripts work
210 $name = $usertitle->getText();
211
212 // Assume no joins required for log_user
213 $this->mConds[] = ActorMigration::newMigration()->getWhere(
214 wfGetDB( DB_REPLICA ), 'log_user', User::newFromName( $name, false )
215 )['conds'];
216
217 $this->enforcePerformerRestrictions();
218
219 $this->performer = $name;
220 }
221
222 /**
223 * Set the log reader to return only entries affecting the given page.
224 * (For the block and rights logs, this is a user page.)
225 *
226 * @param string|Title $page Title name
227 * @param bool $pattern
228 * @return void
229 */
230 private function limitTitle( $page, $pattern ) {
231 global $wgMiserMode, $wgUserrightsInterwikiDelimiter;
232
233 if ( $page instanceof Title ) {
234 $title = $page;
235 } else {
236 $title = Title::newFromText( $page );
237 if ( strlen( $page ) == 0 || !$title instanceof Title ) {
238 return;
239 }
240 }
241
242 $this->title = $title->getPrefixedText();
243 $ns = $title->getNamespace();
244 $db = $this->mDb;
245
246 $doUserRightsLogLike = false;
247 if ( $this->types == [ 'rights' ] ) {
248 $parts = explode( $wgUserrightsInterwikiDelimiter, $title->getDBkey() );
249 if ( count( $parts ) == 2 ) {
250 list( $name, $database ) = array_map( 'trim', $parts );
251 if ( strstr( $database, '*' ) ) { // Search for wildcard in database name
252 $doUserRightsLogLike = true;
253 }
254 }
255 }
256
257 /**
258 * Using the (log_namespace, log_title, log_timestamp) index with a
259 * range scan (LIKE) on the first two parts, instead of simple equality,
260 * makes it unusable for sorting. Sorted retrieval using another index
261 * would be possible, but then we might have to scan arbitrarily many
262 * nodes of that index. Therefore, we need to avoid this if $wgMiserMode
263 * is on.
264 *
265 * This is not a problem with simple title matches, because then we can
266 * use the page_time index. That should have no more than a few hundred
267 * log entries for even the busiest pages, so it can be safely scanned
268 * in full to satisfy an impossible condition on user or similar.
269 */
270 $this->mConds['log_namespace'] = $ns;
271 if ( $doUserRightsLogLike ) {
272 $params = [ $name . $wgUserrightsInterwikiDelimiter ];
273 foreach ( explode( '*', $database ) as $databasepart ) {
274 $params[] = $databasepart;
275 $params[] = $db->anyString();
276 }
277 array_pop( $params ); // Get rid of the last % we added.
278 $this->mConds[] = 'log_title' . $db->buildLike( ...$params );
279 } elseif ( $pattern && !$wgMiserMode ) {
280 $this->mConds[] = 'log_title' . $db->buildLike( $title->getDBkey(), $db->anyString() );
281 $this->pattern = $pattern;
282 } else {
283 $this->mConds['log_title'] = $title->getDBkey();
284 }
285 $this->enforceActionRestrictions();
286 }
287
288 /**
289 * Set the log_action field to a specified value (or values)
290 *
291 * @param string $action
292 */
293 private function limitAction( $action ) {
294 global $wgActionFilteredLogs;
295 // Allow to filter the log by actions
296 $type = $this->typeCGI;
297 if ( $type === '' ) {
298 // nothing to do
299 return;
300 }
301 $actions = $wgActionFilteredLogs;
302 if ( isset( $actions[$type] ) ) {
303 // log type can be filtered by actions
304 $this->mLogEventsList->setAllowedActions( array_keys( $actions[$type] ) );
305 if ( $action !== '' && isset( $actions[$type][$action] ) ) {
306 // add condition to query
307 $this->mConds['log_action'] = $actions[$type][$action];
308 $this->action = $action;
309 }
310 }
311 }
312
313 /**
314 * Limit to the (single) specified log ID.
315 * @param int $logId The log entry ID.
316 */
317 protected function limitLogId( $logId ) {
318 if ( !$logId ) {
319 return;
320 }
321 $this->mConds['log_id'] = $logId;
322 }
323
324 /**
325 * Constructs the most part of the query. Extra conditions are sprinkled in
326 * all over this class.
327 * @return array
328 */
329 public function getQueryInfo() {
330 $basic = DatabaseLogEntry::getSelectQueryData();
331
332 $tables = $basic['tables'];
333 $fields = $basic['fields'];
334 $conds = $basic['conds'];
335 $options = $basic['options'];
336 $joins = $basic['join_conds'];
337
338 # Add log_search table if there are conditions on it.
339 # This filters the results to only include log rows that have
340 # log_search records with the specified ls_field and ls_value values.
341 if ( array_key_exists( 'ls_field', $this->mConds ) ) {
342 $tables[] = 'log_search';
343 $options['IGNORE INDEX'] = [ 'log_search' => 'ls_log_id' ];
344 $options['USE INDEX'] = [ 'logging' => 'PRIMARY' ];
345 if ( !$this->hasEqualsClause( 'ls_field' )
346 || !$this->hasEqualsClause( 'ls_value' )
347 ) {
348 # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
349 # to match a specific (ls_field,ls_value) tuple, then there will be
350 # no duplicate log rows. Otherwise, we need to remove the duplicates.
351 $options[] = 'DISTINCT';
352 }
353 }
354 # Don't show duplicate rows when using log_search
355 $joins['log_search'] = [ 'JOIN', 'ls_log_id=log_id' ];
356
357 // T221458: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
358 // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
359 // Tell it not to reorder the query. But not when tag filtering or log_search was used, as it
360 // seems as likely to be harmed as helped in that case.
361 if ( !$this->mTagFilter && !array_key_exists( 'ls_field', $this->mConds ) ) {
362 $options[] = 'STRAIGHT_JOIN';
363 }
364 if ( $this->performer !== '' ) {
365 // T223151: MariaDB's optimizer, at least 10.1, likes to choose a wildly bad plan for
366 // some reason for this code path. Tell it not to use the wrong index it wants to pick.
367 $options['IGNORE INDEX'] = [ 'logging' => [ 'times' ] ];
368 }
369
370 $info = [
371 'tables' => $tables,
372 'fields' => $fields,
373 'conds' => array_merge( $conds, $this->mConds ),
374 'options' => $options,
375 'join_conds' => $joins,
376 ];
377 # Add ChangeTags filter query
378 ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
379 $info['join_conds'], $info['options'], $this->mTagFilter );
380
381 return $info;
382 }
383
384 /**
385 * Checks if $this->mConds has $field matched to a *single* value
386 * @param string $field
387 * @return bool
388 */
389 protected function hasEqualsClause( $field ) {
390 return (
391 array_key_exists( $field, $this->mConds ) &&
392 ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
393 );
394 }
395
396 function getIndexField() {
397 return 'log_timestamp';
398 }
399
400 protected function getStartBody() {
401 # Do a link batch query
402 if ( $this->getNumRows() > 0 ) {
403 $lb = new LinkBatch;
404 foreach ( $this->mResult as $row ) {
405 $lb->add( $row->log_namespace, $row->log_title );
406 $lb->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) );
407 $lb->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->user_name ) );
408 $formatter = LogFormatter::newFromRow( $row );
409 foreach ( $formatter->getPreloadTitles() as $title ) {
410 $lb->addObj( $title );
411 }
412 }
413 $lb->execute();
414 $this->mResult->seek( 0 );
415 }
416
417 return '';
418 }
419
420 public function formatRow( $row ) {
421 return $this->mLogEventsList->logLine( $row );
422 }
423
424 public function getType() {
425 return $this->types;
426 }
427
428 /**
429 * Guaranteed to either return a valid title string or a Zero-Length String
430 *
431 * @return string
432 */
433 public function getPerformer() {
434 return $this->performer;
435 }
436
437 /**
438 * @return string
439 */
440 public function getPage() {
441 return $this->title;
442 }
443
444 /**
445 * @return bool
446 */
447 public function getPattern() {
448 return $this->pattern;
449 }
450
451 public function getYear() {
452 return $this->mYear;
453 }
454
455 public function getMonth() {
456 return $this->mMonth;
457 }
458
459 public function getDay() {
460 return $this->mDay;
461 }
462
463 public function getTagFilter() {
464 return $this->mTagFilter;
465 }
466
467 public function getAction() {
468 return $this->action;
469 }
470
471 public function doQuery() {
472 // Workaround MySQL optimizer bug
473 $this->mDb->setBigSelects();
474 parent::doQuery();
475 $this->mDb->setBigSelects( 'default' );
476 }
477
478 /**
479 * Paranoia: avoid brute force searches (T19342)
480 */
481 private function enforceActionRestrictions() {
482 if ( $this->actionRestrictionsEnforced ) {
483 return;
484 }
485 $this->actionRestrictionsEnforced = true;
486 $user = $this->getUser();
487 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
488 if ( !$permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
489 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_ACTION ) . ' = 0';
490 } elseif ( !$permissionManager->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' ) ) {
491 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_ACTION ) .
492 ' != ' . LogPage::SUPPRESSED_USER;
493 }
494 }
495
496 /**
497 * Paranoia: avoid brute force searches (T19342)
498 */
499 private function enforcePerformerRestrictions() {
500 // Same as enforceActionRestrictions(), except for _USER instead of _ACTION bits.
501 if ( $this->performerRestrictionsEnforced ) {
502 return;
503 }
504 $this->performerRestrictionsEnforced = true;
505 $user = $this->getUser();
506 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
507 if ( !$permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
508 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_USER ) . ' = 0';
509 } elseif ( !$permissionManager->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' ) ) {
510 $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_USER ) .
511 ' != ' . LogPage::SUPPRESSED_ACTION;
512 }
513 }
514 }