Merge "Move ExpandTemplates special into core"
[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 ApiQueryBase {
36
37 private $diffto, $difftotext, $expandTemplates, $generateXML, $section,
38 $token, $parseContent, $contentFormat;
39
40 public function __construct( $query, $moduleName ) {
41 parent::__construct( $query, $moduleName, 'rv' );
42 }
43
44 private $fld_ids = false, $fld_flags = false, $fld_timestamp = false,
45 $fld_size = false, $fld_sha1 = false, $fld_comment = false,
46 $fld_parsedcomment = false, $fld_user = false, $fld_userid = false,
47 $fld_content = false, $fld_tags = false, $fld_contentmodel = false;
48
49 private $tokenFunctions;
50
51 protected function getTokenFunctions() {
52 // tokenname => function
53 // function prototype is func($pageid, $title, $rev)
54 // should return token or false
55
56 // Don't call the hooks twice
57 if ( isset( $this->tokenFunctions ) ) {
58 return $this->tokenFunctions;
59 }
60
61 // If we're in JSON callback mode, no tokens can be obtained
62 if ( !is_null( $this->getMain()->getRequest()->getVal( 'callback' ) ) ) {
63 return array();
64 }
65
66 $this->tokenFunctions = array(
67 'rollback' => array( 'ApiQueryRevisions', 'getRollbackToken' )
68 );
69 wfRunHooks( 'APIQueryRevisionsTokens', array( &$this->tokenFunctions ) );
70
71 return $this->tokenFunctions;
72 }
73
74 /**
75 * @param $pageid
76 * @param $title Title
77 * @param $rev Revision
78 * @return bool|String
79 */
80 public static function getRollbackToken( $pageid, $title, $rev ) {
81 global $wgUser;
82 if ( !$wgUser->isAllowed( 'rollback' ) ) {
83 return false;
84 }
85
86 return $wgUser->getEditToken(
87 array( $title->getPrefixedText(), $rev->getUserText() ) );
88 }
89
90 public function execute() {
91 $params = $this->extractRequestParams( false );
92
93 // If any of those parameters are used, work in 'enumeration' mode.
94 // Enum mode can only be used when exactly one page is provided.
95 // Enumerating revisions on multiple pages make it extremely
96 // difficult to manage continuations and require additional SQL indexes
97 $enumRevMode = ( !is_null( $params['user'] ) || !is_null( $params['excludeuser'] ) ||
98 !is_null( $params['limit'] ) || !is_null( $params['startid'] ) ||
99 !is_null( $params['endid'] ) || $params['dir'] === 'newer' ||
100 !is_null( $params['start'] ) || !is_null( $params['end'] ) );
101
102 $pageSet = $this->getPageSet();
103 $pageCount = $pageSet->getGoodTitleCount();
104 $revCount = $pageSet->getRevisionCount();
105
106 // Optimization -- nothing to do
107 if ( $revCount === 0 && $pageCount === 0 ) {
108 return;
109 }
110
111 if ( $revCount > 0 && $enumRevMode ) {
112 $this->dieUsage(
113 'The revids= parameter may not be used with the list options ' .
114 '(limit, startid, endid, dirNewer, start, end).',
115 'revids'
116 );
117 }
118
119 if ( $pageCount > 1 && $enumRevMode ) {
120 $this->dieUsage(
121 'titles, pageids or a generator was used to supply multiple pages, ' .
122 'but the limit, startid, endid, dirNewer, user, excludeuser, start ' .
123 'and end parameters may only be used on a single page.',
124 'multpages'
125 );
126 }
127
128 if ( !is_null( $params['difftotext'] ) ) {
129 $this->difftotext = $params['difftotext'];
130 } elseif ( !is_null( $params['diffto'] ) ) {
131 if ( $params['diffto'] == 'cur' ) {
132 $params['diffto'] = 0;
133 }
134 if ( ( !ctype_digit( $params['diffto'] ) || $params['diffto'] < 0 )
135 && $params['diffto'] != 'prev' && $params['diffto'] != 'next'
136 ) {
137 $this->dieUsage(
138 'rvdiffto must be set to a non-negative number, "prev", "next" or "cur"',
139 'diffto'
140 );
141 }
142 // Check whether the revision exists and is readable,
143 // DifferenceEngine returns a rather ambiguous empty
144 // string if that's not the case
145 if ( $params['diffto'] != 0 ) {
146 $difftoRev = Revision::newFromID( $params['diffto'] );
147 if ( !$difftoRev ) {
148 $this->dieUsageMsg( array( 'nosuchrevid', $params['diffto'] ) );
149 }
150 if ( $difftoRev->isDeleted( Revision::DELETED_TEXT ) ) {
151 $this->setWarning( "Couldn't diff to r{$difftoRev->getID()}: content is hidden" );
152 $params['diffto'] = null;
153 }
154 }
155 $this->diffto = $params['diffto'];
156 }
157
158 $db = $this->getDB();
159 $this->addTables( 'page' );
160 $this->addFields( Revision::selectFields() );
161 $this->addWhere( 'page_id = rev_page' );
162
163 $prop = array_flip( $params['prop'] );
164
165 // Optional fields
166 $this->fld_ids = isset( $prop['ids'] );
167 // $this->addFieldsIf('rev_text_id', $this->fld_ids); // should this be exposed?
168 $this->fld_flags = isset( $prop['flags'] );
169 $this->fld_timestamp = isset( $prop['timestamp'] );
170 $this->fld_comment = isset( $prop['comment'] );
171 $this->fld_parsedcomment = isset( $prop['parsedcomment'] );
172 $this->fld_size = isset( $prop['size'] );
173 $this->fld_sha1 = isset( $prop['sha1'] );
174 $this->fld_contentmodel = isset( $prop['contentmodel'] );
175 $this->fld_userid = isset( $prop['userid'] );
176 $this->fld_user = isset( $prop['user'] );
177 $this->token = $params['token'];
178
179 if ( !empty( $params['contentformat'] ) ) {
180 $this->contentFormat = $params['contentformat'];
181 }
182
183 // Possible indexes used
184 $index = array();
185
186 $userMax = ( $this->fld_content ? ApiBase::LIMIT_SML1 : ApiBase::LIMIT_BIG1 );
187 $botMax = ( $this->fld_content ? ApiBase::LIMIT_SML2 : ApiBase::LIMIT_BIG2 );
188 $limit = $params['limit'];
189 if ( $limit == 'max' ) {
190 $limit = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
191 $this->getResult()->setParsedLimit( $this->getModuleName(), $limit );
192 }
193
194 if ( !is_null( $this->token ) || $pageCount > 0 ) {
195 $this->addFields( Revision::selectPageFields() );
196 }
197
198 if ( isset( $prop['tags'] ) ) {
199 $this->fld_tags = true;
200 $this->addTables( 'tag_summary' );
201 $this->addJoinConds(
202 array( 'tag_summary' => array( 'LEFT JOIN', array( 'rev_id=ts_rev_id' ) ) )
203 );
204 $this->addFields( 'ts_tags' );
205 }
206
207 if ( !is_null( $params['tag'] ) ) {
208 $this->addTables( 'change_tag' );
209 $this->addJoinConds(
210 array( 'change_tag' => array( 'INNER JOIN', array( 'rev_id=ct_rev_id' ) ) )
211 );
212 $this->addWhereFld( 'ct_tag', $params['tag'] );
213 $index['change_tag'] = 'change_tag_tag_id';
214 }
215
216 if ( isset( $prop['content'] ) || !is_null( $this->difftotext ) ) {
217 // For each page we will request, the user must have read rights for that page
218 $user = $this->getUser();
219 /** @var $title Title */
220 foreach ( $pageSet->getGoodTitles() as $title ) {
221 if ( !$title->userCan( 'read', $user ) ) {
222 $this->dieUsage(
223 'The current user is not allowed to read ' . $title->getPrefixedText(),
224 'accessdenied' );
225 }
226 }
227
228 $this->addTables( 'text' );
229 $this->addWhere( 'rev_text_id=old_id' );
230 $this->addFields( 'old_id' );
231 $this->addFields( Revision::selectTextFields() );
232
233 $this->fld_content = isset( $prop['content'] );
234
235 $this->expandTemplates = $params['expandtemplates'];
236 $this->generateXML = $params['generatexml'];
237 $this->parseContent = $params['parse'];
238 if ( $this->parseContent ) {
239 // Must manually initialize unset limit
240 if ( is_null( $limit ) ) {
241 $limit = 1;
242 }
243 // We are only going to parse 1 revision per request
244 $this->validateLimit( 'limit', $limit, 1, 1, 1 );
245 }
246 if ( isset( $params['section'] ) ) {
247 $this->section = $params['section'];
248 } else {
249 $this->section = false;
250 }
251 }
252
253 // add user name, if needed
254 if ( $this->fld_user ) {
255 $this->addTables( 'user' );
256 $this->addJoinConds( array( 'user' => Revision::userJoinCond() ) );
257 $this->addFields( Revision::selectUserFields() );
258 }
259
260 // Bug 24166 - API error when using rvprop=tags
261 $this->addTables( 'revision' );
262
263 if ( $enumRevMode ) {
264 // This is mostly to prevent parameter errors (and optimize SQL?)
265 if ( !is_null( $params['startid'] ) && !is_null( $params['start'] ) ) {
266 $this->dieUsage( 'start and startid cannot be used together', 'badparams' );
267 }
268
269 if ( !is_null( $params['endid'] ) && !is_null( $params['end'] ) ) {
270 $this->dieUsage( 'end and endid cannot be used together', 'badparams' );
271 }
272
273 if ( !is_null( $params['user'] ) && !is_null( $params['excludeuser'] ) ) {
274 $this->dieUsage( 'user and excludeuser cannot be used together', 'badparams' );
275 }
276
277 // Continuing effectively uses startid. But we can't use rvstartid
278 // directly, because there is no way to tell the client to ''not''
279 // send rvstart if it sent it in the original query. So instead we
280 // send the continuation startid as rvcontinue, and ignore both
281 // rvstart and rvstartid when that is supplied.
282 if ( !is_null( $params['continue'] ) ) {
283 $params['startid'] = $params['continue'];
284 $params['start'] = null;
285 }
286
287 // This code makes an assumption that sorting by rev_id and rev_timestamp produces
288 // the same result. This way users may request revisions starting at a given time,
289 // but to page through results use the rev_id returned after each page.
290 // Switching to rev_id removes the potential problem of having more than
291 // one row with the same timestamp for the same page.
292 // The order needs to be the same as start parameter to avoid SQL filesort.
293 if ( is_null( $params['startid'] ) && is_null( $params['endid'] ) ) {
294 $this->addTimestampWhereRange( 'rev_timestamp', $params['dir'],
295 $params['start'], $params['end'] );
296 } else {
297 $this->addWhereRange( 'rev_id', $params['dir'],
298 $params['startid'], $params['endid'] );
299 // One of start and end can be set
300 // If neither is set, this does nothing
301 $this->addTimestampWhereRange( 'rev_timestamp', $params['dir'],
302 $params['start'], $params['end'], false );
303 }
304
305 // must manually initialize unset limit
306 if ( is_null( $limit ) ) {
307 $limit = 10;
308 }
309 $this->validateLimit( 'limit', $limit, 1, $userMax, $botMax );
310
311 // There is only one ID, use it
312 $ids = array_keys( $pageSet->getGoodTitles() );
313 $this->addWhereFld( 'rev_page', reset( $ids ) );
314
315 if ( !is_null( $params['user'] ) ) {
316 $this->addWhereFld( 'rev_user_text', $params['user'] );
317 } elseif ( !is_null( $params['excludeuser'] ) ) {
318 $this->addWhere( 'rev_user_text != ' .
319 $db->addQuotes( $params['excludeuser'] ) );
320 }
321 if ( !is_null( $params['user'] ) || !is_null( $params['excludeuser'] ) ) {
322 // Paranoia: avoid brute force searches (bug 17342)
323 $this->addWhere( $db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' );
324 }
325 } elseif ( $revCount > 0 ) {
326 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
327 $revs = $pageSet->getRevisionIDs();
328 if ( self::truncateArray( $revs, $max ) ) {
329 $this->setWarning( "Too many values supplied for parameter 'revids': the limit is $max" );
330 }
331
332 // Get all revision IDs
333 $this->addWhereFld( 'rev_id', array_keys( $revs ) );
334
335 if ( !is_null( $params['continue'] ) ) {
336 $this->addWhere( 'rev_id >= ' . intval( $params['continue'] ) );
337 }
338 $this->addOption( 'ORDER BY', 'rev_id' );
339
340 // assumption testing -- we should never get more then $revCount rows.
341 $limit = $revCount;
342 } elseif ( $pageCount > 0 ) {
343 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
344 $titles = $pageSet->getGoodTitles();
345 if ( self::truncateArray( $titles, $max ) ) {
346 $this->setWarning( "Too many values supplied for parameter 'titles': the limit is $max" );
347 }
348
349 // When working in multi-page non-enumeration mode,
350 // limit to the latest revision only
351 $this->addWhere( 'page_id=rev_page' );
352 $this->addWhere( 'page_latest=rev_id' );
353
354 // Get all page IDs
355 $this->addWhereFld( 'page_id', array_keys( $titles ) );
356 // Every time someone relies on equality propagation, god kills a kitten :)
357 $this->addWhereFld( 'rev_page', array_keys( $titles ) );
358
359 if ( !is_null( $params['continue'] ) ) {
360 $cont = explode( '|', $params['continue'] );
361 $this->dieContinueUsageIf( count( $cont ) != 2 );
362 $pageid = intval( $cont[0] );
363 $revid = intval( $cont[1] );
364 $this->addWhere(
365 "rev_page > $pageid OR " .
366 "(rev_page = $pageid AND " .
367 "rev_id >= $revid)"
368 );
369 }
370 $this->addOption( 'ORDER BY', array(
371 'rev_page',
372 'rev_id'
373 ) );
374
375 // assumption testing -- we should never get more then $pageCount rows.
376 $limit = $pageCount;
377 } else {
378 ApiBase::dieDebug( __METHOD__, 'param validation?' );
379 }
380
381 $this->addOption( 'LIMIT', $limit + 1 );
382 $this->addOption( 'USE INDEX', $index );
383
384 $count = 0;
385 $res = $this->select( __METHOD__ );
386
387 foreach ( $res as $row ) {
388 if ( ++$count > $limit ) {
389 // We've reached the one extra which shows that there are
390 // additional pages to be had. Stop here...
391 if ( !$enumRevMode ) {
392 ApiBase::dieDebug( __METHOD__, 'Got more rows then expected' ); // bug report
393 }
394 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
395 break;
396 }
397
398 $fit = $this->addPageSubItem( $row->rev_page, $this->extractRowInfo( $row ), 'rev' );
399 if ( !$fit ) {
400 if ( $enumRevMode ) {
401 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
402 } elseif ( $revCount > 0 ) {
403 $this->setContinueEnumParameter( 'continue', intval( $row->rev_id ) );
404 } else {
405 $this->setContinueEnumParameter( 'continue', intval( $row->rev_page ) .
406 '|' . intval( $row->rev_id ) );
407 }
408 break;
409 }
410 }
411 }
412
413 private function extractRowInfo( $row ) {
414 $revision = new Revision( $row );
415 $title = $revision->getTitle();
416 $vals = array();
417
418 if ( $this->fld_ids ) {
419 $vals['revid'] = intval( $revision->getId() );
420 // $vals['oldid'] = intval( $row->rev_text_id ); // todo: should this be exposed?
421 if ( !is_null( $revision->getParentId() ) ) {
422 $vals['parentid'] = intval( $revision->getParentId() );
423 }
424 }
425
426 if ( $this->fld_flags && $revision->isMinor() ) {
427 $vals['minor'] = '';
428 }
429
430 if ( $this->fld_user || $this->fld_userid ) {
431 if ( $revision->isDeleted( Revision::DELETED_USER ) ) {
432 $vals['userhidden'] = '';
433 } else {
434 if ( $this->fld_user ) {
435 $vals['user'] = $revision->getUserText();
436 }
437 $userid = $revision->getUser();
438 if ( !$userid ) {
439 $vals['anon'] = '';
440 }
441
442 if ( $this->fld_userid ) {
443 $vals['userid'] = $userid;
444 }
445 }
446 }
447
448 if ( $this->fld_timestamp ) {
449 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $revision->getTimestamp() );
450 }
451
452 if ( $this->fld_size ) {
453 if ( !is_null( $revision->getSize() ) ) {
454 $vals['size'] = intval( $revision->getSize() );
455 } else {
456 $vals['size'] = 0;
457 }
458 }
459
460 if ( $this->fld_sha1 && !$revision->isDeleted( Revision::DELETED_TEXT ) ) {
461 if ( $revision->getSha1() != '' ) {
462 $vals['sha1'] = wfBaseConvert( $revision->getSha1(), 36, 16, 40 );
463 } else {
464 $vals['sha1'] = '';
465 }
466 } elseif ( $this->fld_sha1 ) {
467 $vals['sha1hidden'] = '';
468 }
469
470 if ( $this->fld_contentmodel ) {
471 $vals['contentmodel'] = $revision->getContentModel();
472 }
473
474 if ( $this->fld_comment || $this->fld_parsedcomment ) {
475 if ( $revision->isDeleted( Revision::DELETED_COMMENT ) ) {
476 $vals['commenthidden'] = '';
477 } else {
478 $comment = $revision->getComment();
479
480 if ( $this->fld_comment ) {
481 $vals['comment'] = $comment;
482 }
483
484 if ( $this->fld_parsedcomment ) {
485 $vals['parsedcomment'] = Linker::formatComment( $comment, $title );
486 }
487 }
488 }
489
490 if ( $this->fld_tags ) {
491 if ( $row->ts_tags ) {
492 $tags = explode( ',', $row->ts_tags );
493 $this->getResult()->setIndexedTagName( $tags, 'tag' );
494 $vals['tags'] = $tags;
495 } else {
496 $vals['tags'] = array();
497 }
498 }
499
500 if ( !is_null( $this->token ) ) {
501 $tokenFunctions = $this->getTokenFunctions();
502 foreach ( $this->token as $t ) {
503 $val = call_user_func( $tokenFunctions[$t], $title->getArticleID(), $title, $revision );
504 if ( $val === false ) {
505 $this->setWarning( "Action '$t' is not allowed for the current user" );
506 } else {
507 $vals[$t . 'token'] = $val;
508 }
509 }
510 }
511
512 $content = null;
513 global $wgParser;
514 if ( $this->fld_content || !is_null( $this->diffto ) || !is_null( $this->difftotext ) ) {
515 $content = $revision->getContent();
516 // Expand templates after getting section content because
517 // template-added sections don't count and Parser::preprocess()
518 // will have less input
519 if ( $content && $this->section !== false ) {
520 $content = $content->getSection( $this->section, false );
521 if ( !$content ) {
522 $this->dieUsage(
523 "There is no section {$this->section} in r" . $revision->getId(),
524 'nosuchsection'
525 );
526 }
527 }
528 }
529 if ( $this->fld_content && $content && !$revision->isDeleted( Revision::DELETED_TEXT ) ) {
530 $text = null;
531
532 if ( $this->generateXML ) {
533 if ( $content->getModel() === CONTENT_MODEL_WIKITEXT ) {
534 $t = $content->getNativeData(); # note: don't set $text
535
536 $wgParser->startExternalParse(
537 $title,
538 ParserOptions::newFromContext( $this->getContext() ),
539 OT_PREPROCESS
540 );
541 $dom = $wgParser->preprocessToDom( $t );
542 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
543 $xml = $dom->saveXML();
544 } else {
545 $xml = $dom->__toString();
546 }
547 $vals['parsetree'] = $xml;
548 } else {
549 $this->setWarning( "Conversion to XML is supported for wikitext only, " .
550 $title->getPrefixedDBkey() .
551 " uses content model " . $content->getModel() );
552 }
553 }
554
555 if ( $this->expandTemplates && !$this->parseContent ) {
556 #XXX: implement template expansion for all content types in ContentHandler?
557 if ( $content->getModel() === CONTENT_MODEL_WIKITEXT ) {
558 $text = $content->getNativeData();
559
560 $text = $wgParser->preprocess(
561 $text,
562 $title,
563 ParserOptions::newFromContext( $this->getContext() )
564 );
565 } else {
566 $this->setWarning( "Template expansion is supported for wikitext only, " .
567 $title->getPrefixedDBkey() .
568 " uses content model " . $content->getModel() );
569
570 $text = false;
571 }
572 }
573 if ( $this->parseContent ) {
574 $po = $content->getParserOutput(
575 $title,
576 $revision->getId(),
577 ParserOptions::newFromContext( $this->getContext() )
578 );
579 $text = $po->getText();
580 }
581
582 if ( $text === null ) {
583 $format = $this->contentFormat ? $this->contentFormat : $content->getDefaultFormat();
584 $model = $content->getModel();
585
586 if ( !$content->isSupportedFormat( $format ) ) {
587 $name = $title->getPrefixedDBkey();
588
589 $this->dieUsage( "The requested format {$this->contentFormat} is not supported " .
590 "for content model $model used by $name", 'badformat' );
591 }
592
593 $text = $content->serialize( $format );
594
595 // always include format and model.
596 // Format is needed to deserialize, model is needed to interpret.
597 $vals['contentformat'] = $format;
598 $vals['contentmodel'] = $model;
599 }
600
601 if ( $text !== false ) {
602 ApiResult::setContent( $vals, $text );
603 }
604 } elseif ( $this->fld_content ) {
605 if ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
606 $vals['texthidden'] = '';
607 } else {
608 $vals['textmissing'] = '';
609 }
610 }
611
612 if ( !is_null( $this->diffto ) || !is_null( $this->difftotext ) ) {
613 global $wgAPIMaxUncachedDiffs;
614 static $n = 0; // Number of uncached diffs we've had
615
616 if ( is_null( $content ) ) {
617 $vals['textmissing'] = '';
618 } elseif ( $n < $wgAPIMaxUncachedDiffs ) {
619 $vals['diff'] = array();
620 $context = new DerivativeContext( $this->getContext() );
621 $context->setTitle( $title );
622 $handler = $revision->getContentHandler();
623
624 if ( !is_null( $this->difftotext ) ) {
625 $model = $title->getContentModel();
626
627 if ( $this->contentFormat
628 && !ContentHandler::getForModelID( $model )->isSupportedFormat( $this->contentFormat )
629 ) {
630
631 $name = $title->getPrefixedDBkey();
632
633 $this->dieUsage( "The requested format {$this->contentFormat} is not supported for " .
634 "content model $model used by $name", 'badformat' );
635 }
636
637 $difftocontent = ContentHandler::makeContent(
638 $this->difftotext,
639 $title,
640 $model,
641 $this->contentFormat
642 );
643
644 $engine = $handler->createDifferenceEngine( $context );
645 $engine->setContent( $content, $difftocontent );
646 } else {
647 $engine = $handler->createDifferenceEngine( $context, $revision->getID(), $this->diffto );
648 $vals['diff']['from'] = $engine->getOldid();
649 $vals['diff']['to'] = $engine->getNewid();
650 }
651 $difftext = $engine->getDiffBody();
652 ApiResult::setContent( $vals['diff'], $difftext );
653 if ( !$engine->wasCacheHit() ) {
654 $n++;
655 }
656 } else {
657 $vals['diff']['notcached'] = '';
658 }
659 }
660
661 return $vals;
662 }
663
664 public function getCacheMode( $params ) {
665 if ( isset( $params['token'] ) ) {
666 return 'private';
667 }
668 if ( !is_null( $params['prop'] ) && in_array( 'parsedcomment', $params['prop'] ) ) {
669 // formatComment() calls wfMessage() among other things
670 return 'anon-public-user-private';
671 }
672
673 return 'public';
674 }
675
676 public function getAllowedParams() {
677 return array(
678 'prop' => array(
679 ApiBase::PARAM_ISMULTI => true,
680 ApiBase::PARAM_DFLT => 'ids|timestamp|flags|comment|user',
681 ApiBase::PARAM_TYPE => array(
682 'ids',
683 'flags',
684 'timestamp',
685 'user',
686 'userid',
687 'size',
688 'sha1',
689 'contentmodel',
690 'comment',
691 'parsedcomment',
692 'content',
693 'tags'
694 )
695 ),
696 'limit' => array(
697 ApiBase::PARAM_TYPE => 'limit',
698 ApiBase::PARAM_MIN => 1,
699 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
700 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
701 ),
702 'startid' => array(
703 ApiBase::PARAM_TYPE => 'integer'
704 ),
705 'endid' => array(
706 ApiBase::PARAM_TYPE => 'integer'
707 ),
708 'start' => array(
709 ApiBase::PARAM_TYPE => 'timestamp'
710 ),
711 'end' => array(
712 ApiBase::PARAM_TYPE => 'timestamp'
713 ),
714 'dir' => array(
715 ApiBase::PARAM_DFLT => 'older',
716 ApiBase::PARAM_TYPE => array(
717 'newer',
718 'older'
719 )
720 ),
721 'user' => array(
722 ApiBase::PARAM_TYPE => 'user'
723 ),
724 'excludeuser' => array(
725 ApiBase::PARAM_TYPE => 'user'
726 ),
727 'tag' => null,
728 'expandtemplates' => false,
729 'generatexml' => false,
730 'parse' => false,
731 'section' => null,
732 'token' => array(
733 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
734 ApiBase::PARAM_ISMULTI => true
735 ),
736 'continue' => null,
737 'diffto' => null,
738 'difftotext' => null,
739 'contentformat' => array(
740 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
741 ApiBase::PARAM_DFLT => null
742 ),
743 );
744 }
745
746 public function getParamDescription() {
747 $p = $this->getModulePrefix();
748
749 return array(
750 'prop' => array(
751 'Which properties to get for each revision:',
752 ' ids - The ID of the revision',
753 ' flags - Revision flags (minor)',
754 ' timestamp - The timestamp of the revision',
755 ' user - User that made the revision',
756 ' userid - User id of revision creator',
757 ' size - Length (bytes) of the revision',
758 ' sha1 - SHA-1 (base 16) of the revision',
759 ' contentmodel - Content model id',
760 ' comment - Comment by the user for revision',
761 ' parsedcomment - Parsed comment by the user for the revision',
762 ' content - Text of the revision',
763 ' tags - Tags for the revision',
764 ),
765 'limit' => 'Limit how many revisions will be returned (enum)',
766 'startid' => 'From which revision id to start enumeration (enum)',
767 'endid' => 'Stop revision enumeration on this revid (enum)',
768 'start' => 'From which revision timestamp to start enumeration (enum)',
769 'end' => 'Enumerate up to this timestamp (enum)',
770 'dir' => $this->getDirectionDescription( $p, ' (enum)' ),
771 'user' => 'Only include revisions made by user (enum)',
772 'excludeuser' => 'Exclude revisions made by user (enum)',
773 'expandtemplates' => "Expand templates in revision content (requires {$p}prop=content)",
774 'generatexml' => "Generate XML parse tree for revision content (requires {$p}prop=content)",
775 'parse' => array( "Parse revision content (requires {$p}prop=content).",
776 'For performance reasons if this option is used, rvlimit is enforced to 1.' ),
777 'section' => 'Only retrieve the content of this section number',
778 'token' => 'Which tokens to obtain for each revision',
779 'continue' => 'When more results are available, use this to continue',
780 'diffto' => array( 'Revision ID to diff each revision to.',
781 'Use "prev", "next" and "cur" for the previous, next and current revision respectively' ),
782 'difftotext' => array(
783 'Text to diff each revision to. Only diffs a limited number of revisions.',
784 "Overrides {$p}diffto. If {$p}section is set, only that section will be",
785 'diffed against this text',
786 ),
787 'tag' => 'Only list revisions tagged with this tag',
788 'contentformat' => 'Serialization format used for difftotext and expected for output of content',
789 );
790 }
791
792 public function getResultProperties() {
793 $props = array(
794 '' => array(),
795 'ids' => array(
796 'revid' => 'integer',
797 'parentid' => array(
798 ApiBase::PROP_TYPE => 'integer',
799 ApiBase::PROP_NULLABLE => true
800 )
801 ),
802 'flags' => array(
803 'minor' => 'boolean'
804 ),
805 'user' => array(
806 'userhidden' => 'boolean',
807 'user' => 'string',
808 'anon' => 'boolean'
809 ),
810 'userid' => array(
811 'userhidden' => 'boolean',
812 'userid' => 'integer',
813 'anon' => 'boolean'
814 ),
815 'timestamp' => array(
816 'timestamp' => 'timestamp'
817 ),
818 'size' => array(
819 'size' => 'integer'
820 ),
821 'sha1' => array(
822 'sha1' => 'string'
823 ),
824 'comment' => array(
825 'commenthidden' => 'boolean',
826 'comment' => array(
827 ApiBase::PROP_TYPE => 'string',
828 ApiBase::PROP_NULLABLE => true
829 )
830 ),
831 'parsedcomment' => array(
832 'commenthidden' => 'boolean',
833 'parsedcomment' => array(
834 ApiBase::PROP_TYPE => 'string',
835 ApiBase::PROP_NULLABLE => true
836 )
837 ),
838 'content' => array(
839 '*' => array(
840 ApiBase::PROP_TYPE => 'string',
841 ApiBase::PROP_NULLABLE => true
842 ),
843 'texthidden' => 'boolean',
844 'textmissing' => 'boolean',
845 ),
846 'contentmodel' => array(
847 'contentmodel' => 'string'
848 ),
849 );
850
851 self::addTokenProperties( $props, $this->getTokenFunctions() );
852
853 return $props;
854 }
855
856 public function getDescription() {
857 return array(
858 'Get revision information',
859 'May be used in several ways:',
860 ' 1) Get data about a set of pages (last revision), by setting titles or pageids parameter',
861 ' 2) Get revisions for one given page, by using titles/pageids with start/end/limit params',
862 ' 3) Get data about a set of revisions by setting their IDs with revids parameter',
863 'All parameters marked as (enum) may only be used with a single page (#2)'
864 );
865 }
866
867 public function getPossibleErrors() {
868 return array_merge( parent::getPossibleErrors(), array(
869 array( 'nosuchrevid', 'diffto' ),
870 array(
871 'code' => 'revids',
872 'info' => 'The revids= parameter may not be used with the list options '
873 . '(limit, startid, endid, dirNewer, start, end).'
874 ),
875 array(
876 'code' => 'multpages',
877 'info' => 'titles, pageids or a generator was used to supply multiple pages, '
878 . ' but the limit, startid, endid, dirNewer, user, excludeuser, '
879 . 'start and end parameters may only be used on a single page.'
880 ),
881 array(
882 'code' => 'diffto',
883 'info' => 'rvdiffto must be set to a non-negative number, "prev", "next" or "cur"'
884 ),
885 array( 'code' => 'badparams', 'info' => 'start and startid cannot be used together' ),
886 array( 'code' => 'badparams', 'info' => 'end and endid cannot be used together' ),
887 array( 'code' => 'badparams', 'info' => 'user and excludeuser cannot be used together' ),
888 array( 'code' => 'nosuchsection', 'info' => 'There is no section section in rID' ),
889 array( 'code' => 'badformat', 'info' => 'The requested serialization format can not be applied '
890 . ' to the page\'s content model' ),
891 ) );
892 }
893
894 public function getExamples() {
895 return array(
896 'Get data with content for the last revision of titles "API" and "Main Page"',
897 ' api.php?action=query&prop=revisions&titles=API|Main%20Page&' .
898 'rvprop=timestamp|user|comment|content',
899 'Get last 5 revisions of the "Main Page"',
900 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
901 'rvprop=timestamp|user|comment',
902 'Get first 5 revisions of the "Main Page"',
903 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
904 'rvprop=timestamp|user|comment&rvdir=newer',
905 'Get first 5 revisions of the "Main Page" made after 2006-05-01',
906 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
907 'rvprop=timestamp|user|comment&rvdir=newer&rvstart=20060501000000',
908 'Get first 5 revisions of the "Main Page" that were not made made by anonymous user "127.0.0.1"',
909 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
910 'rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1',
911 'Get first 5 revisions of the "Main Page" that were made by the user "MediaWiki default"',
912 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
913 'rvprop=timestamp|user|comment&rvuser=MediaWiki%20default',
914 );
915 }
916
917 public function getHelpUrls() {
918 return 'https://www.mediawiki.org/wiki/API:Properties#revisions_.2F_rv';
919 }
920 }