Merge "Add attributes parameter to ShowSearchHitTitle"
[lhc/web/wiklou.git] / includes / api / ApiQueryRevisions.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 7, 2006
6 *
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
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' => [ 'ApiQueryRevisions', '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 ( !$wgUser->isAllowed( 'rollback' ) ) {
80 return false;
81 }
82
83 return $wgUser->getEditToken( 'rollback' );
84 }
85
86 protected function run( ApiPageSet $resultPageSet = null ) {
87 $params = $this->extractRequestParams( false );
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 = Revision::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 $user = User::newFromName( $params['user'] );
294 if ( $user && $user->getId() > 0 ) {
295 $this->addWhereFld( 'rev_user', $user->getId() );
296 } else {
297 $this->addWhereFld( 'rev_user_text', $params['user'] );
298 }
299 } elseif ( $params['excludeuser'] !== null ) {
300 $user = User::newFromName( $params['excludeuser'] );
301 if ( $user && $user->getId() > 0 ) {
302 $this->addWhere( 'rev_user != ' . $user->getId() );
303 } else {
304 $this->addWhere( 'rev_user_text != ' .
305 $db->addQuotes( $params['excludeuser'] ) );
306 }
307 }
308 if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
309 // Paranoia: avoid brute force searches (T19342)
310 if ( !$this->getUser()->isAllowed( 'deletedhistory' ) ) {
311 $bitmask = Revision::DELETED_USER;
312 } elseif ( !$this->getUser()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
313 $bitmask = Revision::DELETED_USER | Revision::DELETED_RESTRICTED;
314 } else {
315 $bitmask = 0;
316 }
317 if ( $bitmask ) {
318 $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
319 }
320 }
321 } elseif ( $revCount > 0 ) {
322 // Always targets the PRIMARY index
323
324 $revs = $pageSet->getLiveRevisionIDs();
325
326 // Get all revision IDs
327 $this->addWhereFld( 'rev_id', array_keys( $revs ) );
328
329 if ( $params['continue'] !== null ) {
330 $this->addWhere( 'rev_id >= ' . intval( $params['continue'] ) );
331 }
332 $this->addOption( 'ORDER BY', 'rev_id' );
333 } elseif ( $pageCount > 0 ) {
334 // Always targets the rev_page_id index
335
336 $titles = $pageSet->getGoodTitles();
337
338 // When working in multi-page non-enumeration mode,
339 // limit to the latest revision only
340 $this->addWhere( 'page_latest=rev_id' );
341
342 // Get all page IDs
343 $this->addWhereFld( 'page_id', array_keys( $titles ) );
344 // Every time someone relies on equality propagation, god kills a kitten :)
345 $this->addWhereFld( 'rev_page', array_keys( $titles ) );
346
347 if ( $params['continue'] !== null ) {
348 $cont = explode( '|', $params['continue'] );
349 $this->dieContinueUsageIf( count( $cont ) != 2 );
350 $pageid = intval( $cont[0] );
351 $revid = intval( $cont[1] );
352 $this->addWhere(
353 "rev_page > $pageid OR " .
354 "(rev_page = $pageid AND " .
355 "rev_id >= $revid)"
356 );
357 }
358 $this->addOption( 'ORDER BY', [
359 'rev_page',
360 'rev_id'
361 ] );
362 } else {
363 ApiBase::dieDebug( __METHOD__, 'param validation?' );
364 }
365
366 $this->addOption( 'LIMIT', $this->limit + 1 );
367
368 $count = 0;
369 $generated = [];
370 $hookData = [];
371 $res = $this->select( __METHOD__, [], $hookData );
372
373 foreach ( $res as $row ) {
374 if ( ++$count > $this->limit ) {
375 // We've reached the one extra which shows that there are
376 // additional pages to be had. Stop here...
377 if ( $enumRevMode ) {
378 $this->setContinueEnumParameter( 'continue',
379 $row->rev_timestamp . '|' . intval( $row->rev_id ) );
380 } elseif ( $revCount > 0 ) {
381 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
382 } else {
383 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
384 '|' . intval( $row->rev_id ) );
385 }
386 break;
387 }
388
389 if ( $resultPageSet !== null ) {
390 $generated[] = $row->rev_id;
391 } else {
392 $revision = new Revision( $row );
393 $rev = $this->extractRevisionInfo( $revision, $row );
394
395 if ( $this->token !== null ) {
396 $title = $revision->getTitle();
397 $tokenFunctions = $this->getTokenFunctions();
398 foreach ( $this->token as $t ) {
399 $val = call_user_func( $tokenFunctions[$t], $title->getArticleID(), $title, $revision );
400 if ( $val === false ) {
401 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
402 } else {
403 $rev[$t . 'token'] = $val;
404 }
405 }
406 }
407
408 $fit = $this->processRow( $row, $rev, $hookData ) &&
409 $this->addPageSubItem( $row->rev_page, $rev, 'rev' );
410 if ( !$fit ) {
411 if ( $enumRevMode ) {
412 $this->setContinueEnumParameter( 'continue',
413 $row->rev_timestamp . '|' . intval( $row->rev_id ) );
414 } elseif ( $revCount > 0 ) {
415 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
416 } else {
417 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
418 '|' . intval( $row->rev_id ) );
419 }
420 break;
421 }
422 }
423 }
424
425 if ( $resultPageSet !== null ) {
426 $resultPageSet->populateFromRevisionIDs( $generated );
427 }
428 }
429
430 public function getCacheMode( $params ) {
431 if ( isset( $params['token'] ) ) {
432 return 'private';
433 }
434 return parent::getCacheMode( $params );
435 }
436
437 public function getAllowedParams() {
438 $ret = parent::getAllowedParams() + [
439 'startid' => [
440 ApiBase::PARAM_TYPE => 'integer',
441 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
442 ],
443 'endid' => [
444 ApiBase::PARAM_TYPE => 'integer',
445 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
446 ],
447 'start' => [
448 ApiBase::PARAM_TYPE => 'timestamp',
449 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
450 ],
451 'end' => [
452 ApiBase::PARAM_TYPE => 'timestamp',
453 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
454 ],
455 'dir' => [
456 ApiBase::PARAM_DFLT => 'older',
457 ApiBase::PARAM_TYPE => [
458 'newer',
459 'older'
460 ],
461 ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
462 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
463 ],
464 'user' => [
465 ApiBase::PARAM_TYPE => 'user',
466 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
467 ],
468 'excludeuser' => [
469 ApiBase::PARAM_TYPE => 'user',
470 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
471 ],
472 'tag' => null,
473 'token' => [
474 ApiBase::PARAM_DEPRECATED => true,
475 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
476 ApiBase::PARAM_ISMULTI => true
477 ],
478 'continue' => [
479 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
480 ],
481 ];
482
483 $ret['limit'][ApiBase::PARAM_HELP_MSG_INFO] = [ [ 'singlepageonly' ] ];
484
485 return $ret;
486 }
487
488 protected function getExamplesMessages() {
489 return [
490 'action=query&prop=revisions&titles=API|Main%20Page&' .
491 'rvprop=timestamp|user|comment|content'
492 => 'apihelp-query+revisions-example-content',
493 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
494 'rvprop=timestamp|user|comment'
495 => 'apihelp-query+revisions-example-last5',
496 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
497 'rvprop=timestamp|user|comment&rvdir=newer'
498 => 'apihelp-query+revisions-example-first5',
499 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
500 'rvprop=timestamp|user|comment&rvdir=newer&rvstart=2006-05-01T00:00:00Z'
501 => 'apihelp-query+revisions-example-first5-after',
502 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
503 'rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1'
504 => 'apihelp-query+revisions-example-first5-not-localhost',
505 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
506 'rvprop=timestamp|user|comment&rvuser=MediaWiki%20default'
507 => 'apihelp-query+revisions-example-first5-user',
508 ];
509 }
510
511 public function getHelpUrls() {
512 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Revisions';
513 }
514 }