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\Storage\RevisionRecord
;
27 * A query action to enumerate revisions of a given page, or show top revisions
28 * of multiple pages. Various pieces of information may be shown - flags,
29 * comments, and the actual wiki markup of the rev. In the enumeration mode,
30 * ranges of revisions may be requested and filtered.
34 class ApiQueryRevisions
extends ApiQueryRevisionsBase
{
36 private $token = null;
38 public function __construct( ApiQuery
$query, $moduleName ) {
39 parent
::__construct( $query, $moduleName, 'rv' );
42 private $tokenFunctions;
44 /** @deprecated since 1.24 */
45 protected function getTokenFunctions() {
46 // tokenname => function
47 // function prototype is func($pageid, $title, $rev)
48 // should return token or false
50 // Don't call the hooks twice
51 if ( isset( $this->tokenFunctions
) ) {
52 return $this->tokenFunctions
;
55 // If we're in a mode that breaks the same-origin policy, no tokens can
57 if ( $this->lacksSameOriginSecurity() ) {
61 $this->tokenFunctions
= [
62 'rollback' => [ self
::class, 'getRollbackToken' ]
64 Hooks
::run( 'APIQueryRevisionsTokens', [ &$this->tokenFunctions
] );
66 return $this->tokenFunctions
;
70 * @deprecated since 1.24
73 * @param Revision $rev
76 public static function getRollbackToken( $pageid, $title, $rev ) {
78 if ( !$wgUser->isAllowed( 'rollback' ) ) {
82 return $wgUser->getEditToken( 'rollback' );
85 protected function run( ApiPageSet
$resultPageSet = null ) {
86 $params = $this->extractRequestParams( false );
87 $revisionStore = MediaWikiServices
::getInstance()->getRevisionStore();
89 // If any of those parameters are used, work in 'enumeration' mode.
90 // Enum mode can only be used when exactly one page is provided.
91 // Enumerating revisions on multiple pages make it extremely
92 // difficult to manage continuations and require additional SQL indexes
93 $enumRevMode = ( $params['user'] !== null ||
$params['excludeuser'] !== null ||
94 $params['limit'] !== null ||
$params['startid'] !== null ||
95 $params['endid'] !== null ||
$params['dir'] === 'newer' ||
96 $params['start'] !== null ||
$params['end'] !== null );
98 $pageSet = $this->getPageSet();
99 $pageCount = $pageSet->getGoodTitleCount();
100 $revCount = $pageSet->getRevisionCount();
102 // Optimization -- nothing to do
103 if ( $revCount === 0 && $pageCount === 0 ) {
107 if ( $revCount > 0 && count( $pageSet->getLiveRevisionIDs() ) === 0 ) {
108 // We're in revisions mode but all given revisions are deleted
112 if ( $revCount > 0 && $enumRevMode ) {
114 [ 'apierror-revisions-nolist', $this->getModulePrefix() ], 'invalidparammix'
118 if ( $pageCount > 1 && $enumRevMode ) {
120 [ 'apierror-revisions-singlepage', $this->getModulePrefix() ], 'invalidparammix'
124 // In non-enum mode, rvlimit can't be directly used. Use the maximum
126 if ( !$enumRevMode ) {
127 $this->setParsedLimit
= false;
128 $params['limit'] = 'max';
131 $db = $this->getDB();
133 if ( $resultPageSet === null ) {
134 $this->parseParameters( $params );
135 $this->token
= $params['token'];
137 if ( $this->token
!== null ||
$pageCount > 0 ) {
140 if ( $this->fetchContent
) {
143 if ( $this->fld_user
) {
146 $revQuery = $revisionStore->getQueryInfo( $opts );
147 $this->addTables( $revQuery['tables'] );
148 $this->addFields( $revQuery['fields'] );
149 $this->addJoinConds( $revQuery['joins'] );
151 $this->limit
= $this->getParameter( 'limit' ) ?
: 10;
152 // Always join 'page' so orphaned revisions are filtered out
153 $this->addTables( [ 'revision', 'page' ] );
155 [ 'page' => [ 'INNER JOIN', [ 'page_id = rev_page' ] ] ]
157 $this->addFields( [ 'rev_id', 'rev_timestamp', 'rev_page' ] );
160 if ( $this->fld_tags
) {
161 $this->addTables( 'tag_summary' );
163 [ 'tag_summary' => [ 'LEFT JOIN', [ 'rev_id=ts_rev_id' ] ] ]
165 $this->addFields( 'ts_tags' );
168 if ( $params['tag'] !== null ) {
169 $this->addTables( 'change_tag' );
171 [ 'change_tag' => [ 'INNER JOIN', [ 'rev_id=ct_rev_id' ] ] ]
173 $this->addWhereFld( 'ct_tag', $params['tag'] );
176 if ( $resultPageSet === null && $this->fetchContent
) {
177 // For each page we will request, the user must have read rights for that page
178 $user = $this->getUser();
179 $status = Status
::newGood();
180 /** @var Title $title */
181 foreach ( $pageSet->getGoodTitles() as $title ) {
182 if ( !$title->userCan( 'read', $user ) ) {
183 $status->fatal( ApiMessage
::create(
184 [ 'apierror-cannotviewtitle', wfEscapeWikiText( $title->getPrefixedText() ) ],
189 if ( !$status->isGood() ) {
190 $this->dieStatus( $status );
194 if ( $enumRevMode ) {
196 // page_timestamp if we don't have rvuser
197 // page_user_timestamp if we have a logged-in rvuser
198 // page_timestamp or usertext_timestamp if we have an IP rvuser
200 // This is mostly to prevent parameter errors (and optimize SQL?)
201 $this->requireMaxOneParameter( $params, 'startid', 'start' );
202 $this->requireMaxOneParameter( $params, 'endid', 'end' );
203 $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
205 if ( $params['continue'] !== null ) {
206 $cont = explode( '|', $params['continue'] );
207 $this->dieContinueUsageIf( count( $cont ) != 2 );
208 $op = ( $params['dir'] === 'newer' ?
'>' : '<' );
209 $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
210 $continueId = (int)$cont[1];
211 $this->dieContinueUsageIf( $continueId != $cont[1] );
212 $this->addWhere( "rev_timestamp $op $continueTimestamp OR " .
213 "(rev_timestamp = $continueTimestamp AND " .
214 "rev_id $op= $continueId)"
218 // Convert startid/endid to timestamps (T163532)
220 if ( $params['startid'] !== null ) {
221 $revids[] = (int)$params['startid'];
223 if ( $params['endid'] !== null ) {
224 $revids[] = (int)$params['endid'];
227 $db = $this->getDB();
228 $sql = $db->unionQueries( [
231 [ 'id' => 'rev_id', 'ts' => 'rev_timestamp' ],
232 [ 'rev_id' => $revids ],
237 [ 'id' => 'ar_rev_id', 'ts' => 'ar_timestamp' ],
238 [ 'ar_rev_id' => $revids ],
242 $res = $db->query( $sql, __METHOD__
);
243 foreach ( $res as $row ) {
244 if ( (int)$row->id
=== (int)$params['startid'] ) {
245 $params['start'] = $row->ts
;
247 if ( (int)$row->id
=== (int)$params['endid'] ) {
248 $params['end'] = $row->ts
;
251 if ( $params['startid'] !== null && $params['start'] === null ) {
252 $p = $this->encodeParamName( 'startid' );
253 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
255 if ( $params['endid'] !== null && $params['end'] === null ) {
256 $p = $this->encodeParamName( 'endid' );
257 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
260 if ( $params['start'] !== null ) {
261 $op = ( $params['dir'] === 'newer' ?
'>' : '<' );
262 $ts = $db->addQuotes( $db->timestampOrNull( $params['start'] ) );
263 if ( $params['startid'] !== null ) {
264 $this->addWhere( "rev_timestamp $op $ts OR "
265 . "rev_timestamp = $ts AND rev_id $op= " . intval( $params['startid'] ) );
267 $this->addWhere( "rev_timestamp $op= $ts" );
270 if ( $params['end'] !== null ) {
271 $op = ( $params['dir'] === 'newer' ?
'<' : '>' ); // Yes, opposite of the above
272 $ts = $db->addQuotes( $db->timestampOrNull( $params['end'] ) );
273 if ( $params['endid'] !== null ) {
274 $this->addWhere( "rev_timestamp $op $ts OR "
275 . "rev_timestamp = $ts AND rev_id $op= " . intval( $params['endid'] ) );
277 $this->addWhere( "rev_timestamp $op= $ts" );
281 $this->addTimestampWhereRange( 'rev_timestamp', $params['dir'],
282 $params['start'], $params['end'] );
285 $sort = ( $params['dir'] === 'newer' ?
'' : 'DESC' );
286 $this->addOption( 'ORDER BY', [ "rev_timestamp $sort", "rev_id $sort" ] );
288 // There is only one ID, use it
289 $ids = array_keys( $pageSet->getGoodTitles() );
290 $this->addWhereFld( 'rev_page', reset( $ids ) );
292 if ( $params['user'] !== null ) {
293 $actorQuery = ActorMigration
::newMigration()
294 ->getWhere( $db, 'rev_user', User
::newFromName( $params['user'], false ) );
295 $this->addTables( $actorQuery['tables'] );
296 $this->addJoinConds( $actorQuery['joins'] );
297 $this->addWhere( $actorQuery['conds'] );
298 } elseif ( $params['excludeuser'] !== null ) {
299 $actorQuery = ActorMigration
::newMigration()
300 ->getWhere( $db, 'rev_user', User
::newFromName( $params['excludeuser'], false ) );
301 $this->addTables( $actorQuery['tables'] );
302 $this->addJoinConds( $actorQuery['joins'] );
303 $this->addWhere( 'NOT(' . $actorQuery['conds'] . ')' );
305 if ( $params['user'] !== null ||
$params['excludeuser'] !== null ) {
306 // Paranoia: avoid brute force searches (T19342)
307 if ( !$this->getUser()->isAllowed( 'deletedhistory' ) ) {
308 $bitmask = RevisionRecord
::DELETED_USER
;
309 } elseif ( !$this->getUser()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
310 $bitmask = RevisionRecord
::DELETED_USER | RevisionRecord
::DELETED_RESTRICTED
;
315 $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
318 } elseif ( $revCount > 0 ) {
319 // Always targets the PRIMARY index
321 $revs = $pageSet->getLiveRevisionIDs();
323 // Get all revision IDs
324 $this->addWhereFld( 'rev_id', array_keys( $revs ) );
326 if ( $params['continue'] !== null ) {
327 $this->addWhere( 'rev_id >= ' . intval( $params['continue'] ) );
329 $this->addOption( 'ORDER BY', 'rev_id' );
330 } elseif ( $pageCount > 0 ) {
331 // Always targets the rev_page_id index
333 $titles = $pageSet->getGoodTitles();
335 // When working in multi-page non-enumeration mode,
336 // limit to the latest revision only
337 $this->addWhere( 'page_latest=rev_id' );
340 $this->addWhereFld( 'page_id', array_keys( $titles ) );
341 // Every time someone relies on equality propagation, god kills a kitten :)
342 $this->addWhereFld( 'rev_page', array_keys( $titles ) );
344 if ( $params['continue'] !== null ) {
345 $cont = explode( '|', $params['continue'] );
346 $this->dieContinueUsageIf( count( $cont ) != 2 );
347 $pageid = intval( $cont[0] );
348 $revid = intval( $cont[1] );
350 "rev_page > $pageid OR " .
351 "(rev_page = $pageid AND " .
355 $this->addOption( 'ORDER BY', [
360 ApiBase
::dieDebug( __METHOD__
, 'param validation?' );
363 $this->addOption( 'LIMIT', $this->limit +
1 );
368 $res = $this->select( __METHOD__
, [], $hookData );
370 foreach ( $res as $row ) {
371 if ( ++
$count > $this->limit
) {
372 // We've reached the one extra which shows that there are
373 // additional pages to be had. Stop here...
374 if ( $enumRevMode ) {
375 $this->setContinueEnumParameter( 'continue',
376 $row->rev_timestamp
. '|' . intval( $row->rev_id
) );
377 } elseif ( $revCount > 0 ) {
378 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id
) );
380 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page
) .
381 '|' . intval( $row->rev_id
) );
386 if ( $resultPageSet !== null ) {
387 $generated[] = $row->rev_id
;
389 $revision = $revisionStore->newRevisionFromRow( $row );
390 $rev = $this->extractRevisionInfo( $revision, $row );
392 if ( $this->token
!== null ) {
393 $title = Title
::newFromLinkTarget( $revision->getPageAsLinkTarget() );
394 $revisionCompat = new Revision( $revision );
395 $tokenFunctions = $this->getTokenFunctions();
396 foreach ( $this->token
as $t ) {
397 $val = call_user_func( $tokenFunctions[$t], $title->getArticleID(), $title, $revisionCompat );
398 if ( $val === false ) {
399 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
401 $rev[$t . 'token'] = $val;
406 $fit = $this->processRow( $row, $rev, $hookData ) &&
407 $this->addPageSubItem( $row->rev_page
, $rev, 'rev' );
409 if ( $enumRevMode ) {
410 $this->setContinueEnumParameter( 'continue',
411 $row->rev_timestamp
. '|' . intval( $row->rev_id
) );
412 } elseif ( $revCount > 0 ) {
413 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id
) );
415 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page
) .
416 '|' . intval( $row->rev_id
) );
423 if ( $resultPageSet !== null ) {
424 $resultPageSet->populateFromRevisionIDs( $generated );
428 public function getCacheMode( $params ) {
429 if ( isset( $params['token'] ) ) {
432 return parent
::getCacheMode( $params );
435 public function getAllowedParams() {
436 $ret = parent
::getAllowedParams() +
[
438 ApiBase
::PARAM_TYPE
=> 'integer',
439 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
442 ApiBase
::PARAM_TYPE
=> 'integer',
443 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
446 ApiBase
::PARAM_TYPE
=> 'timestamp',
447 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
450 ApiBase
::PARAM_TYPE
=> 'timestamp',
451 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
454 ApiBase
::PARAM_DFLT
=> 'older',
455 ApiBase
::PARAM_TYPE
=> [
459 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-direction',
460 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
463 ApiBase
::PARAM_TYPE
=> 'user',
464 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
467 ApiBase
::PARAM_TYPE
=> 'user',
468 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'singlepageonly' ] ],
472 ApiBase
::PARAM_DEPRECATED
=> true,
473 ApiBase
::PARAM_TYPE
=> array_keys( $this->getTokenFunctions() ),
474 ApiBase
::PARAM_ISMULTI
=> true
477 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-continue',
481 $ret['limit'][ApiBase
::PARAM_HELP_MSG_INFO
] = [ [ 'singlepageonly' ] ];
486 protected function getExamplesMessages() {
488 'action=query&prop=revisions&titles=API|Main%20Page&' .
489 'rvprop=timestamp|user|comment|content'
490 => 'apihelp-query+revisions-example-content',
491 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
492 'rvprop=timestamp|user|comment'
493 => 'apihelp-query+revisions-example-last5',
494 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
495 'rvprop=timestamp|user|comment&rvdir=newer'
496 => 'apihelp-query+revisions-example-first5',
497 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
498 'rvprop=timestamp|user|comment&rvdir=newer&rvstart=2006-05-01T00:00:00Z'
499 => 'apihelp-query+revisions-example-first5-after',
500 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
501 'rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1'
502 => 'apihelp-query+revisions-example-first5-not-localhost',
503 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
504 'rvprop=timestamp|user|comment&rvuser=MediaWiki%20default'
505 => 'apihelp-query+revisions-example-first5-user',
509 public function getHelpUrls() {
510 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Revisions';