8c26024812d0799d042dd313816c8c3d4237253e
[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\Storage\RevisionRecord;
25
26 /**
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.
31 *
32 * @ingroup API
33 */
34 class ApiQueryRevisions extends ApiQueryRevisionsBase {
35
36 private $token = null;
37
38 public function __construct( ApiQuery $query, $moduleName ) {
39 parent::__construct( $query, $moduleName, 'rv' );
40 }
41
42 private $tokenFunctions;
43
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
49
50 // Don't call the hooks twice
51 if ( isset( $this->tokenFunctions ) ) {
52 return $this->tokenFunctions;
53 }
54
55 // If we're in a mode that breaks the same-origin policy, no tokens can
56 // be obtained
57 if ( $this->lacksSameOriginSecurity() ) {
58 return [];
59 }
60
61 $this->tokenFunctions = [
62 'rollback' => [ self::class, 'getRollbackToken' ]
63 ];
64 Hooks::run( 'APIQueryRevisionsTokens', [ &$this->tokenFunctions ] );
65
66 return $this->tokenFunctions;
67 }
68
69 /**
70 * @deprecated since 1.24
71 * @param int $pageid
72 * @param Title $title
73 * @param Revision $rev
74 * @return bool|string
75 */
76 public static function getRollbackToken( $pageid, $title, $rev ) {
77 global $wgUser;
78 if ( !$wgUser->isAllowed( 'rollback' ) ) {
79 return false;
80 }
81
82 return $wgUser->getEditToken( 'rollback' );
83 }
84
85 protected function run( ApiPageSet $resultPageSet = null ) {
86 $params = $this->extractRequestParams( false );
87 $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
88
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 );
97
98 $pageSet = $this->getPageSet();
99 $pageCount = $pageSet->getGoodTitleCount();
100 $revCount = $pageSet->getRevisionCount();
101
102 // Optimization -- nothing to do
103 if ( $revCount === 0 && $pageCount === 0 ) {
104 // Nothing to do
105 return;
106 }
107 if ( $revCount > 0 && count( $pageSet->getLiveRevisionIDs() ) === 0 ) {
108 // We're in revisions mode but all given revisions are deleted
109 return;
110 }
111
112 if ( $revCount > 0 && $enumRevMode ) {
113 $this->dieWithError(
114 [ 'apierror-revisions-nolist', $this->getModulePrefix() ], 'invalidparammix'
115 );
116 }
117
118 if ( $pageCount > 1 && $enumRevMode ) {
119 $this->dieWithError(
120 [ 'apierror-revisions-singlepage', $this->getModulePrefix() ], 'invalidparammix'
121 );
122 }
123
124 // In non-enum mode, rvlimit can't be directly used. Use the maximum
125 // allowed value.
126 if ( !$enumRevMode ) {
127 $this->setParsedLimit = false;
128 $params['limit'] = 'max';
129 }
130
131 $db = $this->getDB();
132
133 if ( $resultPageSet === null ) {
134 $this->parseParameters( $params );
135 $this->token = $params['token'];
136 $opts = [];
137 if ( $this->token !== null || $pageCount > 0 ) {
138 $opts[] = 'page';
139 }
140 if ( $this->fetchContent ) {
141 $opts[] = 'text';
142 }
143 if ( $this->fld_user ) {
144 $opts[] = 'user';
145 }
146 $revQuery = $revisionStore->getQueryInfo( $opts );
147 $this->addTables( $revQuery['tables'] );
148 $this->addFields( $revQuery['fields'] );
149 $this->addJoinConds( $revQuery['joins'] );
150 } else {
151 $this->limit = $this->getParameter( 'limit' ) ?: 10;
152 // Always join 'page' so orphaned revisions are filtered out
153 $this->addTables( [ 'revision', 'page' ] );
154 $this->addJoinConds(
155 [ 'page' => [ 'INNER JOIN', [ 'page_id = rev_page' ] ] ]
156 );
157 $this->addFields( [ 'rev_id', 'rev_timestamp', 'rev_page' ] );
158 }
159
160 if ( $this->fld_tags ) {
161 $this->addTables( 'tag_summary' );
162 $this->addJoinConds(
163 [ 'tag_summary' => [ 'LEFT JOIN', [ 'rev_id=ts_rev_id' ] ] ]
164 );
165 $this->addFields( 'ts_tags' );
166 }
167
168 if ( $params['tag'] !== null ) {
169 $this->addTables( 'change_tag' );
170 $this->addJoinConds(
171 [ 'change_tag' => [ 'INNER JOIN', [ 'rev_id=ct_rev_id' ] ] ]
172 );
173 $this->addWhereFld( 'ct_tag', $params['tag'] );
174 }
175
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() ) ],
185 'accessdenied'
186 ) );
187 }
188 }
189 if ( !$status->isGood() ) {
190 $this->dieStatus( $status );
191 }
192 }
193
194 if ( $enumRevMode ) {
195 // Indexes targeted:
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
199
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' );
204
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)"
215 );
216 }
217
218 // Convert startid/endid to timestamps (T163532)
219 $revids = [];
220 if ( $params['startid'] !== null ) {
221 $revids[] = (int)$params['startid'];
222 }
223 if ( $params['endid'] !== null ) {
224 $revids[] = (int)$params['endid'];
225 }
226 if ( $revids ) {
227 $db = $this->getDB();
228 $sql = $db->unionQueries( [
229 $db->selectSQLText(
230 'revision',
231 [ 'id' => 'rev_id', 'ts' => 'rev_timestamp' ],
232 [ 'rev_id' => $revids ],
233 __METHOD__
234 ),
235 $db->selectSQLText(
236 'archive',
237 [ 'id' => 'ar_rev_id', 'ts' => 'ar_timestamp' ],
238 [ 'ar_rev_id' => $revids ],
239 __METHOD__
240 ),
241 ], false );
242 $res = $db->query( $sql, __METHOD__ );
243 foreach ( $res as $row ) {
244 if ( (int)$row->id === (int)$params['startid'] ) {
245 $params['start'] = $row->ts;
246 }
247 if ( (int)$row->id === (int)$params['endid'] ) {
248 $params['end'] = $row->ts;
249 }
250 }
251 if ( $params['startid'] !== null && $params['start'] === null ) {
252 $p = $this->encodeParamName( 'startid' );
253 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
254 }
255 if ( $params['endid'] !== null && $params['end'] === null ) {
256 $p = $this->encodeParamName( 'endid' );
257 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
258 }
259
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'] ) );
266 } else {
267 $this->addWhere( "rev_timestamp $op= $ts" );
268 }
269 }
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'] ) );
276 } else {
277 $this->addWhere( "rev_timestamp $op= $ts" );
278 }
279 }
280 } else {
281 $this->addTimestampWhereRange( 'rev_timestamp', $params['dir'],
282 $params['start'], $params['end'] );
283 }
284
285 $sort = ( $params['dir'] === 'newer' ? '' : 'DESC' );
286 $this->addOption( 'ORDER BY', [ "rev_timestamp $sort", "rev_id $sort" ] );
287
288 // There is only one ID, use it
289 $ids = array_keys( $pageSet->getGoodTitles() );
290 $this->addWhereFld( 'rev_page', reset( $ids ) );
291
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'] . ')' );
304 }
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;
311 } else {
312 $bitmask = 0;
313 }
314 if ( $bitmask ) {
315 $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
316 }
317 }
318 } elseif ( $revCount > 0 ) {
319 // Always targets the PRIMARY index
320
321 $revs = $pageSet->getLiveRevisionIDs();
322
323 // Get all revision IDs
324 $this->addWhereFld( 'rev_id', array_keys( $revs ) );
325
326 if ( $params['continue'] !== null ) {
327 $this->addWhere( 'rev_id >= ' . intval( $params['continue'] ) );
328 }
329 $this->addOption( 'ORDER BY', 'rev_id' );
330 } elseif ( $pageCount > 0 ) {
331 // Always targets the rev_page_id index
332
333 $titles = $pageSet->getGoodTitles();
334
335 // When working in multi-page non-enumeration mode,
336 // limit to the latest revision only
337 $this->addWhere( 'page_latest=rev_id' );
338
339 // Get all page IDs
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 ) );
343
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] );
349 $this->addWhere(
350 "rev_page > $pageid OR " .
351 "(rev_page = $pageid AND " .
352 "rev_id >= $revid)"
353 );
354 }
355 $this->addOption( 'ORDER BY', [
356 'rev_page',
357 'rev_id'
358 ] );
359 } else {
360 ApiBase::dieDebug( __METHOD__, 'param validation?' );
361 }
362
363 $this->addOption( 'LIMIT', $this->limit + 1 );
364
365 $count = 0;
366 $generated = [];
367 $hookData = [];
368 $res = $this->select( __METHOD__, [], $hookData );
369
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 ) );
379 } else {
380 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
381 '|' . intval( $row->rev_id ) );
382 }
383 break;
384 }
385
386 if ( $resultPageSet !== null ) {
387 $generated[] = $row->rev_id;
388 } else {
389 $revision = $revisionStore->newRevisionFromRow( $row );
390 $rev = $this->extractRevisionInfo( $revision, $row );
391
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 ] );
400 } else {
401 $rev[$t . 'token'] = $val;
402 }
403 }
404 }
405
406 $fit = $this->processRow( $row, $rev, $hookData ) &&
407 $this->addPageSubItem( $row->rev_page, $rev, 'rev' );
408 if ( !$fit ) {
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 ) );
414 } else {
415 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
416 '|' . intval( $row->rev_id ) );
417 }
418 break;
419 }
420 }
421 }
422
423 if ( $resultPageSet !== null ) {
424 $resultPageSet->populateFromRevisionIDs( $generated );
425 }
426 }
427
428 public function getCacheMode( $params ) {
429 if ( isset( $params['token'] ) ) {
430 return 'private';
431 }
432 return parent::getCacheMode( $params );
433 }
434
435 public function getAllowedParams() {
436 $ret = parent::getAllowedParams() + [
437 'startid' => [
438 ApiBase::PARAM_TYPE => 'integer',
439 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
440 ],
441 'endid' => [
442 ApiBase::PARAM_TYPE => 'integer',
443 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
444 ],
445 'start' => [
446 ApiBase::PARAM_TYPE => 'timestamp',
447 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
448 ],
449 'end' => [
450 ApiBase::PARAM_TYPE => 'timestamp',
451 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
452 ],
453 'dir' => [
454 ApiBase::PARAM_DFLT => 'older',
455 ApiBase::PARAM_TYPE => [
456 'newer',
457 'older'
458 ],
459 ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
460 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
461 ],
462 'user' => [
463 ApiBase::PARAM_TYPE => 'user',
464 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
465 ],
466 'excludeuser' => [
467 ApiBase::PARAM_TYPE => 'user',
468 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
469 ],
470 'tag' => null,
471 'token' => [
472 ApiBase::PARAM_DEPRECATED => true,
473 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
474 ApiBase::PARAM_ISMULTI => true
475 ],
476 'continue' => [
477 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
478 ],
479 ];
480
481 $ret['limit'][ApiBase::PARAM_HELP_MSG_INFO] = [ [ 'singlepageonly' ] ];
482
483 return $ret;
484 }
485
486 protected function getExamplesMessages() {
487 return [
488 'action=query&prop=revisions&titles=API|Main%20Page&' .
489 'rvslots=*&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',
506 ];
507 }
508
509 public function getHelpUrls() {
510 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Revisions';
511 }
512 }