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