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