removed x-codeBlob functions and modified blob handling acordingly
[mediawiki.git] / includes / api / ApiQueryRevisions.php
blobe705cea4b76be3e279455528b23ff3e62fa496e7
1 <?php
3 /*
4 * Created on Sep 7, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiQueryBase.php');
31 /**
32 * A query action to enumerate revisions of a given page, or show top revisions of multiple pages.
33 * Various pieces of information may be shown - flags, comments, and the actual wiki markup of the rev.
34 * In the enumeration mode, ranges of revisions may be requested and filtered.
36 * @ingroup API
38 class ApiQueryRevisions extends ApiQueryBase {
40 public function __construct($query, $moduleName) {
41 parent :: __construct($query, $moduleName, 'rv');
44 private $fld_ids = false, $fld_flags = false, $fld_timestamp = false, $fld_size = false,
45 $fld_comment = false, $fld_user = false, $fld_content = false, $fld_tags = false;
47 protected function getTokenFunctions() {
48 // tokenname => function
49 // function prototype is func($pageid, $title, $rev)
50 // should return token or false
52 // Don't call the hooks twice
53 if(isset($this->tokenFunctions))
54 return $this->tokenFunctions;
56 // If we're in JSON callback mode, no tokens can be obtained
57 if(!is_null($this->getMain()->getRequest()->getVal('callback')))
58 return array();
60 $this->tokenFunctions = array(
61 'rollback' => array( 'ApiQueryRevisions', 'getRollbackToken' )
63 wfRunHooks('APIQueryRevisionsTokens', array(&$this->tokenFunctions));
64 return $this->tokenFunctions;
67 public static function getRollbackToken($pageid, $title, $rev)
69 global $wgUser;
70 if(!$wgUser->isAllowed('rollback'))
71 return false;
72 return $wgUser->editToken(array($title->getPrefixedText(),
73 $rev->getUserText()));
76 public function execute() {
77 $params = $this->extractRequestParams(false);
79 // If any of those parameters are used, work in 'enumeration' mode.
80 // Enum mode can only be used when exactly one page is provided.
81 // Enumerating revisions on multiple pages make it extremely
82 // difficult to manage continuations and require additional SQL indexes
83 $enumRevMode = (!is_null($params['user']) || !is_null($params['excludeuser']) ||
84 !is_null($params['limit']) || !is_null($params['startid']) ||
85 !is_null($params['endid']) || $params['dir'] === 'newer' ||
86 !is_null($params['start']) || !is_null($params['end']));
89 $pageSet = $this->getPageSet();
90 $pageCount = $pageSet->getGoodTitleCount();
91 $revCount = $pageSet->getRevisionCount();
93 // Optimization -- nothing to do
94 if ($revCount === 0 && $pageCount === 0)
95 return;
97 if ($revCount > 0 && $enumRevMode)
98 $this->dieUsage('The revids= parameter may not be used with the list options (limit, startid, endid, dirNewer, start, end).', 'revids');
100 if ($pageCount > 1 && $enumRevMode)
101 $this->dieUsage('titles, pageids or a generator was used to supply multiple pages, but the limit, startid, endid, dirNewer, user, excludeuser, start and end parameters may only be used on a single page.', 'multpages');
103 if (!is_null($params['diffto'])) {
104 if ($params['diffto'] == 'cur')
105 $params['diffto'] = 0;
106 if ((!ctype_digit($params['diffto']) || $params['diffto'] < 0)
107 && $params['diffto'] != 'prev' && $params['diffto'] != 'next')
108 $this->dieUsage('rvdiffto must be set to a non-negative number, "prev", "next" or "cur"', 'diffto');
109 // Check whether the revision exists and is readable,
110 // DifferenceEngine returns a rather ambiguous empty
111 // string if that's not the case
112 if ($params['diffto'] != 0) {
113 $difftoRev = Revision::newFromID($params['diffto']);
114 if (!$difftoRev)
115 $this->dieUsageMsg(array('nosuchrevid', $params['diffto']));
116 if (!$difftoRev->userCan(Revision::DELETED_TEXT)) {
117 $this->setWarning("Couldn't diff to r{$difftoRev->getID()}: content is hidden");
118 $params['diffto'] = null;
123 $db = $this->getDB();
124 $this->addTables(array('page', 'revision'));
125 $this->addFields(Revision::selectFields());
126 $this->addWhere('page_id = rev_page');
128 $prop = array_flip($params['prop']);
130 // Optional fields
131 $this->fld_ids = isset ($prop['ids']);
132 // $this->addFieldsIf('rev_text_id', $this->fld_ids); // should this be exposed?
133 $this->fld_flags = isset ($prop['flags']);
134 $this->fld_timestamp = isset ($prop['timestamp']);
135 $this->fld_comment = isset ($prop['comment']);
136 $this->fld_size = isset ($prop['size']);
137 $this->fld_user = isset ($prop['user']);
138 $this->token = $params['token'];
139 $this->diffto = $params['diffto'];
141 if ( !is_null($this->token) || $pageCount > 0) {
142 $this->addFields( Revision::selectPageFields() );
145 if (isset ($prop['tags'])) {
146 $this->fld_tags = true;
147 $this->addTables('tag_summary');
148 $this->addJoinConds(array('tag_summary' => array('LEFT JOIN', array('rev_id=ts_rev_id'))));
149 $this->addFields('ts_tags');
152 if( !is_null($params['tag']) ) {
153 $this->addTables('change_tag');
154 $this->addJoinConds(array('change_tag' => array('INNER JOIN', array('rev_id=ct_rev_id'))));
155 $this->addWhereFld('ct_tag' , $params['tag']);
158 if (isset ($prop['content'])) {
160 // For each page we will request, the user must have read rights for that page
161 foreach ($pageSet->getGoodTitles() as $title) {
162 if( !$title->userCanRead() )
163 $this->dieUsage(
164 'The current user is not allowed to read ' . $title->getPrefixedText(),
165 'accessdenied');
168 $this->addTables('text');
169 $this->addWhere('rev_text_id=old_id');
170 $this->addFields('old_id');
171 $this->addFields(Revision::selectTextFields());
173 $this->fld_content = true;
175 $this->expandTemplates = $params['expandtemplates'];
176 $this->generateXML = $params['generatexml'];
177 if(isset($params['section']))
178 $this->section = $params['section'];
179 else
180 $this->section = false;
183 $userMax = ( $this->fld_content ? ApiBase::LIMIT_SML1 : ApiBase::LIMIT_BIG1 );
184 $botMax = ( $this->fld_content ? ApiBase::LIMIT_SML2 : ApiBase::LIMIT_BIG2 );
185 $limit = $params['limit'];
186 if( $limit == 'max' ) {
187 $limit = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
188 $this->getResult()->addValue( 'limits', $this->getModuleName(), $limit );
191 if ($enumRevMode) {
193 // This is mostly to prevent parameter errors (and optimize SQL?)
194 if (!is_null($params['startid']) && !is_null($params['start']))
195 $this->dieUsage('start and startid cannot be used together', 'badparams');
197 if (!is_null($params['endid']) && !is_null($params['end']))
198 $this->dieUsage('end and endid cannot be used together', 'badparams');
200 if(!is_null($params['user']) && !is_null($params['excludeuser']))
201 $this->dieUsage('user and excludeuser cannot be used together', 'badparams');
203 // This code makes an assumption that sorting by rev_id and rev_timestamp produces
204 // the same result. This way users may request revisions starting at a given time,
205 // but to page through results use the rev_id returned after each page.
206 // Switching to rev_id removes the potential problem of having more than
207 // one row with the same timestamp for the same page.
208 // The order needs to be the same as start parameter to avoid SQL filesort.
210 if (is_null($params['startid']) && is_null($params['endid']))
211 $this->addWhereRange('rev_timestamp', $params['dir'],
212 $params['start'], $params['end']);
213 else {
214 $this->addWhereRange('rev_id', $params['dir'],
215 $params['startid'], $params['endid']);
216 // One of start and end can be set
217 // If neither is set, this does nothing
218 $this->addWhereRange('rev_timestamp', $params['dir'],
219 $params['start'], $params['end'], false);
222 // must manually initialize unset limit
223 if (is_null($limit))
224 $limit = 10;
225 $this->validateLimit('limit', $limit, 1, $userMax, $botMax);
227 // There is only one ID, use it
228 $ids = array_keys($pageSet->getGoodTitles());
229 $this->addWhereFld('rev_page', reset($ids));
231 if(!is_null($params['user'])) {
232 $this->addWhereFld('rev_user_text', $params['user']);
233 } elseif (!is_null($params['excludeuser'])) {
234 $this->addWhere('rev_user_text != ' .
235 $db->addQuotes($params['excludeuser']));
237 if(!is_null($params['user']) || !is_null($params['excludeuser'])) {
238 // Paranoia: avoid brute force searches (bug 17342)
239 $this->addWhere($db->bitAnd('rev_deleted',Revision::DELETED_USER) . ' = 0');
242 elseif ($revCount > 0) {
243 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
244 $revs = $pageSet->getRevisionIDs();
245 if(self::truncateArray($revs, $max))
246 $this->setWarning("Too many values supplied for parameter 'revids': the limit is $max");
248 // Get all revision IDs
249 $this->addWhereFld('rev_id', array_keys($revs));
251 if(!is_null($params['continue']))
252 $this->addWhere("rev_id >= '" . intval($params['continue']) . "'");
253 $this->addOption('ORDER BY', 'rev_id');
255 // assumption testing -- we should never get more then $revCount rows.
256 $limit = $revCount;
258 elseif ($pageCount > 0) {
259 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
260 $titles = $pageSet->getGoodTitles();
261 if(self::truncateArray($titles, $max))
262 $this->setWarning("Too many values supplied for parameter 'titles': the limit is $max");
264 // When working in multi-page non-enumeration mode,
265 // limit to the latest revision only
266 $this->addWhere('page_id=rev_page');
267 $this->addWhere('page_latest=rev_id');
269 // Get all page IDs
270 $this->addWhereFld('page_id', array_keys($titles));
271 // Every time someone relies on equality propagation, god kills a kitten :)
272 $this->addWhereFld('rev_page', array_keys($titles));
274 if(!is_null($params['continue']))
276 $cont = explode('|', $params['continue']);
277 if(count($cont) != 2)
278 $this->dieUsage("Invalid continue param. You should pass the original " .
279 "value returned by the previous query", "_badcontinue");
280 $pageid = intval($cont[0]);
281 $revid = intval($cont[1]);
282 $this->addWhere("rev_page > '$pageid' OR " .
283 "(rev_page = '$pageid' AND " .
284 "rev_id >= '$revid')");
286 $this->addOption('ORDER BY', 'rev_page, rev_id');
288 // assumption testing -- we should never get more then $pageCount rows.
289 $limit = $pageCount;
290 } else
291 ApiBase :: dieDebug(__METHOD__, 'param validation?');
293 $this->addOption('LIMIT', $limit +1);
295 $data = array ();
296 $count = 0;
297 $res = $this->select(__METHOD__);
299 while ($row = $db->fetchObject($res)) {
301 if (++ $count > $limit) {
302 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
303 if (!$enumRevMode)
304 ApiBase :: dieDebug(__METHOD__, 'Got more rows then expected'); // bug report
305 $this->setContinueEnumParameter('startid', intval($row->rev_id));
306 break;
310 $fit = $this->addPageSubItem($row->rev_page, $this->extractRowInfo($row), 'rev');
311 if(!$fit)
313 if($enumRevMode)
314 $this->setContinueEnumParameter('startid', intval($row->rev_id));
315 else if($revCount > 0)
316 $this->setContinueEnumParameter('continue', intval($row->rev_id));
317 else
318 $this->setContinueEnumParameter('continue', intval($row->rev_page) .
319 '|' . intval($row->rev_id));
320 break;
323 $db->freeResult($res);
326 private function extractRowInfo( $row ) {
327 $revision = new Revision( $row );
328 $title = $revision->getTitle();
329 $vals = array ();
331 if ($this->fld_ids) {
332 $vals['revid'] = intval($revision->getId());
333 // $vals['oldid'] = intval($row->rev_text_id); // todo: should this be exposed?
334 if (!is_null($revision->getParentId()))
335 $vals['parentid'] = intval($revision->getParentId());
338 if ($this->fld_flags && $revision->isMinor())
339 $vals['minor'] = '';
341 if ($this->fld_user) {
342 if ($revision->isDeleted(Revision::DELETED_USER)) {
343 $vals['userhidden'] = '';
344 } else {
345 $vals['user'] = $revision->getUserText();
346 if (!$revision->getUser())
347 $vals['anon'] = '';
351 if ($this->fld_timestamp) {
352 $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $revision->getTimestamp());
355 if ($this->fld_size && !is_null($revision->getSize())) {
356 $vals['size'] = intval($revision->getSize());
359 if ($this->fld_comment) {
360 if ($revision->isDeleted(Revision::DELETED_COMMENT)) {
361 $vals['commenthidden'] = '';
362 } else {
363 $comment = $revision->getComment();
364 if (strval($comment) !== '')
365 $vals['comment'] = $comment;
369 if ($this->fld_tags) {
370 if ($row->ts_tags) {
371 $tags = explode(',', $row->ts_tags);
372 $this->getResult()->setIndexedTagName($tags, 'tag');
373 $vals['tags'] = $tags;
374 } else {
375 $vals['tags'] = array();
379 if(!is_null($this->token))
381 $tokenFunctions = $this->getTokenFunctions();
382 foreach($this->token as $t)
384 $val = call_user_func($tokenFunctions[$t], $title->getArticleID(), $title, $revision);
385 if($val === false)
386 $this->setWarning("Action '$t' is not allowed for the current user");
387 else
388 $vals[$t . 'token'] = $val;
392 if ($this->fld_content && !$revision->isDeleted(Revision::DELETED_TEXT)) {
393 global $wgParser;
394 $text = $revision->getText();
395 # Expand templates after getting section content because
396 # template-added sections don't count and Parser::preprocess()
397 # will have less input
398 if ($this->section !== false) {
399 $text = $wgParser->getSection( $text, $this->section, false);
400 if($text === false)
401 $this->dieUsage("There is no section {$this->section} in r".$revision->getId(), 'nosuchsection');
403 if ($this->generateXML) {
404 $wgParser->startExternalParse( $title, new ParserOptions(), OT_PREPROCESS );
405 $dom = $wgParser->preprocessToDom( $text );
406 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
407 $xml = $dom->saveXML();
408 } else {
409 $xml = $dom->__toString();
411 $vals['parsetree'] = $xml;
414 if ($this->expandTemplates) {
415 $text = $wgParser->preprocess( $text, $title, new ParserOptions() );
417 ApiResult :: setContent($vals, $text);
418 } else if ($this->fld_content) {
419 $vals['texthidden'] = '';
422 if (!is_null($this->diffto)) {
423 global $wgAPIMaxUncachedDiffs;
424 static $n = 0; // Numer of uncached diffs we've had
425 if($n< $wgAPIMaxUncachedDiffs) {
426 $engine = new DifferenceEngine($title, $revision->getID(), $this->diffto);
427 $difftext = $engine->getDiffBody();
428 $vals['diff']['from'] = $engine->getOldid();
429 $vals['diff']['to'] = $engine->getNewid();
430 ApiResult::setContent($vals['diff'], $difftext);
431 if(!$engine->wasCacheHit())
432 $n++;
433 } else {
434 $vals['diff']['notcached'] = '';
437 return $vals;
440 public function getAllowedParams() {
441 return array (
442 'prop' => array (
443 ApiBase :: PARAM_ISMULTI => true,
444 ApiBase :: PARAM_DFLT => 'ids|timestamp|flags|comment|user',
445 ApiBase :: PARAM_TYPE => array (
446 'ids',
447 'flags',
448 'timestamp',
449 'user',
450 'size',
451 'comment',
452 'content',
453 'tags'
456 'limit' => array (
457 ApiBase :: PARAM_TYPE => 'limit',
458 ApiBase :: PARAM_MIN => 1,
459 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
460 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
462 'startid' => array (
463 ApiBase :: PARAM_TYPE => 'integer'
465 'endid' => array (
466 ApiBase :: PARAM_TYPE => 'integer'
468 'start' => array (
469 ApiBase :: PARAM_TYPE => 'timestamp'
471 'end' => array (
472 ApiBase :: PARAM_TYPE => 'timestamp'
474 'dir' => array (
475 ApiBase :: PARAM_DFLT => 'older',
476 ApiBase :: PARAM_TYPE => array (
477 'newer',
478 'older'
481 'user' => array(
482 ApiBase :: PARAM_TYPE => 'user'
484 'excludeuser' => array(
485 ApiBase :: PARAM_TYPE => 'user'
487 'tag' => null,
488 'expandtemplates' => false,
489 'generatexml' => false,
490 'section' => null,
491 'token' => array(
492 ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions()),
493 ApiBase :: PARAM_ISMULTI => true
495 'continue' => null,
496 'diffto' => null,
500 public function getParamDescription() {
501 return array (
502 'prop' => 'Which properties to get for each revision.',
503 'limit' => 'limit how many revisions will be returned (enum)',
504 'startid' => 'from which revision id to start enumeration (enum)',
505 'endid' => 'stop revision enumeration on this revid (enum)',
506 'start' => 'from which revision timestamp to start enumeration (enum)',
507 'end' => 'enumerate up to this timestamp (enum)',
508 'dir' => 'direction of enumeration - towards "newer" or "older" revisions (enum)',
509 'user' => 'only include revisions made by user',
510 'excludeuser' => 'exclude revisions made by user',
511 'expandtemplates' => 'expand templates in revision content',
512 'generatexml' => 'generate XML parse tree for revision content',
513 'section' => 'only retrieve the content of this section',
514 'token' => 'Which tokens to obtain for each revision',
515 'continue' => 'When more results are available, use this to continue',
516 'diffto' => array('Revision ID to diff each revision to.',
517 'Use "prev", "next" and "cur" for the previous, next and current revision respectively.'),
518 'tag' => 'Only list revisions tagged with this tag',
522 public function getDescription() {
523 return array (
524 'Get revision information.',
525 'This module may be used in several ways:',
526 ' 1) Get data about a set of pages (last revision), by setting titles or pageids parameter.',
527 ' 2) Get revisions for one given page, by using titles/pageids with start/end/limit params.',
528 ' 3) Get data about a set of revisions by setting their IDs with revids parameter.',
529 'All parameters marked as (enum) may only be used with a single page (#2).'
533 protected function getExamples() {
534 return array (
535 'Get data with content for the last revision of titles "API" and "Main Page":',
536 ' api.php?action=query&prop=revisions&titles=API|Main%20Page&rvprop=timestamp|user|comment|content',
537 'Get last 5 revisions of the "Main Page":',
538 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment',
539 'Get first 5 revisions of the "Main Page":',
540 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer',
541 'Get first 5 revisions of the "Main Page" made after 2006-05-01:',
542 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer&rvstart=20060501000000',
543 'Get first 5 revisions of the "Main Page" that were not made made by anonymous user "127.0.0.1"',
544 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1',
545 'Get first 5 revisions of the "Main Page" that were made by the user "MediaWiki default"',
546 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvuser=MediaWiki%20default',
550 public function getVersion() {
551 return __CLASS__ . ': $Id$';