Merge "Provide command to adjust phpunit.xml for code coverage"
[lhc/web/wiklou.git] / includes / api / ApiQueryRevisions.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\Revision\RevisionRecord;
25 use MediaWiki\Storage\NameTableAccessException;
26
27 /**
28 * A query action to enumerate revisions of a given page, or show top revisions
29 * of multiple pages. Various pieces of information may be shown - flags,
30 * comments, and the actual wiki markup of the rev. In the enumeration mode,
31 * ranges of revisions may be requested and filtered.
32 *
33 * @ingroup API
34 */
35 class ApiQueryRevisions extends ApiQueryRevisionsBase {
36
37 private $token = null;
38
39 public function __construct( ApiQuery $query, $moduleName ) {
40 parent::__construct( $query, $moduleName, 'rv' );
41 }
42
43 private $tokenFunctions;
44
45 /** @deprecated since 1.24 */
46 protected function getTokenFunctions() {
47 // tokenname => function
48 // function prototype is func($pageid, $title, $rev)
49 // should return token or false
50
51 // Don't call the hooks twice
52 if ( isset( $this->tokenFunctions ) ) {
53 return $this->tokenFunctions;
54 }
55
56 // If we're in a mode that breaks the same-origin policy, no tokens can
57 // be obtained
58 if ( $this->lacksSameOriginSecurity() ) {
59 return [];
60 }
61
62 $this->tokenFunctions = [
63 'rollback' => [ self::class, 'getRollbackToken' ]
64 ];
65 Hooks::run( 'APIQueryRevisionsTokens', [ &$this->tokenFunctions ] );
66
67 return $this->tokenFunctions;
68 }
69
70 /**
71 * @deprecated since 1.24
72 * @param int $pageid
73 * @param Title $title
74 * @param Revision $rev
75 * @return bool|string
76 */
77 public static function getRollbackToken( $pageid, $title, $rev ) {
78 global $wgUser;
79 if ( !MediaWikiServices::getInstance()->getPermissionManager()
80 ->userHasRight( $wgUser, 'rollback' ) ) {
81 return false;
82 }
83
84 return $wgUser->getEditToken( 'rollback' );
85 }
86
87 protected function run( ApiPageSet $resultPageSet = null ) {
88 $params = $this->extractRequestParams( false );
89 $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
90
91 // If any of those parameters are used, work in 'enumeration' mode.
92 // Enum mode can only be used when exactly one page is provided.
93 // Enumerating revisions on multiple pages make it extremely
94 // difficult to manage continuations and require additional SQL indexes
95 $enumRevMode = ( $params['user'] !== null || $params['excludeuser'] !== null ||
96 $params['limit'] !== null || $params['startid'] !== null ||
97 $params['endid'] !== null || $params['dir'] === 'newer' ||
98 $params['start'] !== null || $params['end'] !== null );
99
100 $pageSet = $this->getPageSet();
101 $pageCount = $pageSet->getGoodTitleCount();
102 $revCount = $pageSet->getRevisionCount();
103
104 // Optimization -- nothing to do
105 if ( $revCount === 0 && $pageCount === 0 ) {
106 // Nothing to do
107 return;
108 }
109 if ( $revCount > 0 && count( $pageSet->getLiveRevisionIDs() ) === 0 ) {
110 // We're in revisions mode but all given revisions are deleted
111 return;
112 }
113
114 if ( $revCount > 0 && $enumRevMode ) {
115 $this->dieWithError(
116 [ 'apierror-revisions-norevids', $this->getModulePrefix() ], 'invalidparammix'
117 );
118 }
119
120 if ( $pageCount > 1 && $enumRevMode ) {
121 $this->dieWithError(
122 [ 'apierror-revisions-singlepage', $this->getModulePrefix() ], 'invalidparammix'
123 );
124 }
125
126 // In non-enum mode, rvlimit can't be directly used. Use the maximum
127 // allowed value.
128 if ( !$enumRevMode ) {
129 $this->setParsedLimit = false;
130 $params['limit'] = 'max';
131 }
132
133 $db = $this->getDB();
134
135 $idField = 'rev_id';
136 $tsField = 'rev_timestamp';
137 $pageField = 'rev_page';
138 if ( $params['user'] !== null ) {
139 // We're going to want to use the page_actor_timestamp index (on revision_actor_temp)
140 // so use that table's denormalized fields.
141 $idField = 'revactor_rev';
142 $tsField = 'revactor_timestamp';
143 $pageField = 'revactor_page';
144 }
145
146 if ( $resultPageSet === null ) {
147 $this->parseParameters( $params );
148 $this->token = $params['token'];
149 $opts = [];
150 if ( $this->token !== null || $pageCount > 0 ) {
151 $opts[] = 'page';
152 }
153 if ( $this->fld_user ) {
154 $opts[] = 'user';
155 }
156 $revQuery = $revisionStore->getQueryInfo( $opts );
157
158 if ( $idField !== 'rev_id' ) {
159 $aliasFields = [ 'rev_id' => $idField, 'rev_timestamp' => $tsField, 'rev_page' => $pageField ];
160 $revQuery['fields'] = array_merge(
161 $aliasFields,
162 array_diff( $revQuery['fields'], array_keys( $aliasFields ) )
163 );
164 }
165
166 $this->addTables( $revQuery['tables'] );
167 $this->addFields( $revQuery['fields'] );
168 $this->addJoinConds( $revQuery['joins'] );
169 } else {
170 $this->limit = $this->getParameter( 'limit' ) ?: 10;
171 // Always join 'page' so orphaned revisions are filtered out
172 $this->addTables( [ 'revision', 'page' ] );
173 $this->addJoinConds(
174 [ 'page' => [ 'JOIN', [ 'page_id = rev_page' ] ] ]
175 );
176 $this->addFields( [
177 'rev_id' => $idField, 'rev_timestamp' => $tsField, 'rev_page' => $pageField
178 ] );
179 }
180
181 if ( $this->fld_tags ) {
182 $this->addFields( [ 'ts_tags' => ChangeTags::makeTagSummarySubquery( 'revision' ) ] );
183 }
184
185 if ( $params['tag'] !== null ) {
186 $this->addTables( 'change_tag' );
187 $this->addJoinConds(
188 [ 'change_tag' => [ 'JOIN', [ 'rev_id=ct_rev_id' ] ] ]
189 );
190 $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
191 try {
192 $this->addWhereFld( 'ct_tag_id', $changeTagDefStore->getId( $params['tag'] ) );
193 } catch ( NameTableAccessException $exception ) {
194 // Return nothing.
195 $this->addWhere( '1=0' );
196 }
197 }
198
199 if ( $resultPageSet === null && $this->fetchContent ) {
200 // For each page we will request, the user must have read rights for that page
201 $status = Status::newGood();
202 $user = $this->getUser();
203
204 /** @var Title $title */
205 foreach ( $pageSet->getGoodTitles() as $title ) {
206 if ( !$this->getPermissionManager()->userCan( 'read', $user, $title ) ) {
207 $status->fatal( ApiMessage::create(
208 [ 'apierror-cannotviewtitle', wfEscapeWikiText( $title->getPrefixedText() ) ],
209 'accessdenied'
210 ) );
211 }
212 }
213 if ( !$status->isGood() ) {
214 $this->dieStatus( $status );
215 }
216 }
217
218 if ( $enumRevMode ) {
219 // Indexes targeted:
220 // page_timestamp if we don't have rvuser
221 // page_actor_timestamp (on revision_actor_temp) if we have rvuser in READ_NEW mode
222 // page_user_timestamp if we have a logged-in rvuser
223 // page_timestamp or usertext_timestamp if we have an IP rvuser
224
225 // This is mostly to prevent parameter errors (and optimize SQL?)
226 $this->requireMaxOneParameter( $params, 'startid', 'start' );
227 $this->requireMaxOneParameter( $params, 'endid', 'end' );
228 $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
229
230 if ( $params['continue'] !== null ) {
231 $cont = explode( '|', $params['continue'] );
232 $this->dieContinueUsageIf( count( $cont ) != 2 );
233 $op = ( $params['dir'] === 'newer' ? '>' : '<' );
234 $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
235 $continueId = (int)$cont[1];
236 $this->dieContinueUsageIf( $continueId != $cont[1] );
237 $this->addWhere( "$tsField $op $continueTimestamp OR " .
238 "($tsField = $continueTimestamp AND " .
239 "$idField $op= $continueId)"
240 );
241 }
242
243 // Convert startid/endid to timestamps (T163532)
244 $revids = [];
245 if ( $params['startid'] !== null ) {
246 $revids[] = (int)$params['startid'];
247 }
248 if ( $params['endid'] !== null ) {
249 $revids[] = (int)$params['endid'];
250 }
251 if ( $revids ) {
252 $db = $this->getDB();
253 $sql = $db->unionQueries( [
254 $db->selectSQLText(
255 'revision',
256 [ 'id' => 'rev_id', 'ts' => 'rev_timestamp' ],
257 [ 'rev_id' => $revids ],
258 __METHOD__
259 ),
260 $db->selectSQLText(
261 'archive',
262 [ 'id' => 'ar_rev_id', 'ts' => 'ar_timestamp' ],
263 [ 'ar_rev_id' => $revids ],
264 __METHOD__
265 ),
266 ], $db::UNION_DISTINCT );
267 $res = $db->query( $sql, __METHOD__ );
268 foreach ( $res as $row ) {
269 if ( (int)$row->id === (int)$params['startid'] ) {
270 $params['start'] = $row->ts;
271 }
272 if ( (int)$row->id === (int)$params['endid'] ) {
273 $params['end'] = $row->ts;
274 }
275 }
276 if ( $params['startid'] !== null && $params['start'] === null ) {
277 $p = $this->encodeParamName( 'startid' );
278 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
279 }
280 if ( $params['endid'] !== null && $params['end'] === null ) {
281 $p = $this->encodeParamName( 'endid' );
282 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
283 }
284
285 if ( $params['start'] !== null ) {
286 $op = ( $params['dir'] === 'newer' ? '>' : '<' );
287 $ts = $db->addQuotes( $db->timestampOrNull( $params['start'] ) );
288 if ( $params['startid'] !== null ) {
289 $this->addWhere( "$tsField $op $ts OR "
290 . "$tsField = $ts AND $idField $op= " . (int)$params['startid'] );
291 } else {
292 $this->addWhere( "$tsField $op= $ts" );
293 }
294 }
295 if ( $params['end'] !== null ) {
296 $op = ( $params['dir'] === 'newer' ? '<' : '>' ); // Yes, opposite of the above
297 $ts = $db->addQuotes( $db->timestampOrNull( $params['end'] ) );
298 if ( $params['endid'] !== null ) {
299 $this->addWhere( "$tsField $op $ts OR "
300 . "$tsField = $ts AND $idField $op= " . (int)$params['endid'] );
301 } else {
302 $this->addWhere( "$tsField $op= $ts" );
303 }
304 }
305 } else {
306 $this->addTimestampWhereRange( $tsField, $params['dir'],
307 $params['start'], $params['end'] );
308 }
309
310 $sort = ( $params['dir'] === 'newer' ? '' : 'DESC' );
311 $this->addOption( 'ORDER BY', [ "rev_timestamp $sort", "rev_id $sort" ] );
312
313 // There is only one ID, use it
314 $ids = array_keys( $pageSet->getGoodTitles() );
315 $this->addWhereFld( $pageField, reset( $ids ) );
316
317 if ( $params['user'] !== null ) {
318 $actorQuery = ActorMigration::newMigration()
319 ->getWhere( $db, 'rev_user', User::newFromName( $params['user'], false ) );
320 $this->addTables( $actorQuery['tables'] );
321 $this->addJoinConds( $actorQuery['joins'] );
322 $this->addWhere( $actorQuery['conds'] );
323 } elseif ( $params['excludeuser'] !== null ) {
324 $actorQuery = ActorMigration::newMigration()
325 ->getWhere( $db, 'rev_user', User::newFromName( $params['excludeuser'], false ) );
326 $this->addTables( $actorQuery['tables'] );
327 $this->addJoinConds( $actorQuery['joins'] );
328 $this->addWhere( 'NOT(' . $actorQuery['conds'] . ')' );
329 }
330 if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
331 // Paranoia: avoid brute force searches (T19342)
332 if ( !$this->getPermissionManager()->userHasRight( $this->getUser(), 'deletedhistory' ) ) {
333 $bitmask = RevisionRecord::DELETED_USER;
334 } elseif ( !$this->getPermissionManager()
335 ->userHasAnyRight( $this->getUser(), 'suppressrevision', 'viewsuppressed' )
336 ) {
337 $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
338 } else {
339 $bitmask = 0;
340 }
341 if ( $bitmask ) {
342 $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
343 }
344 }
345 } elseif ( $revCount > 0 ) {
346 // Always targets the PRIMARY index
347
348 $revs = $pageSet->getLiveRevisionIDs();
349
350 // Get all revision IDs
351 $this->addWhereFld( 'rev_id', array_keys( $revs ) );
352
353 if ( $params['continue'] !== null ) {
354 $this->addWhere( 'rev_id >= ' . (int)$params['continue'] );
355 }
356 $this->addOption( 'ORDER BY', 'rev_id' );
357 } elseif ( $pageCount > 0 ) {
358 // Always targets the rev_page_id index
359
360 $titles = $pageSet->getGoodTitles();
361
362 // When working in multi-page non-enumeration mode,
363 // limit to the latest revision only
364 $this->addWhere( 'page_latest=rev_id' );
365
366 // Get all page IDs
367 $this->addWhereFld( 'page_id', array_keys( $titles ) );
368 // Every time someone relies on equality propagation, god kills a kitten :)
369 $this->addWhereFld( 'rev_page', array_keys( $titles ) );
370
371 if ( $params['continue'] !== null ) {
372 $cont = explode( '|', $params['continue'] );
373 $this->dieContinueUsageIf( count( $cont ) != 2 );
374 $pageid = (int)$cont[0];
375 $revid = (int)$cont[1];
376 $this->addWhere(
377 "rev_page > $pageid OR " .
378 "(rev_page = $pageid AND " .
379 "rev_id >= $revid)"
380 );
381 }
382 $this->addOption( 'ORDER BY', [
383 'rev_page',
384 'rev_id'
385 ] );
386 } else {
387 ApiBase::dieDebug( __METHOD__, 'param validation?' );
388 }
389
390 $this->addOption( 'LIMIT', $this->limit + 1 );
391
392 // T224017: `rev_timestamp` is never the correct index to use for this module, but
393 // MariaDB (10.1.37-39) sometimes insists on trying to use it anyway. Tell it not to.
394 $this->addOption( 'IGNORE INDEX', [ 'revision' => 'rev_timestamp' ] );
395
396 $count = 0;
397 $generated = [];
398 $hookData = [];
399 $res = $this->select( __METHOD__, [], $hookData );
400
401 foreach ( $res as $row ) {
402 if ( ++$count > $this->limit ) {
403 // We've reached the one extra which shows that there are
404 // additional pages to be had. Stop here...
405 if ( $enumRevMode ) {
406 $this->setContinueEnumParameter( 'continue',
407 $row->rev_timestamp . '|' . (int)$row->rev_id );
408 } elseif ( $revCount > 0 ) {
409 $this->setContinueEnumParameter( 'continue', (int)$row->rev_id );
410 } else {
411 $this->setContinueEnumParameter( 'continue', (int)$row->rev_page .
412 '|' . (int)$row->rev_id );
413 }
414 break;
415 }
416
417 if ( $resultPageSet !== null ) {
418 $generated[] = $row->rev_id;
419 } else {
420 $revision = $revisionStore->newRevisionFromRow( $row );
421 $rev = $this->extractRevisionInfo( $revision, $row );
422
423 if ( $this->token !== null ) {
424 $title = Title::newFromLinkTarget( $revision->getPageAsLinkTarget() );
425 $revisionCompat = new Revision( $revision );
426 $tokenFunctions = $this->getTokenFunctions();
427 foreach ( $this->token as $t ) {
428 $val = call_user_func( $tokenFunctions[$t], $title->getArticleID(), $title, $revisionCompat );
429 if ( $val === false ) {
430 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
431 } else {
432 $rev[$t . 'token'] = $val;
433 }
434 }
435 }
436
437 $fit = $this->processRow( $row, $rev, $hookData ) &&
438 $this->addPageSubItem( $row->rev_page, $rev, 'rev' );
439 if ( !$fit ) {
440 if ( $enumRevMode ) {
441 $this->setContinueEnumParameter( 'continue',
442 $row->rev_timestamp . '|' . (int)$row->rev_id );
443 } elseif ( $revCount > 0 ) {
444 $this->setContinueEnumParameter( 'continue', (int)$row->rev_id );
445 } else {
446 $this->setContinueEnumParameter( 'continue', (int)$row->rev_page .
447 '|' . (int)$row->rev_id );
448 }
449 break;
450 }
451 }
452 }
453
454 if ( $resultPageSet !== null ) {
455 $resultPageSet->populateFromRevisionIDs( $generated );
456 }
457 }
458
459 public function getCacheMode( $params ) {
460 if ( isset( $params['token'] ) ) {
461 return 'private';
462 }
463 return parent::getCacheMode( $params );
464 }
465
466 public function getAllowedParams() {
467 $ret = parent::getAllowedParams() + [
468 'startid' => [
469 ApiBase::PARAM_TYPE => 'integer',
470 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
471 ],
472 'endid' => [
473 ApiBase::PARAM_TYPE => 'integer',
474 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
475 ],
476 'start' => [
477 ApiBase::PARAM_TYPE => 'timestamp',
478 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
479 ],
480 'end' => [
481 ApiBase::PARAM_TYPE => 'timestamp',
482 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
483 ],
484 'dir' => [
485 ApiBase::PARAM_DFLT => 'older',
486 ApiBase::PARAM_TYPE => [
487 'newer',
488 'older'
489 ],
490 ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
491 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
492 ],
493 'user' => [
494 ApiBase::PARAM_TYPE => 'user',
495 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
496 ],
497 'excludeuser' => [
498 ApiBase::PARAM_TYPE => 'user',
499 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
500 ],
501 'tag' => null,
502 'token' => [
503 ApiBase::PARAM_DEPRECATED => true,
504 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
505 ApiBase::PARAM_ISMULTI => true
506 ],
507 'continue' => [
508 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
509 ],
510 ];
511
512 $ret['limit'][ApiBase::PARAM_HELP_MSG_INFO] = [ [ 'singlepageonly' ] ];
513
514 return $ret;
515 }
516
517 protected function getExamplesMessages() {
518 return [
519 'action=query&prop=revisions&titles=API|Main%20Page&' .
520 'rvslots=*&rvprop=timestamp|user|comment|content'
521 => 'apihelp-query+revisions-example-content',
522 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
523 'rvprop=timestamp|user|comment'
524 => 'apihelp-query+revisions-example-last5',
525 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
526 'rvprop=timestamp|user|comment&rvdir=newer'
527 => 'apihelp-query+revisions-example-first5',
528 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
529 'rvprop=timestamp|user|comment&rvdir=newer&rvstart=2006-05-01T00:00:00Z'
530 => 'apihelp-query+revisions-example-first5-after',
531 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
532 'rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1'
533 => 'apihelp-query+revisions-example-first5-not-localhost',
534 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
535 'rvprop=timestamp|user|comment&rvuser=MediaWiki%20default'
536 => 'apihelp-query+revisions-example-first5-user',
537 ];
538 }
539
540 public function getHelpUrls() {
541 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Revisions';
542 }
543 }