Merge "Show a warning in edit preview when a template loop is detected"
[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 $this->addTables( [ 'revision', 'page' ] );
133 $this->addJoinConds(
134 [ 'page' => [ 'INNER JOIN', [ 'page_id = rev_page' ] ] ]
135 );
136
137 if ( $resultPageSet === null ) {
138 $this->parseParameters( $params );
139 $this->token = $params['token'];
140 $this->addFields( Revision::selectFields() );
141 if ( $this->token !== null || $pageCount > 0 ) {
142 $this->addFields( Revision::selectPageFields() );
143 }
144 } else {
145 $this->limit = $this->getParameter( 'limit' ) ?: 10;
146 $this->addFields( [ 'rev_id', 'rev_timestamp', 'rev_page' ] );
147 }
148
149 if ( $this->fld_tags ) {
150 $this->addTables( 'tag_summary' );
151 $this->addJoinConds(
152 [ 'tag_summary' => [ 'LEFT JOIN', [ 'rev_id=ts_rev_id' ] ] ]
153 );
154 $this->addFields( 'ts_tags' );
155 }
156
157 if ( $params['tag'] !== null ) {
158 $this->addTables( 'change_tag' );
159 $this->addJoinConds(
160 [ 'change_tag' => [ 'INNER JOIN', [ 'rev_id=ct_rev_id' ] ] ]
161 );
162 $this->addWhereFld( 'ct_tag', $params['tag'] );
163 }
164
165 if ( $this->fetchContent ) {
166 // For each page we will request, the user must have read rights for that page
167 $user = $this->getUser();
168 $status = Status::newGood();
169 /** @var Title $title */
170 foreach ( $pageSet->getGoodTitles() as $title ) {
171 if ( !$title->userCan( 'read', $user ) ) {
172 $status->fatal( ApiMessage::create(
173 [ 'apierror-cannotviewtitle', wfEscapeWikiText( $title->getPrefixedText() ) ],
174 'accessdenied'
175 ) );
176 }
177 }
178 if ( !$status->isGood() ) {
179 $this->dieStatus( $status );
180 }
181
182 $this->addTables( 'text' );
183 $this->addJoinConds(
184 [ 'text' => [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ] ]
185 );
186 $this->addFields( 'old_id' );
187 $this->addFields( Revision::selectTextFields() );
188 }
189
190 // add user name, if needed
191 if ( $this->fld_user ) {
192 $this->addTables( 'user' );
193 $this->addJoinConds( [ 'user' => Revision::userJoinCond() ] );
194 $this->addFields( Revision::selectUserFields() );
195 }
196
197 if ( $enumRevMode ) {
198 // Indexes targeted:
199 // page_timestamp if we don't have rvuser
200 // page_user_timestamp if we have a logged-in rvuser
201 // page_timestamp or usertext_timestamp if we have an IP rvuser
202
203 // This is mostly to prevent parameter errors (and optimize SQL?)
204 $this->requireMaxOneParameter( $params, 'startid', 'start' );
205 $this->requireMaxOneParameter( $params, 'endid', 'end' );
206 $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
207
208 if ( $params['continue'] !== null ) {
209 $cont = explode( '|', $params['continue'] );
210 $this->dieContinueUsageIf( count( $cont ) != 2 );
211 $op = ( $params['dir'] === 'newer' ? '>' : '<' );
212 $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
213 $continueId = (int)$cont[1];
214 $this->dieContinueUsageIf( $continueId != $cont[1] );
215 $this->addWhere( "rev_timestamp $op $continueTimestamp OR " .
216 "(rev_timestamp = $continueTimestamp AND " .
217 "rev_id $op= $continueId)"
218 );
219 }
220
221 // Convert startid/endid to timestamps (T163532)
222 $revids = [];
223 if ( $params['startid'] !== null ) {
224 $revids[] = (int)$params['startid'];
225 }
226 if ( $params['endid'] !== null ) {
227 $revids[] = (int)$params['endid'];
228 }
229 if ( $revids ) {
230 $db = $this->getDB();
231 $sql = $db->unionQueries( [
232 $db->selectSQLText(
233 'revision',
234 [ 'id' => 'rev_id', 'ts' => 'rev_timestamp' ],
235 [ 'rev_id' => $revids ],
236 __METHOD__
237 ),
238 $db->selectSQLText(
239 'archive',
240 [ 'id' => 'ar_rev_id', 'ts' => 'ar_timestamp' ],
241 [ 'ar_rev_id' => $revids ],
242 __METHOD__
243 ),
244 ], false );
245 $res = $db->query( $sql, __METHOD__ );
246 foreach ( $res as $row ) {
247 if ( (int)$row->id === (int)$params['startid'] ) {
248 $params['start'] = $row->ts;
249 }
250 if ( (int)$row->id === (int)$params['endid'] ) {
251 $params['end'] = $row->ts;
252 }
253 }
254 if ( $params['startid'] !== null && $params['start'] === null ) {
255 $p = $this->encodeParamName( 'startid' );
256 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
257 }
258 if ( $params['endid'] !== null && $params['end'] === null ) {
259 $p = $this->encodeParamName( 'endid' );
260 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
261 }
262
263 if ( $params['start'] !== null ) {
264 $op = ( $params['dir'] === 'newer' ? '>' : '<' );
265 $ts = $db->addQuotes( $db->timestampOrNull( $params['start'] ) );
266 if ( $params['startid'] !== null ) {
267 $this->addWhere( "rev_timestamp $op $ts OR "
268 . "rev_timestamp = $ts AND rev_id $op= " . intval( $params['startid'] ) );
269 } else {
270 $this->addWhere( "rev_timestamp $op= $ts" );
271 }
272 }
273 if ( $params['end'] !== null ) {
274 $op = ( $params['dir'] === 'newer' ? '<' : '>' ); // Yes, opposite of the above
275 $ts = $db->addQuotes( $db->timestampOrNull( $params['end'] ) );
276 if ( $params['endid'] !== null ) {
277 $this->addWhere( "rev_timestamp $op $ts OR "
278 . "rev_timestamp = $ts AND rev_id $op= " . intval( $params['endid'] ) );
279 } else {
280 $this->addWhere( "rev_timestamp $op= $ts" );
281 }
282 }
283 } else {
284 $this->addTimestampWhereRange( 'rev_timestamp', $params['dir'],
285 $params['start'], $params['end'] );
286 }
287
288 $sort = ( $params['dir'] === 'newer' ? '' : 'DESC' );
289 $this->addOption( 'ORDER BY', [ "rev_timestamp $sort", "rev_id $sort" ] );
290
291 // There is only one ID, use it
292 $ids = array_keys( $pageSet->getGoodTitles() );
293 $this->addWhereFld( 'rev_page', reset( $ids ) );
294
295 if ( $params['user'] !== null ) {
296 $user = User::newFromName( $params['user'] );
297 if ( $user && $user->getId() > 0 ) {
298 $this->addWhereFld( 'rev_user', $user->getId() );
299 } else {
300 $this->addWhereFld( 'rev_user_text', $params['user'] );
301 }
302 } elseif ( $params['excludeuser'] !== null ) {
303 $user = User::newFromName( $params['excludeuser'] );
304 if ( $user && $user->getId() > 0 ) {
305 $this->addWhere( 'rev_user != ' . $user->getId() );
306 } else {
307 $this->addWhere( 'rev_user_text != ' .
308 $db->addQuotes( $params['excludeuser'] ) );
309 }
310 }
311 if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
312 // Paranoia: avoid brute force searches (T19342)
313 if ( !$this->getUser()->isAllowed( 'deletedhistory' ) ) {
314 $bitmask = Revision::DELETED_USER;
315 } elseif ( !$this->getUser()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
316 $bitmask = Revision::DELETED_USER | Revision::DELETED_RESTRICTED;
317 } else {
318 $bitmask = 0;
319 }
320 if ( $bitmask ) {
321 $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
322 }
323 }
324 } elseif ( $revCount > 0 ) {
325 // Always targets the PRIMARY index
326
327 $revs = $pageSet->getLiveRevisionIDs();
328
329 // Get all revision IDs
330 $this->addWhereFld( 'rev_id', array_keys( $revs ) );
331
332 if ( $params['continue'] !== null ) {
333 $this->addWhere( 'rev_id >= ' . intval( $params['continue'] ) );
334 }
335 $this->addOption( 'ORDER BY', 'rev_id' );
336 } elseif ( $pageCount > 0 ) {
337 // Always targets the rev_page_id index
338
339 $titles = $pageSet->getGoodTitles();
340
341 // When working in multi-page non-enumeration mode,
342 // limit to the latest revision only
343 $this->addWhere( 'page_latest=rev_id' );
344
345 // Get all page IDs
346 $this->addWhereFld( 'page_id', array_keys( $titles ) );
347 // Every time someone relies on equality propagation, god kills a kitten :)
348 $this->addWhereFld( 'rev_page', array_keys( $titles ) );
349
350 if ( $params['continue'] !== null ) {
351 $cont = explode( '|', $params['continue'] );
352 $this->dieContinueUsageIf( count( $cont ) != 2 );
353 $pageid = intval( $cont[0] );
354 $revid = intval( $cont[1] );
355 $this->addWhere(
356 "rev_page > $pageid OR " .
357 "(rev_page = $pageid AND " .
358 "rev_id >= $revid)"
359 );
360 }
361 $this->addOption( 'ORDER BY', [
362 'rev_page',
363 'rev_id'
364 ] );
365 } else {
366 ApiBase::dieDebug( __METHOD__, 'param validation?' );
367 }
368
369 $this->addOption( 'LIMIT', $this->limit + 1 );
370
371 $count = 0;
372 $generated = [];
373 $hookData = [];
374 $res = $this->select( __METHOD__, [], $hookData );
375
376 foreach ( $res as $row ) {
377 if ( ++$count > $this->limit ) {
378 // We've reached the one extra which shows that there are
379 // additional pages to be had. Stop here...
380 if ( $enumRevMode ) {
381 $this->setContinueEnumParameter( 'continue',
382 $row->rev_timestamp . '|' . intval( $row->rev_id ) );
383 } elseif ( $revCount > 0 ) {
384 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
385 } else {
386 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
387 '|' . intval( $row->rev_id ) );
388 }
389 break;
390 }
391
392 if ( $resultPageSet !== null ) {
393 $generated[] = $row->rev_id;
394 } else {
395 $revision = new Revision( $row );
396 $rev = $this->extractRevisionInfo( $revision, $row );
397
398 if ( $this->token !== null ) {
399 $title = $revision->getTitle();
400 $tokenFunctions = $this->getTokenFunctions();
401 foreach ( $this->token as $t ) {
402 $val = call_user_func( $tokenFunctions[$t], $title->getArticleID(), $title, $revision );
403 if ( $val === false ) {
404 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
405 } else {
406 $rev[$t . 'token'] = $val;
407 }
408 }
409 }
410
411 $fit = $this->processRow( $row, $rev, $hookData ) &&
412 $this->addPageSubItem( $row->rev_page, $rev, 'rev' );
413 if ( !$fit ) {
414 if ( $enumRevMode ) {
415 $this->setContinueEnumParameter( 'continue',
416 $row->rev_timestamp . '|' . intval( $row->rev_id ) );
417 } elseif ( $revCount > 0 ) {
418 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
419 } else {
420 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
421 '|' . intval( $row->rev_id ) );
422 }
423 break;
424 }
425 }
426 }
427
428 if ( $resultPageSet !== null ) {
429 $resultPageSet->populateFromRevisionIDs( $generated );
430 }
431 }
432
433 public function getCacheMode( $params ) {
434 if ( isset( $params['token'] ) ) {
435 return 'private';
436 }
437 return parent::getCacheMode( $params );
438 }
439
440 public function getAllowedParams() {
441 $ret = parent::getAllowedParams() + [
442 'startid' => [
443 ApiBase::PARAM_TYPE => 'integer',
444 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
445 ],
446 'endid' => [
447 ApiBase::PARAM_TYPE => 'integer',
448 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
449 ],
450 'start' => [
451 ApiBase::PARAM_TYPE => 'timestamp',
452 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
453 ],
454 'end' => [
455 ApiBase::PARAM_TYPE => 'timestamp',
456 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
457 ],
458 'dir' => [
459 ApiBase::PARAM_DFLT => 'older',
460 ApiBase::PARAM_TYPE => [
461 'newer',
462 'older'
463 ],
464 ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
465 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
466 ],
467 'user' => [
468 ApiBase::PARAM_TYPE => 'user',
469 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
470 ],
471 'excludeuser' => [
472 ApiBase::PARAM_TYPE => 'user',
473 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
474 ],
475 'tag' => null,
476 'token' => [
477 ApiBase::PARAM_DEPRECATED => true,
478 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
479 ApiBase::PARAM_ISMULTI => true
480 ],
481 'continue' => [
482 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
483 ],
484 ];
485
486 $ret['limit'][ApiBase::PARAM_HELP_MSG_INFO] = [ [ 'singlepageonly' ] ];
487
488 return $ret;
489 }
490
491 protected function getExamplesMessages() {
492 return [
493 'action=query&prop=revisions&titles=API|Main%20Page&' .
494 'rvprop=timestamp|user|comment|content'
495 => 'apihelp-query+revisions-example-content',
496 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
497 'rvprop=timestamp|user|comment'
498 => 'apihelp-query+revisions-example-last5',
499 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
500 'rvprop=timestamp|user|comment&rvdir=newer'
501 => 'apihelp-query+revisions-example-first5',
502 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
503 'rvprop=timestamp|user|comment&rvdir=newer&rvstart=2006-05-01T00:00:00Z'
504 => 'apihelp-query+revisions-example-first5-after',
505 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
506 'rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1'
507 => 'apihelp-query+revisions-example-first5-not-localhost',
508 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
509 'rvprop=timestamp|user|comment&rvuser=MediaWiki%20default'
510 => 'apihelp-query+revisions-example-first5-user',
511 ];
512 }
513
514 public function getHelpUrls() {
515 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Revisions';
516 }
517 }