Merge "Fix a couple of issues with cleanupInvalidDbKeys.php maint script"
[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 if ( $params['startid'] !== null || $params['endid'] !== null ) {
223 $ids = [
224 (int)$params['startid'] => true,
225 (int)$params['endid'] => true,
226 ];
227 unset( $ids[0] ); // null
228 $ids = array_keys( $ids );
229
230 $db = $this->getDB();
231 $sql = $db->unionQueries( [
232 $db->selectSQLText(
233 'revision',
234 [ 'id' => 'rev_id', 'ts' => 'rev_timestamp' ],
235 [ 'rev_id' => $ids ],
236 __METHOD__
237 ),
238 $db->selectSQLText(
239 'archive',
240 [ 'id' => 'ar_rev_id', 'ts' => 'ar_timestamp' ],
241 [ 'ar_rev_id' => $ids ],
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
264 $this->addTimestampWhereRange( 'rev_timestamp', $params['dir'],
265 $params['start'], $params['end'] );
266 // Dummy to add rev_id to ORDER BY
267 $this->addWhereRange( 'rev_id', $params['dir'], null, null );
268
269 // There is only one ID, use it
270 $ids = array_keys( $pageSet->getGoodTitles() );
271 $this->addWhereFld( 'rev_page', reset( $ids ) );
272
273 if ( $params['user'] !== null ) {
274 $user = User::newFromName( $params['user'] );
275 if ( $user && $user->getId() > 0 ) {
276 $this->addWhereFld( 'rev_user', $user->getId() );
277 } else {
278 $this->addWhereFld( 'rev_user_text', $params['user'] );
279 }
280 } elseif ( $params['excludeuser'] !== null ) {
281 $user = User::newFromName( $params['excludeuser'] );
282 if ( $user && $user->getId() > 0 ) {
283 $this->addWhere( 'rev_user != ' . $user->getId() );
284 } else {
285 $this->addWhere( 'rev_user_text != ' .
286 $db->addQuotes( $params['excludeuser'] ) );
287 }
288 }
289 if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
290 // Paranoia: avoid brute force searches (T19342)
291 if ( !$this->getUser()->isAllowed( 'deletedhistory' ) ) {
292 $bitmask = Revision::DELETED_USER;
293 } elseif ( !$this->getUser()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
294 $bitmask = Revision::DELETED_USER | Revision::DELETED_RESTRICTED;
295 } else {
296 $bitmask = 0;
297 }
298 if ( $bitmask ) {
299 $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
300 }
301 }
302 } elseif ( $revCount > 0 ) {
303 // Always targets the PRIMARY index
304
305 $revs = $pageSet->getLiveRevisionIDs();
306
307 // Get all revision IDs
308 $this->addWhereFld( 'rev_id', array_keys( $revs ) );
309
310 if ( $params['continue'] !== null ) {
311 $this->addWhere( 'rev_id >= ' . intval( $params['continue'] ) );
312 }
313 $this->addOption( 'ORDER BY', 'rev_id' );
314 } elseif ( $pageCount > 0 ) {
315 // Always targets the rev_page_id index
316
317 $titles = $pageSet->getGoodTitles();
318
319 // When working in multi-page non-enumeration mode,
320 // limit to the latest revision only
321 $this->addWhere( 'page_latest=rev_id' );
322
323 // Get all page IDs
324 $this->addWhereFld( 'page_id', array_keys( $titles ) );
325 // Every time someone relies on equality propagation, god kills a kitten :)
326 $this->addWhereFld( 'rev_page', array_keys( $titles ) );
327
328 if ( $params['continue'] !== null ) {
329 $cont = explode( '|', $params['continue'] );
330 $this->dieContinueUsageIf( count( $cont ) != 2 );
331 $pageid = intval( $cont[0] );
332 $revid = intval( $cont[1] );
333 $this->addWhere(
334 "rev_page > $pageid OR " .
335 "(rev_page = $pageid AND " .
336 "rev_id >= $revid)"
337 );
338 }
339 $this->addOption( 'ORDER BY', [
340 'rev_page',
341 'rev_id'
342 ] );
343 } else {
344 ApiBase::dieDebug( __METHOD__, 'param validation?' );
345 }
346
347 $this->addOption( 'LIMIT', $this->limit + 1 );
348
349 $count = 0;
350 $generated = [];
351 $hookData = [];
352 $res = $this->select( __METHOD__, [], $hookData );
353
354 foreach ( $res as $row ) {
355 if ( ++$count > $this->limit ) {
356 // We've reached the one extra which shows that there are
357 // additional pages to be had. Stop here...
358 if ( $enumRevMode ) {
359 $this->setContinueEnumParameter( 'continue',
360 $row->rev_timestamp . '|' . intval( $row->rev_id ) );
361 } elseif ( $revCount > 0 ) {
362 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
363 } else {
364 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
365 '|' . intval( $row->rev_id ) );
366 }
367 break;
368 }
369
370 if ( $resultPageSet !== null ) {
371 $generated[] = $row->rev_id;
372 } else {
373 $revision = new Revision( $row );
374 $rev = $this->extractRevisionInfo( $revision, $row );
375
376 if ( $this->token !== null ) {
377 $title = $revision->getTitle();
378 $tokenFunctions = $this->getTokenFunctions();
379 foreach ( $this->token as $t ) {
380 $val = call_user_func( $tokenFunctions[$t], $title->getArticleID(), $title, $revision );
381 if ( $val === false ) {
382 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
383 } else {
384 $rev[$t . 'token'] = $val;
385 }
386 }
387 }
388
389 $fit = $this->processRow( $row, $rev, $hookData ) &&
390 $this->addPageSubItem( $row->rev_page, $rev, 'rev' );
391 if ( !$fit ) {
392 if ( $enumRevMode ) {
393 $this->setContinueEnumParameter( 'continue',
394 $row->rev_timestamp . '|' . intval( $row->rev_id ) );
395 } elseif ( $revCount > 0 ) {
396 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
397 } else {
398 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
399 '|' . intval( $row->rev_id ) );
400 }
401 break;
402 }
403 }
404 }
405
406 if ( $resultPageSet !== null ) {
407 $resultPageSet->populateFromRevisionIDs( $generated );
408 }
409 }
410
411 public function getCacheMode( $params ) {
412 if ( isset( $params['token'] ) ) {
413 return 'private';
414 }
415 return parent::getCacheMode( $params );
416 }
417
418 public function getAllowedParams() {
419 $ret = parent::getAllowedParams() + [
420 'startid' => [
421 ApiBase::PARAM_TYPE => 'integer',
422 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
423 ],
424 'endid' => [
425 ApiBase::PARAM_TYPE => 'integer',
426 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
427 ],
428 'start' => [
429 ApiBase::PARAM_TYPE => 'timestamp',
430 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
431 ],
432 'end' => [
433 ApiBase::PARAM_TYPE => 'timestamp',
434 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
435 ],
436 'dir' => [
437 ApiBase::PARAM_DFLT => 'older',
438 ApiBase::PARAM_TYPE => [
439 'newer',
440 'older'
441 ],
442 ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
443 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
444 ],
445 'user' => [
446 ApiBase::PARAM_TYPE => 'user',
447 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
448 ],
449 'excludeuser' => [
450 ApiBase::PARAM_TYPE => 'user',
451 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
452 ],
453 'tag' => null,
454 'token' => [
455 ApiBase::PARAM_DEPRECATED => true,
456 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
457 ApiBase::PARAM_ISMULTI => true
458 ],
459 'continue' => [
460 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
461 ],
462 ];
463
464 $ret['limit'][ApiBase::PARAM_HELP_MSG_INFO] = [ [ 'singlepageonly' ] ];
465
466 return $ret;
467 }
468
469 protected function getExamplesMessages() {
470 return [
471 'action=query&prop=revisions&titles=API|Main%20Page&' .
472 'rvprop=timestamp|user|comment|content'
473 => 'apihelp-query+revisions-example-content',
474 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
475 'rvprop=timestamp|user|comment'
476 => 'apihelp-query+revisions-example-last5',
477 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
478 'rvprop=timestamp|user|comment&rvdir=newer'
479 => 'apihelp-query+revisions-example-first5',
480 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
481 'rvprop=timestamp|user|comment&rvdir=newer&rvstart=2006-05-01T00:00:00Z'
482 => 'apihelp-query+revisions-example-first5-after',
483 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
484 'rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1'
485 => 'apihelp-query+revisions-example-first5-not-localhost',
486 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
487 'rvprop=timestamp|user|comment&rvuser=MediaWiki%20default'
488 => 'apihelp-query+revisions-example-first5-user',
489 ];
490 }
491
492 public function getHelpUrls() {
493 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Revisions';
494 }
495 }