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