MediaWiki REL1_37
ApiQueryRevisions.php
Go to the documentation of this file.
1<?php
31
41
44
47
50
62 public function __construct(
63 ApiQuery $query,
64 $moduleName,
72 ) {
73 parent::__construct(
74 $query,
75 $moduleName,
76 'rv',
82 );
83 $this->revisionStore = $revisionStore;
84 $this->changeTagDefStore = $changeTagDefStore;
85 $this->actorMigration = $actorMigration;
86 }
87
88 protected function run( ApiPageSet $resultPageSet = null ) {
90
91 $params = $this->extractRequestParams( false );
92
93 // If any of those parameters are used, work in 'enumeration' mode.
94 // Enum mode can only be used when exactly one page is provided.
95 // Enumerating revisions on multiple pages make it extremely
96 // difficult to manage continuations and require additional SQL indexes
97 $enumRevMode = ( $params['user'] !== null || $params['excludeuser'] !== null ||
98 $params['limit'] !== null || $params['startid'] !== null ||
99 $params['endid'] !== null || $params['dir'] === 'newer' ||
100 $params['start'] !== null || $params['end'] !== null );
101
102 $pageSet = $this->getPageSet();
103 $pageCount = $pageSet->getGoodTitleCount();
104 $revCount = $pageSet->getRevisionCount();
105
106 // Optimization -- nothing to do
107 if ( $revCount === 0 && $pageCount === 0 ) {
108 // Nothing to do
109 return;
110 }
111 if ( $revCount > 0 && count( $pageSet->getLiveRevisionIDs() ) === 0 ) {
112 // We're in revisions mode but all given revisions are deleted
113 return;
114 }
115
116 if ( $revCount > 0 && $enumRevMode ) {
117 $this->dieWithError(
118 [ 'apierror-revisions-norevids', $this->getModulePrefix() ], 'invalidparammix'
119 );
120 }
121
122 if ( $pageCount > 1 && $enumRevMode ) {
123 $this->dieWithError(
124 [ 'apierror-revisions-singlepage', $this->getModulePrefix() ], 'invalidparammix'
125 );
126 }
127
128 // In non-enum mode, rvlimit can't be directly used. Use the maximum
129 // allowed value.
130 if ( !$enumRevMode ) {
131 $this->setParsedLimit = false;
132 $params['limit'] = 'max';
133 }
134
135 $db = $this->getDB();
136
137 $idField = 'rev_id';
138 $tsField = 'rev_timestamp';
139 $pageField = 'rev_page';
140
141 $ignoreIndex = [
142 // T224017: `rev_timestamp` is never the correct index to use for this module, but
143 // MariaDB sometimes insists on trying to use it anyway. Tell it not to.
144 // Last checked with MariaDB 10.4.13
145 'revision' => 'rev_timestamp',
146 ];
147 $useIndex = [];
148
149 if ( $params['user'] !== null &&
151 ) {
152 // We're going to want to use the page_actor_timestamp index (on revision_actor_temp)
153 // so use that table's denormalized fields.
154 $idField = 'revactor_rev';
155 $tsField = 'revactor_timestamp';
156 $pageField = 'revactor_page';
157 }
158
159 if ( $resultPageSet === null ) {
160 $this->parseParameters( $params );
161 $opts = [ 'page' ];
162 if ( $this->fld_user ) {
163 $opts[] = 'user';
164 }
165 $revQuery = $this->revisionStore->getQueryInfo( $opts );
166
167 if ( $idField !== 'rev_id' ) {
168 $aliasFields = [ 'rev_id' => $idField, 'rev_timestamp' => $tsField, 'rev_page' => $pageField ];
169 $revQuery['fields'] = array_merge(
170 $aliasFields,
171 array_diff( $revQuery['fields'], array_keys( $aliasFields ) )
172 );
173 }
174
175 $this->addTables( $revQuery['tables'] );
176 $this->addFields( $revQuery['fields'] );
177 $this->addJoinConds( $revQuery['joins'] );
178 } else {
179 $this->limit = $this->getParameter( 'limit' ) ?: 10;
180 // Always join 'page' so orphaned revisions are filtered out
181 $this->addTables( [ 'revision', 'page' ] );
182 $this->addJoinConds(
183 [ 'page' => [ 'JOIN', [ 'page_id = rev_page' ] ] ]
184 );
185 $this->addFields( [
186 'rev_id' => $idField, 'rev_timestamp' => $tsField, 'rev_page' => $pageField
187 ] );
188 }
189
190 if ( $this->fld_tags ) {
191 $this->addFields( [ 'ts_tags' => ChangeTags::makeTagSummarySubquery( 'revision' ) ] );
192 }
193
194 if ( $params['tag'] !== null ) {
195 $this->addTables( 'change_tag' );
196 $this->addJoinConds(
197 [ 'change_tag' => [ 'JOIN', [ 'rev_id=ct_rev_id' ] ] ]
198 );
199 try {
200 $this->addWhereFld( 'ct_tag_id', $this->changeTagDefStore->getId( $params['tag'] ) );
201 } catch ( NameTableAccessException $exception ) {
202 // Return nothing.
203 $this->addWhere( '1=0' );
204 }
205 }
206
207 if ( $resultPageSet === null && $this->fetchContent ) {
208 // For each page we will request, the user must have read rights for that page
209 $status = Status::newGood();
210
212 foreach ( $pageSet->getGoodTitles() as $title ) {
213 if ( !$this->getAuthority()->authorizeRead( 'read', $title ) ) {
214 $status->fatal( ApiMessage::create(
215 [ 'apierror-cannotviewtitle', wfEscapeWikiText( $title->getPrefixedText() ) ],
216 'accessdenied'
217 ) );
218 }
219 }
220 if ( !$status->isGood() ) {
221 $this->dieStatus( $status );
222 }
223 }
224
225 if ( $enumRevMode ) {
226 // Indexes targeted:
227 // page_timestamp if we don't have rvuser
228 // page_actor_timestamp (on revision_actor_temp) if we have rvuser in READ_NEW mode
229 // page_user_timestamp if we have a logged-in rvuser
230 // page_timestamp or usertext_timestamp if we have an IP rvuser
231
232 // This is mostly to prevent parameter errors (and optimize SQL?)
233 $this->requireMaxOneParameter( $params, 'startid', 'start' );
234 $this->requireMaxOneParameter( $params, 'endid', 'end' );
235 $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
236
237 if ( $params['continue'] !== null ) {
238 $cont = explode( '|', $params['continue'] );
239 $this->dieContinueUsageIf( count( $cont ) != 2 );
240 $op = ( $params['dir'] === 'newer' ? '>' : '<' );
241 $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
242 $continueId = (int)$cont[1];
243 $this->dieContinueUsageIf( $continueId != $cont[1] );
244 $this->addWhere( "$tsField $op $continueTimestamp OR " .
245 "($tsField = $continueTimestamp AND " .
246 "$idField $op= $continueId)"
247 );
248 }
249
250 // Convert startid/endid to timestamps (T163532)
251 $revids = [];
252 if ( $params['startid'] !== null ) {
253 $revids[] = (int)$params['startid'];
254 }
255 if ( $params['endid'] !== null ) {
256 $revids[] = (int)$params['endid'];
257 }
258 if ( $revids ) {
259 $db = $this->getDB();
260 $sql = $db->unionQueries( [
261 $db->selectSQLText(
262 'revision',
263 [ 'id' => 'rev_id', 'ts' => 'rev_timestamp' ],
264 [ 'rev_id' => $revids ],
265 __METHOD__
266 ),
267 $db->selectSQLText(
268 'archive',
269 [ 'id' => 'ar_rev_id', 'ts' => 'ar_timestamp' ],
270 [ 'ar_rev_id' => $revids ],
271 __METHOD__
272 ),
273 ], $db::UNION_DISTINCT );
274 $res = $db->query( $sql, __METHOD__ );
275 foreach ( $res as $row ) {
276 if ( (int)$row->id === (int)$params['startid'] ) {
277 $params['start'] = $row->ts;
278 }
279 if ( (int)$row->id === (int)$params['endid'] ) {
280 $params['end'] = $row->ts;
281 }
282 }
283 if ( $params['startid'] !== null && $params['start'] === null ) {
284 $p = $this->encodeParamName( 'startid' );
285 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
286 }
287 if ( $params['endid'] !== null && $params['end'] === null ) {
288 $p = $this->encodeParamName( 'endid' );
289 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
290 }
291
292 if ( $params['start'] !== null ) {
293 $op = ( $params['dir'] === 'newer' ? '>' : '<' );
294 $ts = $db->addQuotes( $db->timestampOrNull( $params['start'] ) );
295 if ( $params['startid'] !== null ) {
296 $this->addWhere( "$tsField $op $ts OR "
297 . "$tsField = $ts AND $idField $op= " . (int)$params['startid'] );
298 } else {
299 $this->addWhere( "$tsField $op= $ts" );
300 }
301 }
302 if ( $params['end'] !== null ) {
303 $op = ( $params['dir'] === 'newer' ? '<' : '>' ); // Yes, opposite of the above
304 $ts = $db->addQuotes( $db->timestampOrNull( $params['end'] ) );
305 if ( $params['endid'] !== null ) {
306 $this->addWhere( "$tsField $op $ts OR "
307 . "$tsField = $ts AND $idField $op= " . (int)$params['endid'] );
308 } else {
309 $this->addWhere( "$tsField $op= $ts" );
310 }
311 }
312 } else {
313 $this->addTimestampWhereRange( $tsField, $params['dir'],
314 $params['start'], $params['end'] );
315 }
316
317 $sort = ( $params['dir'] === 'newer' ? '' : 'DESC' );
318 $this->addOption( 'ORDER BY', [ "rev_timestamp $sort", "rev_id $sort" ] );
319
320 // There is only one ID, use it
321 $ids = array_keys( $pageSet->getGoodTitles() );
322 $this->addWhereFld( $pageField, reset( $ids ) );
323
324 if ( $params['user'] !== null ) {
325 $actorQuery = $this->actorMigration->getWhere( $db, 'rev_user', $params['user'] );
326 $this->addTables( $actorQuery['tables'] );
327 $this->addJoinConds( $actorQuery['joins'] );
328 $this->addWhere( $actorQuery['conds'] );
329 } elseif ( $params['excludeuser'] !== null ) {
330 $actorQuery = $this->actorMigration->getWhere( $db, 'rev_user', $params['excludeuser'] );
331 $this->addTables( $actorQuery['tables'] );
332 $this->addJoinConds( $actorQuery['joins'] );
333 $this->addWhere( 'NOT(' . $actorQuery['conds'] . ')' );
334 } else {
335 // T270033 Index renaming
336 $revIndex = $this->getDB()->indexExists( 'revision', 'page_timestamp', __METHOD__ )
337 ? 'page_timestamp'
338 : 'rev_page_timestamp';
339 // T258480: MariaDB ends up using rev_page_actor_timestamp in some cases here.
340 // Last checked with MariaDB 10.4.13
341 // Unless we are filtering by user (see above), we always want to use the
342 // "history" index on the revision table, namely page_timestamp.
343 $useIndex['revision'] = $revIndex;
344 }
345
346 if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
347 // Paranoia: avoid brute force searches (T19342)
348 if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
349 $bitmask = RevisionRecord::DELETED_USER;
350 } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' )
351 ) {
352 $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
353 } else {
354 $bitmask = 0;
355 }
356 if ( $bitmask ) {
357 $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
358 }
359 }
360 } elseif ( $revCount > 0 ) {
361 // Always targets the PRIMARY index
362
363 $revs = $pageSet->getLiveRevisionIDs();
364
365 // Get all revision IDs
366 $this->addWhereFld( 'rev_id', array_keys( $revs ) );
367
368 if ( $params['continue'] !== null ) {
369 $this->addWhere( 'rev_id >= ' . (int)$params['continue'] );
370 }
371 $this->addOption( 'ORDER BY', 'rev_id' );
372 } elseif ( $pageCount > 0 ) {
373 // Always targets the rev_page_id index
374
375 $titles = $pageSet->getGoodTitles();
376
377 // When working in multi-page non-enumeration mode,
378 // limit to the latest revision only
379 $this->addWhere( 'page_latest=rev_id' );
380
381 // Get all page IDs
382 $this->addWhereFld( 'page_id', array_keys( $titles ) );
383 // Every time someone relies on equality propagation, god kills a kitten :)
384 $this->addWhereFld( 'rev_page', array_keys( $titles ) );
385
386 if ( $params['continue'] !== null ) {
387 $cont = explode( '|', $params['continue'] );
388 $this->dieContinueUsageIf( count( $cont ) != 2 );
389 $pageid = (int)$cont[0];
390 $revid = (int)$cont[1];
391 $this->addWhere(
392 "rev_page > $pageid OR " .
393 "(rev_page = $pageid AND " .
394 "rev_id >= $revid)"
395 );
396 }
397 $this->addOption( 'ORDER BY', [
398 'rev_page',
399 'rev_id'
400 ] );
401 } else {
402 ApiBase::dieDebug( __METHOD__, 'param validation?' );
403 }
404
405 $this->addOption( 'LIMIT', $this->limit + 1 );
406
407 $this->addOption( 'IGNORE INDEX', $ignoreIndex );
408
409 if ( $useIndex ) {
410 $this->addOption( 'USE INDEX', $useIndex );
411 }
412
413 $count = 0;
414 $generated = [];
415 $hookData = [];
416 $res = $this->select( __METHOD__, [], $hookData );
417
418 foreach ( $res as $row ) {
419 if ( ++$count > $this->limit ) {
420 // We've reached the one extra which shows that there are
421 // additional pages to be had. Stop here...
422 if ( $enumRevMode ) {
423 $this->setContinueEnumParameter( 'continue',
424 $row->rev_timestamp . '|' . (int)$row->rev_id );
425 } elseif ( $revCount > 0 ) {
426 $this->setContinueEnumParameter( 'continue', (int)$row->rev_id );
427 } else {
428 $this->setContinueEnumParameter( 'continue', (int)$row->rev_page .
429 '|' . (int)$row->rev_id );
430 }
431 break;
432 }
433
434 if ( $resultPageSet !== null ) {
435 $generated[] = $row->rev_id;
436 } else {
437 $revision = $this->revisionStore->newRevisionFromRow( $row, 0, Title::newFromRow( $row ) );
438 $rev = $this->extractRevisionInfo( $revision, $row );
439 $fit = $this->processRow( $row, $rev, $hookData ) &&
440 $this->addPageSubItem( $row->rev_page, $rev, 'rev' );
441 if ( !$fit ) {
442 if ( $enumRevMode ) {
443 $this->setContinueEnumParameter( 'continue',
444 $row->rev_timestamp . '|' . (int)$row->rev_id );
445 } elseif ( $revCount > 0 ) {
446 $this->setContinueEnumParameter( 'continue', (int)$row->rev_id );
447 } else {
448 $this->setContinueEnumParameter( 'continue', (int)$row->rev_page .
449 '|' . (int)$row->rev_id );
450 }
451 break;
452 }
453 }
454 }
455
456 if ( $resultPageSet !== null ) {
457 $resultPageSet->populateFromRevisionIDs( $generated );
458 }
459 }
460
461 public function getAllowedParams() {
462 $ret = parent::getAllowedParams() + [
463 'startid' => [
464 ApiBase::PARAM_TYPE => 'integer',
465 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
466 ],
467 'endid' => [
468 ApiBase::PARAM_TYPE => 'integer',
469 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
470 ],
471 'start' => [
472 ApiBase::PARAM_TYPE => 'timestamp',
473 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
474 ],
475 'end' => [
476 ApiBase::PARAM_TYPE => 'timestamp',
477 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
478 ],
479 'dir' => [
480 ApiBase::PARAM_DFLT => 'older',
482 'newer',
483 'older'
484 ],
485 ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
486 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
487 ],
488 'user' => [
489 ApiBase::PARAM_TYPE => 'user',
490 UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
491 UserDef::PARAM_RETURN_OBJECT => true,
492 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
493 ],
494 'excludeuser' => [
495 ApiBase::PARAM_TYPE => 'user',
496 UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
497 UserDef::PARAM_RETURN_OBJECT => true,
498 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
499 ],
500 'tag' => null,
501 'continue' => [
502 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
503 ],
504 ];
505
506 $ret['limit'][ApiBase::PARAM_HELP_MSG_INFO] = [ [ 'singlepageonly' ] ];
507
508 return $ret;
509 }
510
511 protected function getExamplesMessages() {
512 return [
513 'action=query&prop=revisions&titles=API|Main%20Page&' .
514 'rvslots=*&rvprop=timestamp|user|comment|content'
515 => 'apihelp-query+revisions-example-content',
516 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
517 'rvprop=timestamp|user|comment'
518 => 'apihelp-query+revisions-example-last5',
519 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
520 'rvprop=timestamp|user|comment&rvdir=newer'
521 => 'apihelp-query+revisions-example-first5',
522 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
523 'rvprop=timestamp|user|comment&rvdir=newer&rvstart=2006-05-01T00:00:00Z'
524 => 'apihelp-query+revisions-example-first5-after',
525 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
526 'rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1'
527 => 'apihelp-query+revisions-example-first5-not-localhost',
528 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
529 'rvprop=timestamp|user|comment&rvuser=MediaWiki%20default'
530 => 'apihelp-query+revisions-example-first5-user',
531 ];
532 }
533
534 public function getHelpUrls() {
535 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Revisions';
536 }
537}
getAuthority()
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage, for migration from the temporary table revision_actor_temp to the...
const SCHEMA_COMPAT_READ_TEMP
Definition Defines.php:265
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
This is not intended to be a long-term part of MediaWiki; it will be deprecated and removed once acto...
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1436
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition ApiBase.php:505
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition ApiBase.php:884
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
Definition ApiBase.php:1620
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:1633
const PARAM_TYPE
Definition ApiBase.php:81
const PARAM_HELP_MSG_INFO
(array) Specify additional information tags for the parameter.
Definition ApiBase.php:179
const PARAM_DFLT
Definition ApiBase.php:73
requireMaxOneParameter( $params,... $required)
Die if more than one of a certain set of parameters is set and not false.
Definition ApiBase.php:936
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:764
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:162
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1495
This class contains a list of pages that the client has requested.
processRow( $row, array &$data, array &$hookData)
Call the ApiQueryBaseProcessRow hook.
addFields( $value)
Add a set of fields to select to the internal array.
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addTimestampWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
getDB()
Get the Query database connection (read-only)
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addWhere( $value)
Add a set of WHERE clauses to the internal array.
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
getPageSet()
Get the PageSet object to work on.
encodeParamName( $paramName)
Overrides ApiBase to prepend 'g' to every generator parameter.
A base class for functions common to producing a list of revisions.
parseParameters( $params)
Parse the parameters into the various instance fields.
IContentHandlerFactory $contentHandlerFactory
ContentTransformer $contentTransformer
SlotRoleRegistry $slotRoleRegistry
extractRevisionInfo(RevisionRecord $revision, $row)
Extract information from the RevisionRecord.
A query action to enumerate revisions of a given page, or show top revisions of multiple pages.
ActorMigration $actorMigration
getHelpUrls()
Return links to more detailed help pages about the module.
run(ApiPageSet $resultPageSet=null)
RevisionStore $revisionStore
__construct(ApiQuery $query, $moduleName, RevisionStore $revisionStore, IContentHandlerFactory $contentHandlerFactory, ParserFactory $parserFactory, SlotRoleRegistry $slotRoleRegistry, NameTableStore $changeTagDefStore, ActorMigration $actorMigration, ContentTransformer $contentTransformer)
NameTableStore $changeTagDefStore
getExamplesMessages()
Returns usage examples for this module.
This is the main query class.
Definition ApiQuery.php:37
static makeTagSummarySubquery( $tables)
Make the tag summary subquery based on the given tables and return it.
Type definition for user types.
Definition UserDef.php:25
Page revision base class.
Service for looking up page revisions.
A registry service for SlotRoleHandlers, used to define which slot roles are available on which page.
Exception representing a failure to look up a row from a name table.
Represents a title within MediaWiki.
Definition Title.php:48