3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
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.
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.
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
23 use MediaWiki\MediaWikiServices
;
24 use MediaWiki\Revision\RevisionRecord
;
25 use MediaWiki\Storage\NameTableAccessException
;
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.
35 class ApiQueryRevisions
extends ApiQueryRevisionsBase
{
37 private $token = null;
39 public function __construct( ApiQuery
$query, $moduleName ) {
40 parent
::__construct( $query, $moduleName, 'rv' );
43 private $tokenFunctions;
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
51 // Don't call the hooks twice
52 if ( isset( $this->tokenFunctions
) ) {
53 return $this->tokenFunctions
;
56 // If we're in a mode that breaks the same-origin policy, no tokens can
58 if ( $this->lacksSameOriginSecurity() ) {
62 $this->tokenFunctions
= [
63 'rollback' => [ self
::class, 'getRollbackToken' ]
65 Hooks
::run( 'APIQueryRevisionsTokens', [ &$this->tokenFunctions
] );
67 return $this->tokenFunctions
;
71 * @deprecated since 1.24
74 * @param Revision $rev
77 public static function getRollbackToken( $pageid, $title, $rev ) {
79 if ( !MediaWikiServices
::getInstance()->getPermissionManager()
80 ->userHasRight( $wgUser, 'rollback' ) ) {
84 return $wgUser->getEditToken( 'rollback' );
87 protected function run( ApiPageSet
$resultPageSet = null ) {
88 $params = $this->extractRequestParams( false );
89 $revisionStore = MediaWikiServices
::getInstance()->getRevisionStore();
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 );
100 $pageSet = $this->getPageSet();
101 $pageCount = $pageSet->getGoodTitleCount();
102 $revCount = $pageSet->getRevisionCount();
104 // Optimization -- nothing to do
105 if ( $revCount === 0 && $pageCount === 0 ) {
109 if ( $revCount > 0 && count( $pageSet->getLiveRevisionIDs() ) === 0 ) {
110 // We're in revisions mode but all given revisions are deleted
114 if ( $revCount > 0 && $enumRevMode ) {
116 [ 'apierror-revisions-norevids', $this->getModulePrefix() ], 'invalidparammix'
120 if ( $pageCount > 1 && $enumRevMode ) {
122 [ 'apierror-revisions-singlepage', $this->getModulePrefix() ], 'invalidparammix'
126 // In non-enum mode, rvlimit can't be directly used. Use the maximum
128 if ( !$enumRevMode ) {
129 $this->setParsedLimit
= false;
130 $params['limit'] = 'max';
133 $db = $this->getDB();
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';
146 if ( $resultPageSet === null ) {
147 $this->parseParameters( $params );
148 $this->token
= $params['token'];
150 if ( $this->token
!== null ||
$pageCount > 0 ) {
153 if ( $this->fld_user
) {
156 $revQuery = $revisionStore->getQueryInfo( $opts );
158 if ( $idField !== 'rev_id' ) {
159 $aliasFields = [ 'rev_id' => $idField, 'rev_timestamp' => $tsField, 'rev_page' => $pageField ];
160 $revQuery['fields'] = array_merge(
162 array_diff( $revQuery['fields'], array_keys( $aliasFields ) )
166 $this->addTables( $revQuery['tables'] );
167 $this->addFields( $revQuery['fields'] );
168 $this->addJoinConds( $revQuery['joins'] );
170 $this->limit
= $this->getParameter( 'limit' ) ?
: 10;
171 // Always join 'page' so orphaned revisions are filtered out
172 $this->addTables( [ 'revision', 'page' ] );
174 [ 'page' => [ 'JOIN', [ 'page_id = rev_page' ] ] ]
177 'rev_id' => $idField, 'rev_timestamp' => $tsField, 'rev_page' => $pageField
181 if ( $this->fld_tags
) {
182 $this->addFields( [ 'ts_tags' => ChangeTags
::makeTagSummarySubquery( 'revision' ) ] );
185 if ( $params['tag'] !== null ) {
186 $this->addTables( 'change_tag' );
188 [ 'change_tag' => [ 'JOIN', [ 'rev_id=ct_rev_id' ] ] ]
190 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
192 $this->addWhereFld( 'ct_tag_id', $changeTagDefStore->getId( $params['tag'] ) );
193 } catch ( NameTableAccessException
$exception ) {
195 $this->addWhere( '1=0' );
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();
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() ) ],
213 if ( !$status->isGood() ) {
214 $this->dieStatus( $status );
218 if ( $enumRevMode ) {
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
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' );
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)"
243 // Convert startid/endid to timestamps (T163532)
245 if ( $params['startid'] !== null ) {
246 $revids[] = (int)$params['startid'];
248 if ( $params['endid'] !== null ) {
249 $revids[] = (int)$params['endid'];
252 $db = $this->getDB();
253 $sql = $db->unionQueries( [
256 [ 'id' => 'rev_id', 'ts' => 'rev_timestamp' ],
257 [ 'rev_id' => $revids ],
262 [ 'id' => 'ar_rev_id', 'ts' => 'ar_timestamp' ],
263 [ 'ar_rev_id' => $revids ],
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
;
272 if ( (int)$row->id
=== (int)$params['endid'] ) {
273 $params['end'] = $row->ts
;
276 if ( $params['startid'] !== null && $params['start'] === null ) {
277 $p = $this->encodeParamName( 'startid' );
278 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
280 if ( $params['endid'] !== null && $params['end'] === null ) {
281 $p = $this->encodeParamName( 'endid' );
282 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
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'] );
292 $this->addWhere( "$tsField $op= $ts" );
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'] );
302 $this->addWhere( "$tsField $op= $ts" );
306 $this->addTimestampWhereRange( $tsField, $params['dir'],
307 $params['start'], $params['end'] );
310 $sort = ( $params['dir'] === 'newer' ?
'' : 'DESC' );
311 $this->addOption( 'ORDER BY', [ "rev_timestamp $sort", "rev_id $sort" ] );
313 // There is only one ID, use it
314 $ids = array_keys( $pageSet->getGoodTitles() );
315 $this->addWhereFld( $pageField, reset( $ids ) );
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'] . ')' );
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' )
337 $bitmask = RevisionRecord
::DELETED_USER | RevisionRecord
::DELETED_RESTRICTED
;
342 $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
345 } elseif ( $revCount > 0 ) {
346 // Always targets the PRIMARY index
348 $revs = $pageSet->getLiveRevisionIDs();
350 // Get all revision IDs
351 $this->addWhereFld( 'rev_id', array_keys( $revs ) );
353 if ( $params['continue'] !== null ) {
354 $this->addWhere( 'rev_id >= ' . (int)$params['continue'] );
356 $this->addOption( 'ORDER BY', 'rev_id' );
357 } elseif ( $pageCount > 0 ) {
358 // Always targets the rev_page_id index
360 $titles = $pageSet->getGoodTitles();
362 // When working in multi-page non-enumeration mode,
363 // limit to the latest revision only
364 $this->addWhere( 'page_latest=rev_id' );
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 ) );
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];
377 "rev_page > $pageid OR " .
378 "(rev_page = $pageid AND " .
382 $this->addOption( 'ORDER BY', [
387 ApiBase
::dieDebug( __METHOD__
, 'param validation?' );
390 $this->addOption( 'LIMIT', $this->limit +
1 );
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' ] );
399 $res = $this->select( __METHOD__
, [], $hookData );
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
);
411 $this->setContinueEnumParameter( 'continue', (int)$row->rev_page
.
412 '|' . (int)$row->rev_id
);
417 if ( $resultPageSet !== null ) {
418 $generated[] = $row->rev_id
;
420 $revision = $revisionStore->newRevisionFromRow( $row );
421 $rev = $this->extractRevisionInfo( $revision, $row );
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 ] );
432 $rev[$t . 'token'] = $val;
437 $fit = $this->processRow( $row, $rev, $hookData ) &&
438 $this->addPageSubItem( $row->rev_page
, $rev, 'rev' );
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
);
446 $this->setContinueEnumParameter( 'continue', (int)$row->rev_page
.
447 '|' . (int)$row->rev_id
);
454 if ( $resultPageSet !== null ) {
455 $resultPageSet->populateFromRevisionIDs( $generated );
459 public function getCacheMode( $params ) {
460 if ( isset( $params['token'] ) ) {
463 return parent
::getCacheMode( $params );
466 public function getAllowedParams() {
467 $ret = parent
::getAllowedParams() +
[
469 ApiBase
::PARAM_TYPE
=> 'integer',
470 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
473 ApiBase
::PARAM_TYPE
=> 'integer',
474 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
477 ApiBase
::PARAM_TYPE
=> 'timestamp',
478 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
481 ApiBase
::PARAM_TYPE
=> 'timestamp',
482 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
485 ApiBase
::PARAM_DFLT
=> 'older',
486 ApiBase
::PARAM_TYPE
=> [
490 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-direction',
491 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
494 ApiBase
::PARAM_TYPE
=> 'user',
495 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
498 ApiBase
::PARAM_TYPE
=> 'user',
499 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
503 ApiBase
::PARAM_DEPRECATED
=> true,
504 ApiBase
::PARAM_TYPE
=> array_keys( $this->getTokenFunctions() ),
505 ApiBase
::PARAM_ISMULTI
=> true
508 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-continue',
512 $ret['limit'][ApiBase
::PARAM_HELP_MSG_INFO
] = [ [ 'singlepageonly' ] ];
517 protected function getExamplesMessages() {
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',
540 public function getHelpUrls() {
541 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Revisions';