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