Merge "RevisionStoreDbTestBase, remove redundant needsDB override"
[lhc/web/wiklou.git] / includes / api / ApiQueryLogEvents.php
1 <?php
2 /**
3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\MediaWikiServices;
24 use MediaWiki\Storage\NameTableAccessException;
25
26 /**
27 * Query action to List the log events, with optional filtering by various parameters.
28 *
29 * @ingroup API
30 */
31 class ApiQueryLogEvents extends ApiQueryBase {
32
33 private $commentStore;
34
35 public function __construct( ApiQuery $query, $moduleName ) {
36 parent::__construct( $query, $moduleName, 'le' );
37 }
38
39 private $fld_ids = false, $fld_title = false, $fld_type = false,
40 $fld_user = false, $fld_userid = false,
41 $fld_timestamp = false, $fld_comment = false, $fld_parsedcomment = false,
42 $fld_details = false, $fld_tags = false;
43
44 public function execute() {
45 global $wgChangeTagsSchemaMigrationStage;
46
47 $params = $this->extractRequestParams();
48 $db = $this->getDB();
49 $this->commentStore = CommentStore::getStore();
50 $this->requireMaxOneParameter( $params, 'title', 'prefix', 'namespace' );
51
52 $prop = array_flip( $params['prop'] );
53
54 $this->fld_ids = isset( $prop['ids'] );
55 $this->fld_title = isset( $prop['title'] );
56 $this->fld_type = isset( $prop['type'] );
57 $this->fld_user = isset( $prop['user'] );
58 $this->fld_userid = isset( $prop['userid'] );
59 $this->fld_timestamp = isset( $prop['timestamp'] );
60 $this->fld_comment = isset( $prop['comment'] );
61 $this->fld_parsedcomment = isset( $prop['parsedcomment'] );
62 $this->fld_details = isset( $prop['details'] );
63 $this->fld_tags = isset( $prop['tags'] );
64
65 $hideLogs = LogEventsList::getExcludeClause( $db, 'user', $this->getUser() );
66 if ( $hideLogs !== false ) {
67 $this->addWhere( $hideLogs );
68 }
69
70 $actorMigration = ActorMigration::newMigration();
71 $actorQuery = $actorMigration->getJoin( 'log_user' );
72 $this->addTables( 'logging' );
73 $this->addTables( $actorQuery['tables'] );
74 $this->addTables( [ 'user', 'page' ] );
75 $this->addJoinConds( $actorQuery['joins'] );
76 $this->addJoinConds( [
77 'user' => [ 'LEFT JOIN',
78 'user_id=' . $actorQuery['fields']['log_user'] ],
79 'page' => [ 'LEFT JOIN',
80 [ 'log_namespace=page_namespace',
81 'log_title=page_title' ] ] ] );
82
83 $this->addFields( [
84 'log_id',
85 'log_type',
86 'log_action',
87 'log_timestamp',
88 'log_deleted',
89 ] );
90
91 $this->addFieldsIf( 'page_id', $this->fld_ids );
92 // log_page is the page_id saved at log time, whereas page_id is from a
93 // join at query time. This leads to different results in various
94 // scenarios, e.g. deletion, recreation.
95 $this->addFieldsIf( 'log_page', $this->fld_ids );
96 $this->addFieldsIf( $actorQuery['fields'] + [ 'user_name' ], $this->fld_user );
97 $this->addFieldsIf( $actorQuery['fields'], $this->fld_userid );
98 $this->addFieldsIf(
99 [ 'log_namespace', 'log_title' ],
100 $this->fld_title || $this->fld_parsedcomment
101 );
102 $this->addFieldsIf( 'log_params', $this->fld_details );
103
104 if ( $this->fld_comment || $this->fld_parsedcomment ) {
105 $commentQuery = $this->commentStore->getJoin( 'log_comment' );
106 $this->addTables( $commentQuery['tables'] );
107 $this->addFields( $commentQuery['fields'] );
108 $this->addJoinConds( $commentQuery['joins'] );
109 }
110
111 if ( $this->fld_tags ) {
112 $this->addTables( 'tag_summary' );
113 $this->addJoinConds( [ 'tag_summary' => [ 'LEFT JOIN', 'log_id=ts_log_id' ] ] );
114 $this->addFields( 'ts_tags' );
115 }
116
117 if ( !is_null( $params['tag'] ) ) {
118 $this->addTables( 'change_tag' );
119 $this->addJoinConds( [ 'change_tag' => [ 'INNER JOIN',
120 [ 'log_id=ct_log_id' ] ] ] );
121 if ( $wgChangeTagsSchemaMigrationStage > MIGRATION_WRITE_BOTH ) {
122 $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
123 try {
124 $this->addWhereFld( 'ct_tag_id', $changeTagDefStore->getId( $params['tag'] ) );
125 } catch ( NameTableAccessException $exception ) {
126 // Return nothing.
127 $this->addWhere( '1=0' );
128 }
129 } else {
130 $this->addWhereFld( 'ct_tag', $params['tag'] );
131 }
132 }
133
134 if ( !is_null( $params['action'] ) ) {
135 // Do validation of action param, list of allowed actions can contains wildcards
136 // Allow the param, when the actions is in the list or a wildcard version is listed.
137 $logAction = $params['action'];
138 if ( strpos( $logAction, '/' ) === false ) {
139 // all items in the list have a slash
140 $valid = false;
141 } else {
142 $logActions = array_flip( $this->getAllowedLogActions() );
143 list( $type, $action ) = explode( '/', $logAction, 2 );
144 $valid = isset( $logActions[$logAction] ) || isset( $logActions[$type . '/*'] );
145 }
146
147 if ( !$valid ) {
148 $encParamName = $this->encodeParamName( 'action' );
149 $this->dieWithError(
150 [ 'apierror-unrecognizedvalue', $encParamName, wfEscapeWikiText( $logAction ) ],
151 "unknown_$encParamName"
152 );
153 }
154
155 $this->addWhereFld( 'log_type', $type );
156 $this->addWhereFld( 'log_action', $action );
157 } elseif ( !is_null( $params['type'] ) ) {
158 $this->addWhereFld( 'log_type', $params['type'] );
159 }
160
161 $this->addTimestampWhereRange(
162 'log_timestamp',
163 $params['dir'],
164 $params['start'],
165 $params['end']
166 );
167 // Include in ORDER BY for uniqueness
168 $this->addWhereRange( 'log_id', $params['dir'], null, null );
169
170 if ( !is_null( $params['continue'] ) ) {
171 $cont = explode( '|', $params['continue'] );
172 $this->dieContinueUsageIf( count( $cont ) != 2 );
173 $op = ( $params['dir'] === 'newer' ? '>' : '<' );
174 $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
175 $continueId = (int)$cont[1];
176 $this->dieContinueUsageIf( $continueId != $cont[1] );
177 $this->addWhere( "log_timestamp $op $continueTimestamp OR " .
178 "(log_timestamp = $continueTimestamp AND " .
179 "log_id $op= $continueId)"
180 );
181 }
182
183 $limit = $params['limit'];
184 $this->addOption( 'LIMIT', $limit + 1 );
185
186 $user = $params['user'];
187 if ( !is_null( $user ) ) {
188 // Note the joins in $q are the same as those from ->getJoin() above
189 // so we only need to add 'conds' here.
190 $q = $actorMigration->getWhere(
191 $db, 'log_user', User::newFromName( $params['user'], false )
192 );
193 $this->addWhere( $q['conds'] );
194 }
195
196 $title = $params['title'];
197 if ( !is_null( $title ) ) {
198 $titleObj = Title::newFromText( $title );
199 if ( is_null( $titleObj ) ) {
200 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $title ) ] );
201 }
202 $this->addWhereFld( 'log_namespace', $titleObj->getNamespace() );
203 $this->addWhereFld( 'log_title', $titleObj->getDBkey() );
204 }
205
206 if ( $params['namespace'] !== null ) {
207 $this->addWhereFld( 'log_namespace', $params['namespace'] );
208 }
209
210 $prefix = $params['prefix'];
211
212 if ( !is_null( $prefix ) ) {
213 if ( $this->getConfig()->get( 'MiserMode' ) ) {
214 $this->dieWithError( 'apierror-prefixsearchdisabled' );
215 }
216
217 $title = Title::newFromText( $prefix );
218 if ( is_null( $title ) ) {
219 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $prefix ) ] );
220 }
221 $this->addWhereFld( 'log_namespace', $title->getNamespace() );
222 $this->addWhere( 'log_title ' . $db->buildLike( $title->getDBkey(), $db->anyString() ) );
223 }
224
225 // Paranoia: avoid brute force searches (T19342)
226 if ( $params['namespace'] !== null || !is_null( $title ) || !is_null( $user ) ) {
227 if ( !$this->getUser()->isAllowed( 'deletedhistory' ) ) {
228 $titleBits = LogPage::DELETED_ACTION;
229 $userBits = LogPage::DELETED_USER;
230 } elseif ( !$this->getUser()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
231 $titleBits = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
232 $userBits = LogPage::DELETED_USER | LogPage::DELETED_RESTRICTED;
233 } else {
234 $titleBits = 0;
235 $userBits = 0;
236 }
237 if ( ( $params['namespace'] !== null || !is_null( $title ) ) && $titleBits ) {
238 $this->addWhere( $db->bitAnd( 'log_deleted', $titleBits ) . " != $titleBits" );
239 }
240 if ( !is_null( $user ) && $userBits ) {
241 $this->addWhere( $db->bitAnd( 'log_deleted', $userBits ) . " != $userBits" );
242 }
243 }
244
245 $count = 0;
246 $res = $this->select( __METHOD__ );
247 $result = $this->getResult();
248 foreach ( $res as $row ) {
249 if ( ++$count > $limit ) {
250 // We've reached the one extra which shows that there are
251 // additional pages to be had. Stop here...
252 $this->setContinueEnumParameter( 'continue', "$row->log_timestamp|$row->log_id" );
253 break;
254 }
255
256 $vals = $this->extractRowInfo( $row );
257 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $vals );
258 if ( !$fit ) {
259 $this->setContinueEnumParameter( 'continue', "$row->log_timestamp|$row->log_id" );
260 break;
261 }
262 }
263 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'item' );
264 }
265
266 /**
267 * @deprecated since 1.25 Use LogFormatter::formatParametersForApi instead
268 * @param ApiResult $result
269 * @param array &$vals
270 * @param string $params
271 * @param string $type
272 * @param string $action
273 * @param string $ts
274 * @param bool $legacy
275 * @return array
276 */
277 public static function addLogParams( $result, &$vals, $params, $type,
278 $action, $ts, $legacy = false
279 ) {
280 wfDeprecated( __METHOD__, '1.25' );
281
282 $entry = new ManualLogEntry( $type, $action );
283 $entry->setParameters( $params );
284 $entry->setTimestamp( $ts );
285 $entry->setLegacy( $legacy );
286 $formatter = LogFormatter::newFromEntry( $entry );
287 $vals['params'] = $formatter->formatParametersForApi();
288
289 return $vals;
290 }
291
292 private function extractRowInfo( $row ) {
293 $logEntry = DatabaseLogEntry::newFromRow( $row );
294 $vals = [
295 ApiResult::META_TYPE => 'assoc',
296 ];
297 $anyHidden = false;
298 $user = $this->getUser();
299
300 if ( $this->fld_ids ) {
301 $vals['logid'] = intval( $row->log_id );
302 }
303
304 if ( $this->fld_title || $this->fld_parsedcomment ) {
305 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
306 }
307
308 if ( $this->fld_title || $this->fld_ids || $this->fld_details && $row->log_params !== '' ) {
309 if ( LogEventsList::isDeleted( $row, LogPage::DELETED_ACTION ) ) {
310 $vals['actionhidden'] = true;
311 $anyHidden = true;
312 }
313 if ( LogEventsList::userCan( $row, LogPage::DELETED_ACTION, $user ) ) {
314 if ( $this->fld_title ) {
315 ApiQueryBase::addTitleInfo( $vals, $title );
316 }
317 if ( $this->fld_ids ) {
318 $vals['pageid'] = intval( $row->page_id );
319 $vals['logpage'] = intval( $row->log_page );
320 }
321 if ( $this->fld_details ) {
322 $vals['params'] = LogFormatter::newFromEntry( $logEntry )->formatParametersForApi();
323 }
324 }
325 }
326
327 if ( $this->fld_type ) {
328 $vals['type'] = $row->log_type;
329 $vals['action'] = $row->log_action;
330 }
331
332 if ( $this->fld_user || $this->fld_userid ) {
333 if ( LogEventsList::isDeleted( $row, LogPage::DELETED_USER ) ) {
334 $vals['userhidden'] = true;
335 $anyHidden = true;
336 }
337 if ( LogEventsList::userCan( $row, LogPage::DELETED_USER, $user ) ) {
338 if ( $this->fld_user ) {
339 $vals['user'] = $row->user_name ?? $row->log_user_text;
340 }
341 if ( $this->fld_userid ) {
342 $vals['userid'] = intval( $row->log_user );
343 }
344
345 if ( !$row->log_user ) {
346 $vals['anon'] = true;
347 }
348 }
349 }
350 if ( $this->fld_timestamp ) {
351 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $row->log_timestamp );
352 }
353
354 if ( $this->fld_comment || $this->fld_parsedcomment ) {
355 if ( LogEventsList::isDeleted( $row, LogPage::DELETED_COMMENT ) ) {
356 $vals['commenthidden'] = true;
357 $anyHidden = true;
358 }
359 if ( LogEventsList::userCan( $row, LogPage::DELETED_COMMENT, $user ) ) {
360 $comment = $this->commentStore->getComment( 'log_comment', $row )->text;
361 if ( $this->fld_comment ) {
362 $vals['comment'] = $comment;
363 }
364
365 if ( $this->fld_parsedcomment ) {
366 $vals['parsedcomment'] = Linker::formatComment( $comment, $title );
367 }
368 }
369 }
370
371 if ( $this->fld_tags ) {
372 if ( $row->ts_tags ) {
373 $tags = explode( ',', $row->ts_tags );
374 ApiResult::setIndexedTagName( $tags, 'tag' );
375 $vals['tags'] = $tags;
376 } else {
377 $vals['tags'] = [];
378 }
379 }
380
381 if ( $anyHidden && LogEventsList::isDeleted( $row, LogPage::DELETED_RESTRICTED ) ) {
382 $vals['suppressed'] = true;
383 }
384
385 return $vals;
386 }
387
388 /**
389 * @return array
390 */
391 private function getAllowedLogActions() {
392 $config = $this->getConfig();
393 return array_keys( array_merge(
394 $config->get( 'LogActions' ),
395 $config->get( 'LogActionsHandlers' )
396 ) );
397 }
398
399 public function getCacheMode( $params ) {
400 if ( $this->userCanSeeRevDel() ) {
401 return 'private';
402 }
403 if ( !is_null( $params['prop'] ) && in_array( 'parsedcomment', $params['prop'] ) ) {
404 // formatComment() calls wfMessage() among other things
405 return 'anon-public-user-private';
406 } elseif ( LogEventsList::getExcludeClause( $this->getDB(), 'user', $this->getUser() )
407 === LogEventsList::getExcludeClause( $this->getDB(), 'public' )
408 ) { // Output can only contain public data.
409 return 'public';
410 } else {
411 return 'anon-public-user-private';
412 }
413 }
414
415 public function getAllowedParams( $flags = 0 ) {
416 $config = $this->getConfig();
417 $ret = [
418 'prop' => [
419 ApiBase::PARAM_ISMULTI => true,
420 ApiBase::PARAM_DFLT => 'ids|title|type|user|timestamp|comment|details',
421 ApiBase::PARAM_TYPE => [
422 'ids',
423 'title',
424 'type',
425 'user',
426 'userid',
427 'timestamp',
428 'comment',
429 'parsedcomment',
430 'details',
431 'tags'
432 ],
433 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
434 ],
435 'type' => [
436 ApiBase::PARAM_TYPE => LogPage::validTypes(),
437 ],
438 'action' => [
439 // validation on request is done in execute()
440 ApiBase::PARAM_TYPE => ( $flags & ApiBase::GET_VALUES_FOR_HELP )
441 ? $this->getAllowedLogActions()
442 : null
443 ],
444 'start' => [
445 ApiBase::PARAM_TYPE => 'timestamp'
446 ],
447 'end' => [
448 ApiBase::PARAM_TYPE => 'timestamp'
449 ],
450 'dir' => [
451 ApiBase::PARAM_DFLT => 'older',
452 ApiBase::PARAM_TYPE => [
453 'newer',
454 'older'
455 ],
456 ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
457 ],
458 'user' => [
459 ApiBase::PARAM_TYPE => 'user',
460 ],
461 'title' => null,
462 'namespace' => [
463 ApiBase::PARAM_TYPE => 'namespace',
464 ApiBase::PARAM_EXTRA_NAMESPACES => [ NS_MEDIA, NS_SPECIAL ],
465 ],
466 'prefix' => [],
467 'tag' => null,
468 'limit' => [
469 ApiBase::PARAM_DFLT => 10,
470 ApiBase::PARAM_TYPE => 'limit',
471 ApiBase::PARAM_MIN => 1,
472 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
473 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
474 ],
475 'continue' => [
476 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
477 ],
478 ];
479
480 if ( $config->get( 'MiserMode' ) ) {
481 $ret['prefix'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
482 }
483
484 return $ret;
485 }
486
487 protected function getExamplesMessages() {
488 return [
489 'action=query&list=logevents'
490 => 'apihelp-query+logevents-example-simple',
491 ];
492 }
493
494 public function getHelpUrls() {
495 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Logevents';
496 }
497 }