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