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