Merge "Rewrite pref cleanup script"
[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 /**
24 * A query action to enumerate revisions of a given page, or show top revisions
25 * of multiple pages. Various pieces of information may be shown - flags,
26 * comments, and the actual wiki markup of the rev. In the enumeration mode,
27 * ranges of revisions may be requested and filtered.
28 *
29 * @ingroup API
30 */
31 class ApiQueryRevisions extends ApiQueryRevisionsBase {
32
33 private $token = null;
34
35 public function __construct( ApiQuery $query, $moduleName ) {
36 parent::__construct( $query, $moduleName, 'rv' );
37 }
38
39 private $tokenFunctions;
40
41 /** @deprecated since 1.24 */
42 protected function getTokenFunctions() {
43 // tokenname => function
44 // function prototype is func($pageid, $title, $rev)
45 // should return token or false
46
47 // Don't call the hooks twice
48 if ( isset( $this->tokenFunctions ) ) {
49 return $this->tokenFunctions;
50 }
51
52 // If we're in a mode that breaks the same-origin policy, no tokens can
53 // be obtained
54 if ( $this->lacksSameOriginSecurity() ) {
55 return [];
56 }
57
58 $this->tokenFunctions = [
59 'rollback' => [ self::class, 'getRollbackToken' ]
60 ];
61 Hooks::run( 'APIQueryRevisionsTokens', [ &$this->tokenFunctions ] );
62
63 return $this->tokenFunctions;
64 }
65
66 /**
67 * @deprecated since 1.24
68 * @param int $pageid
69 * @param Title $title
70 * @param Revision $rev
71 * @return bool|string
72 */
73 public static function getRollbackToken( $pageid, $title, $rev ) {
74 global $wgUser;
75 if ( !$wgUser->isAllowed( 'rollback' ) ) {
76 return false;
77 }
78
79 return $wgUser->getEditToken( 'rollback' );
80 }
81
82 protected function run( ApiPageSet $resultPageSet = null ) {
83 $params = $this->extractRequestParams( false );
84
85 // If any of those parameters are used, work in 'enumeration' mode.
86 // Enum mode can only be used when exactly one page is provided.
87 // Enumerating revisions on multiple pages make it extremely
88 // difficult to manage continuations and require additional SQL indexes
89 $enumRevMode = ( $params['user'] !== null || $params['excludeuser'] !== null ||
90 $params['limit'] !== null || $params['startid'] !== null ||
91 $params['endid'] !== null || $params['dir'] === 'newer' ||
92 $params['start'] !== null || $params['end'] !== null );
93
94 $pageSet = $this->getPageSet();
95 $pageCount = $pageSet->getGoodTitleCount();
96 $revCount = $pageSet->getRevisionCount();
97
98 // Optimization -- nothing to do
99 if ( $revCount === 0 && $pageCount === 0 ) {
100 // Nothing to do
101 return;
102 }
103 if ( $revCount > 0 && count( $pageSet->getLiveRevisionIDs() ) === 0 ) {
104 // We're in revisions mode but all given revisions are deleted
105 return;
106 }
107
108 if ( $revCount > 0 && $enumRevMode ) {
109 $this->dieWithError(
110 [ 'apierror-revisions-nolist', $this->getModulePrefix() ], 'invalidparammix'
111 );
112 }
113
114 if ( $pageCount > 1 && $enumRevMode ) {
115 $this->dieWithError(
116 [ 'apierror-revisions-singlepage', $this->getModulePrefix() ], 'invalidparammix'
117 );
118 }
119
120 // In non-enum mode, rvlimit can't be directly used. Use the maximum
121 // allowed value.
122 if ( !$enumRevMode ) {
123 $this->setParsedLimit = false;
124 $params['limit'] = 'max';
125 }
126
127 $db = $this->getDB();
128
129 if ( $resultPageSet === null ) {
130 $this->parseParameters( $params );
131 $this->token = $params['token'];
132 $opts = [];
133 if ( $this->token !== null || $pageCount > 0 ) {
134 $opts[] = 'page';
135 }
136 if ( $this->fetchContent ) {
137 $opts[] = 'text';
138 }
139 if ( $this->fld_user ) {
140 $opts[] = 'user';
141 }
142 $revQuery = Revision::getQueryInfo( $opts );
143 $this->addTables( $revQuery['tables'] );
144 $this->addFields( $revQuery['fields'] );
145 $this->addJoinConds( $revQuery['joins'] );
146 } else {
147 $this->limit = $this->getParameter( 'limit' ) ?: 10;
148 // Always join 'page' so orphaned revisions are filtered out
149 $this->addTables( [ 'revision', 'page' ] );
150 $this->addJoinConds(
151 [ 'page' => [ 'INNER JOIN', [ 'page_id = rev_page' ] ] ]
152 );
153 $this->addFields( [ 'rev_id', 'rev_timestamp', 'rev_page' ] );
154 }
155
156 if ( $this->fld_tags ) {
157 $this->addTables( 'tag_summary' );
158 $this->addJoinConds(
159 [ 'tag_summary' => [ 'LEFT JOIN', [ 'rev_id=ts_rev_id' ] ] ]
160 );
161 $this->addFields( 'ts_tags' );
162 }
163
164 if ( $params['tag'] !== null ) {
165 $this->addTables( 'change_tag' );
166 $this->addJoinConds(
167 [ 'change_tag' => [ 'INNER JOIN', [ 'rev_id=ct_rev_id' ] ] ]
168 );
169 $this->addWhereFld( 'ct_tag', $params['tag'] );
170 }
171
172 if ( $resultPageSet === null && $this->fetchContent ) {
173 // For each page we will request, the user must have read rights for that page
174 $user = $this->getUser();
175 $status = Status::newGood();
176 /** @var Title $title */
177 foreach ( $pageSet->getGoodTitles() as $title ) {
178 if ( !$title->userCan( 'read', $user ) ) {
179 $status->fatal( ApiMessage::create(
180 [ 'apierror-cannotviewtitle', wfEscapeWikiText( $title->getPrefixedText() ) ],
181 'accessdenied'
182 ) );
183 }
184 }
185 if ( !$status->isGood() ) {
186 $this->dieStatus( $status );
187 }
188 }
189
190 if ( $enumRevMode ) {
191 // Indexes targeted:
192 // page_timestamp if we don't have rvuser
193 // page_user_timestamp if we have a logged-in rvuser
194 // page_timestamp or usertext_timestamp if we have an IP rvuser
195
196 // This is mostly to prevent parameter errors (and optimize SQL?)
197 $this->requireMaxOneParameter( $params, 'startid', 'start' );
198 $this->requireMaxOneParameter( $params, 'endid', 'end' );
199 $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
200
201 if ( $params['continue'] !== null ) {
202 $cont = explode( '|', $params['continue'] );
203 $this->dieContinueUsageIf( count( $cont ) != 2 );
204 $op = ( $params['dir'] === 'newer' ? '>' : '<' );
205 $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
206 $continueId = (int)$cont[1];
207 $this->dieContinueUsageIf( $continueId != $cont[1] );
208 $this->addWhere( "rev_timestamp $op $continueTimestamp OR " .
209 "(rev_timestamp = $continueTimestamp AND " .
210 "rev_id $op= $continueId)"
211 );
212 }
213
214 // Convert startid/endid to timestamps (T163532)
215 $revids = [];
216 if ( $params['startid'] !== null ) {
217 $revids[] = (int)$params['startid'];
218 }
219 if ( $params['endid'] !== null ) {
220 $revids[] = (int)$params['endid'];
221 }
222 if ( $revids ) {
223 $db = $this->getDB();
224 $sql = $db->unionQueries( [
225 $db->selectSQLText(
226 'revision',
227 [ 'id' => 'rev_id', 'ts' => 'rev_timestamp' ],
228 [ 'rev_id' => $revids ],
229 __METHOD__
230 ),
231 $db->selectSQLText(
232 'archive',
233 [ 'id' => 'ar_rev_id', 'ts' => 'ar_timestamp' ],
234 [ 'ar_rev_id' => $revids ],
235 __METHOD__
236 ),
237 ], false );
238 $res = $db->query( $sql, __METHOD__ );
239 foreach ( $res as $row ) {
240 if ( (int)$row->id === (int)$params['startid'] ) {
241 $params['start'] = $row->ts;
242 }
243 if ( (int)$row->id === (int)$params['endid'] ) {
244 $params['end'] = $row->ts;
245 }
246 }
247 if ( $params['startid'] !== null && $params['start'] === null ) {
248 $p = $this->encodeParamName( 'startid' );
249 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
250 }
251 if ( $params['endid'] !== null && $params['end'] === null ) {
252 $p = $this->encodeParamName( 'endid' );
253 $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
254 }
255
256 if ( $params['start'] !== null ) {
257 $op = ( $params['dir'] === 'newer' ? '>' : '<' );
258 $ts = $db->addQuotes( $db->timestampOrNull( $params['start'] ) );
259 if ( $params['startid'] !== null ) {
260 $this->addWhere( "rev_timestamp $op $ts OR "
261 . "rev_timestamp = $ts AND rev_id $op= " . intval( $params['startid'] ) );
262 } else {
263 $this->addWhere( "rev_timestamp $op= $ts" );
264 }
265 }
266 if ( $params['end'] !== null ) {
267 $op = ( $params['dir'] === 'newer' ? '<' : '>' ); // Yes, opposite of the above
268 $ts = $db->addQuotes( $db->timestampOrNull( $params['end'] ) );
269 if ( $params['endid'] !== null ) {
270 $this->addWhere( "rev_timestamp $op $ts OR "
271 . "rev_timestamp = $ts AND rev_id $op= " . intval( $params['endid'] ) );
272 } else {
273 $this->addWhere( "rev_timestamp $op= $ts" );
274 }
275 }
276 } else {
277 $this->addTimestampWhereRange( 'rev_timestamp', $params['dir'],
278 $params['start'], $params['end'] );
279 }
280
281 $sort = ( $params['dir'] === 'newer' ? '' : 'DESC' );
282 $this->addOption( 'ORDER BY', [ "rev_timestamp $sort", "rev_id $sort" ] );
283
284 // There is only one ID, use it
285 $ids = array_keys( $pageSet->getGoodTitles() );
286 $this->addWhereFld( 'rev_page', reset( $ids ) );
287
288 if ( $params['user'] !== null ) {
289 $user = User::newFromName( $params['user'] );
290 if ( $user && $user->getId() > 0 ) {
291 $this->addWhereFld( 'rev_user', $user->getId() );
292 } else {
293 $this->addWhereFld( 'rev_user_text', $params['user'] );
294 }
295 } elseif ( $params['excludeuser'] !== null ) {
296 $user = User::newFromName( $params['excludeuser'] );
297 if ( $user && $user->getId() > 0 ) {
298 $this->addWhere( 'rev_user != ' . $user->getId() );
299 } else {
300 $this->addWhere( 'rev_user_text != ' .
301 $db->addQuotes( $params['excludeuser'] ) );
302 }
303 }
304 if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
305 // Paranoia: avoid brute force searches (T19342)
306 if ( !$this->getUser()->isAllowed( 'deletedhistory' ) ) {
307 $bitmask = Revision::DELETED_USER;
308 } elseif ( !$this->getUser()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
309 $bitmask = Revision::DELETED_USER | Revision::DELETED_RESTRICTED;
310 } else {
311 $bitmask = 0;
312 }
313 if ( $bitmask ) {
314 $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
315 }
316 }
317 } elseif ( $revCount > 0 ) {
318 // Always targets the PRIMARY index
319
320 $revs = $pageSet->getLiveRevisionIDs();
321
322 // Get all revision IDs
323 $this->addWhereFld( 'rev_id', array_keys( $revs ) );
324
325 if ( $params['continue'] !== null ) {
326 $this->addWhere( 'rev_id >= ' . intval( $params['continue'] ) );
327 }
328 $this->addOption( 'ORDER BY', 'rev_id' );
329 } elseif ( $pageCount > 0 ) {
330 // Always targets the rev_page_id index
331
332 $titles = $pageSet->getGoodTitles();
333
334 // When working in multi-page non-enumeration mode,
335 // limit to the latest revision only
336 $this->addWhere( 'page_latest=rev_id' );
337
338 // Get all page IDs
339 $this->addWhereFld( 'page_id', array_keys( $titles ) );
340 // Every time someone relies on equality propagation, god kills a kitten :)
341 $this->addWhereFld( 'rev_page', array_keys( $titles ) );
342
343 if ( $params['continue'] !== null ) {
344 $cont = explode( '|', $params['continue'] );
345 $this->dieContinueUsageIf( count( $cont ) != 2 );
346 $pageid = intval( $cont[0] );
347 $revid = intval( $cont[1] );
348 $this->addWhere(
349 "rev_page > $pageid OR " .
350 "(rev_page = $pageid AND " .
351 "rev_id >= $revid)"
352 );
353 }
354 $this->addOption( 'ORDER BY', [
355 'rev_page',
356 'rev_id'
357 ] );
358 } else {
359 ApiBase::dieDebug( __METHOD__, 'param validation?' );
360 }
361
362 $this->addOption( 'LIMIT', $this->limit + 1 );
363
364 $count = 0;
365 $generated = [];
366 $hookData = [];
367 $res = $this->select( __METHOD__, [], $hookData );
368
369 foreach ( $res as $row ) {
370 if ( ++$count > $this->limit ) {
371 // We've reached the one extra which shows that there are
372 // additional pages to be had. Stop here...
373 if ( $enumRevMode ) {
374 $this->setContinueEnumParameter( 'continue',
375 $row->rev_timestamp . '|' . intval( $row->rev_id ) );
376 } elseif ( $revCount > 0 ) {
377 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
378 } else {
379 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
380 '|' . intval( $row->rev_id ) );
381 }
382 break;
383 }
384
385 if ( $resultPageSet !== null ) {
386 $generated[] = $row->rev_id;
387 } else {
388 $revision = new Revision( $row );
389 $rev = $this->extractRevisionInfo( $revision, $row );
390
391 if ( $this->token !== null ) {
392 $title = $revision->getTitle();
393 $tokenFunctions = $this->getTokenFunctions();
394 foreach ( $this->token as $t ) {
395 $val = call_user_func( $tokenFunctions[$t], $title->getArticleID(), $title, $revision );
396 if ( $val === false ) {
397 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
398 } else {
399 $rev[$t . 'token'] = $val;
400 }
401 }
402 }
403
404 $fit = $this->processRow( $row, $rev, $hookData ) &&
405 $this->addPageSubItem( $row->rev_page, $rev, 'rev' );
406 if ( !$fit ) {
407 if ( $enumRevMode ) {
408 $this->setContinueEnumParameter( 'continue',
409 $row->rev_timestamp . '|' . intval( $row->rev_id ) );
410 } elseif ( $revCount > 0 ) {
411 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
412 } else {
413 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
414 '|' . intval( $row->rev_id ) );
415 }
416 break;
417 }
418 }
419 }
420
421 if ( $resultPageSet !== null ) {
422 $resultPageSet->populateFromRevisionIDs( $generated );
423 }
424 }
425
426 public function getCacheMode( $params ) {
427 if ( isset( $params['token'] ) ) {
428 return 'private';
429 }
430 return parent::getCacheMode( $params );
431 }
432
433 public function getAllowedParams() {
434 $ret = parent::getAllowedParams() + [
435 'startid' => [
436 ApiBase::PARAM_TYPE => 'integer',
437 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
438 ],
439 'endid' => [
440 ApiBase::PARAM_TYPE => 'integer',
441 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
442 ],
443 'start' => [
444 ApiBase::PARAM_TYPE => 'timestamp',
445 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
446 ],
447 'end' => [
448 ApiBase::PARAM_TYPE => 'timestamp',
449 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
450 ],
451 'dir' => [
452 ApiBase::PARAM_DFLT => 'older',
453 ApiBase::PARAM_TYPE => [
454 'newer',
455 'older'
456 ],
457 ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
458 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
459 ],
460 'user' => [
461 ApiBase::PARAM_TYPE => 'user',
462 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
463 ],
464 'excludeuser' => [
465 ApiBase::PARAM_TYPE => 'user',
466 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
467 ],
468 'tag' => null,
469 'token' => [
470 ApiBase::PARAM_DEPRECATED => true,
471 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
472 ApiBase::PARAM_ISMULTI => true
473 ],
474 'continue' => [
475 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
476 ],
477 ];
478
479 $ret['limit'][ApiBase::PARAM_HELP_MSG_INFO] = [ [ 'singlepageonly' ] ];
480
481 return $ret;
482 }
483
484 protected function getExamplesMessages() {
485 return [
486 'action=query&prop=revisions&titles=API|Main%20Page&' .
487 'rvprop=timestamp|user|comment|content'
488 => 'apihelp-query+revisions-example-content',
489 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
490 'rvprop=timestamp|user|comment'
491 => 'apihelp-query+revisions-example-last5',
492 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
493 'rvprop=timestamp|user|comment&rvdir=newer'
494 => 'apihelp-query+revisions-example-first5',
495 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
496 'rvprop=timestamp|user|comment&rvdir=newer&rvstart=2006-05-01T00:00:00Z'
497 => 'apihelp-query+revisions-example-first5-after',
498 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
499 'rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1'
500 => 'apihelp-query+revisions-example-first5-not-localhost',
501 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
502 'rvprop=timestamp|user|comment&rvuser=MediaWiki%20default'
503 => 'apihelp-query+revisions-example-first5-user',
504 ];
505 }
506
507 public function getHelpUrls() {
508 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Revisions';
509 }
510 }