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