Fix for r47482: put the RELEASE-NOTES entry in the "bug fixes" section and not the...
[mediawiki.git] / includes / api / ApiQueryRevisions.php
blobd3e2125d82f2f4f0a6a9d1d6b43a2eeed336ca51
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;
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 $this->addTables('revision');
104 $this->addFields(Revision::selectFields());
105 $this->addTables('page');
106 $this->addWhere('page_id = rev_page');
108 $prop = array_flip($params['prop']);
110 // Optional fields
111 $this->fld_ids = isset ($prop['ids']);
112 // $this->addFieldsIf('rev_text_id', $this->fld_ids); // should this be exposed?
113 $this->fld_flags = isset ($prop['flags']);
114 $this->fld_timestamp = isset ($prop['timestamp']);
115 $this->fld_comment = isset ($prop['comment']);
116 $this->fld_size = isset ($prop['size']);
117 $this->fld_user = isset ($prop['user']);
118 $this->token = $params['token'];
120 if ( !is_null($this->token) || $pageCount > 0) {
121 $this->addFields( Revision::selectPageFields() );
124 if (isset ($prop['content'])) {
126 // For each page we will request, the user must have read rights for that page
127 foreach ($pageSet->getGoodTitles() as $title) {
128 if( !$title->userCanRead() )
129 $this->dieUsage(
130 'The current user is not allowed to read ' . $title->getPrefixedText(),
131 'accessdenied');
134 $this->addTables('text');
135 $this->addWhere('rev_text_id=old_id');
136 $this->addFields('old_id');
137 $this->addFields(Revision::selectTextFields());
139 $this->fld_content = true;
141 $this->expandTemplates = $params['expandtemplates'];
142 $this->generateXML = $params['generatexml'];
143 if(isset($params['section']))
144 $this->section = $params['section'];
145 else
146 $this->section = false;
149 $userMax = ( $this->fld_content ? ApiBase::LIMIT_SML1 : ApiBase::LIMIT_BIG1 );
150 $botMax = ( $this->fld_content ? ApiBase::LIMIT_SML2 : ApiBase::LIMIT_BIG2 );
151 $limit = $params['limit'];
152 if( $limit == 'max' ) {
153 $limit = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
154 $this->getResult()->addValue( 'limits', $this->getModuleName(), $limit );
157 if ($enumRevMode) {
159 // This is mostly to prevent parameter errors (and optimize SQL?)
160 if (!is_null($params['startid']) && !is_null($params['start']))
161 $this->dieUsage('start and startid cannot be used together', 'badparams');
163 if (!is_null($params['endid']) && !is_null($params['end']))
164 $this->dieUsage('end and endid cannot be used together', 'badparams');
166 if(!is_null($params['user']) && !is_null($params['excludeuser']))
167 $this->dieUsage('user and excludeuser cannot be used together', 'badparams');
169 // This code makes an assumption that sorting by rev_id and rev_timestamp produces
170 // the same result. This way users may request revisions starting at a given time,
171 // but to page through results use the rev_id returned after each page.
172 // Switching to rev_id removes the potential problem of having more than
173 // one row with the same timestamp for the same page.
174 // The order needs to be the same as start parameter to avoid SQL filesort.
176 if (is_null($params['startid']) && is_null($params['endid']))
177 $this->addWhereRange('rev_timestamp', $params['dir'],
178 $params['start'], $params['end']);
179 else {
180 $this->addWhereRange('rev_id', $params['dir'],
181 $params['startid'], $params['endid']);
182 // One of start and end can be set
183 // If neither is set, this does nothing
184 $this->addWhereRange('rev_timestamp', $params['dir'],
185 $params['start'], $params['end'], false);
188 // must manually initialize unset limit
189 if (is_null($limit))
190 $limit = 10;
191 $this->validateLimit('limit', $limit, 1, $userMax, $botMax);
193 // There is only one ID, use it
194 $this->addWhereFld('rev_page', current(array_keys($pageSet->getGoodTitles())));
196 if(!is_null($params['user'])) {
197 $this->addWhereFld('rev_user_text', $params['user']);
198 } elseif (!is_null($params['excludeuser'])) {
199 $this->addWhere('rev_user_text != ' .
200 $this->getDB()->addQuotes($params['excludeuser']));
202 if(!is_null($params['user']) || !is_null($params['excludeuser'])) {
203 // Paranoia: avoid brute force searches (bug 17342)
204 $this->addWhere('rev_deleted & ' . Revision::DELETED_USER . ' = 0');
207 elseif ($revCount > 0) {
208 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
209 $revs = $pageSet->getRevisionIDs();
210 if(self::truncateArray($revs, $max))
211 $this->setWarning("Too many values supplied for parameter 'revids': the limit is $max");
213 // Get all revision IDs
214 $this->addWhereFld('rev_id', array_keys($revs));
216 if(!is_null($params['continue']))
217 $this->addWhere("rev_id >= '" . intval($params['continue']) . "'");
218 $this->addOption('ORDER BY', 'rev_id');
220 // assumption testing -- we should never get more then $revCount rows.
221 $limit = $revCount;
223 elseif ($pageCount > 0) {
224 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
225 $titles = $pageSet->getGoodTitles();
226 if(self::truncateArray($titles, $max))
227 $this->setWarning("Too many values supplied for parameter 'titles': the limit is $max");
229 // When working in multi-page non-enumeration mode,
230 // limit to the latest revision only
231 $this->addWhere('page_id=rev_page');
232 $this->addWhere('page_latest=rev_id');
234 // Get all page IDs
235 $this->addWhereFld('page_id', array_keys($titles));
237 if(!is_null($params['continue']))
239 $cont = explode('|', $params['continue']);
240 if(count($cont) != 2)
241 $this->dieUsage("Invalid continue param. You should pass the original " .
242 "value returned by the previous query", "_badcontinue");
243 $pageid = intval($cont[0]);
244 $revid = intval($cont[1]);
245 $this->addWhere("rev_page > '$pageid' OR " .
246 "(rev_page = '$pageid' AND " .
247 "rev_id >= '$revid')");
249 $this->addOption('ORDER BY', 'rev_page, rev_id');
251 // assumption testing -- we should never get more then $pageCount rows.
252 $limit = $pageCount;
253 } else
254 ApiBase :: dieDebug(__METHOD__, 'param validation?');
256 $this->addOption('LIMIT', $limit +1);
258 $data = array ();
259 $count = 0;
260 $res = $this->select(__METHOD__);
262 $db = $this->getDB();
263 while ($row = $db->fetchObject($res)) {
265 if (++ $count > $limit) {
266 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
267 if (!$enumRevMode)
268 ApiBase :: dieDebug(__METHOD__, 'Got more rows then expected'); // bug report
269 $this->setContinueEnumParameter('startid', intval($row->rev_id));
270 break;
272 $revision = new Revision( $row );
274 $fit = $this->addPageSubItem($revision->getPage(), $this->extractRowInfo($revision), 'rev');
275 if(!$fit)
277 if($enumRevMode)
278 $this->setContinueEnumParameter('startid', intval($row->rev_id));
279 else if($revCount > 0)
280 $this->setContinueEnumParameter('continue', intval($row->rev_id));
281 else
282 $this->setContinueEnumParameter('continue', intval($row->rev_page) .
283 '|' . intval($row->rev_id));
284 break;
287 $db->freeResult($res);
290 private function extractRowInfo( $revision ) {
292 $vals = array ();
294 if ($this->fld_ids) {
295 $vals['revid'] = $revision->getId();
296 // $vals['oldid'] = intval($row->rev_text_id); // todo: should this be exposed?
299 if ($this->fld_flags && $revision->isMinor())
300 $vals['minor'] = '';
302 if ($this->fld_user) {
303 if ($revision->isDeleted(Revision::DELETED_USER)) {
304 $vals['userhidden'] = '';
305 } else {
306 $vals['user'] = $revision->getUserText();
307 if (!$revision->getUser())
308 $vals['anon'] = '';
312 if ($this->fld_timestamp) {
313 $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $revision->getTimestamp());
316 if ($this->fld_size && !is_null($revision->getSize())) {
317 $vals['size'] = $revision->getSize();
320 if ($this->fld_comment) {
321 if ($revision->isDeleted(Revision::DELETED_COMMENT)) {
322 $vals['commenthidden'] = '';
323 } else {
324 $comment = $revision->getComment();
325 if (strval($comment) !== '')
326 $vals['comment'] = $comment;
330 if(!is_null($this->token) || ($this->fld_content && $this->expandTemplates))
331 $title = $revision->getTitle();
333 if(!is_null($this->token))
335 $tokenFunctions = $this->getTokenFunctions();
336 foreach($this->token as $t)
338 $val = call_user_func($tokenFunctions[$t], $title->getArticleID(), $title, $revision);
339 if($val === false)
340 $this->setWarning("Action '$t' is not allowed for the current user");
341 else
342 $vals[$t . 'token'] = $val;
346 if ($this->fld_content && !$revision->isDeleted(Revision::DELETED_TEXT)) {
347 global $wgParser;
348 $text = $revision->getText();
349 # Expand templates after getting section content because
350 # template-added sections don't count and Parser::preprocess()
351 # will have less input
352 if ($this->section !== false) {
353 $text = $wgParser->getSection( $text, $this->section, false);
354 if($text === false)
355 $this->dieUsage("There is no section {$this->section} in r".$revision->getId(), 'nosuchsection');
357 if ($this->generateXML) {
358 $wgParser->startExternalParse( $title, new ParserOptions(), OT_PREPROCESS );
359 $dom = $wgParser->preprocessToDom( $text );
360 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
361 $xml = $dom->saveXML();
362 } else {
363 $xml = $dom->__toString();
365 $vals['parsetree'] = $xml;
368 if ($this->expandTemplates) {
369 $text = $wgParser->preprocess( $text, $title, new ParserOptions() );
371 ApiResult :: setContent($vals, $text);
372 } else if ($this->fld_content) {
373 $vals['texthidden'] = '';
375 return $vals;
378 public function getAllowedParams() {
379 return array (
380 'prop' => array (
381 ApiBase :: PARAM_ISMULTI => true,
382 ApiBase :: PARAM_DFLT => 'ids|timestamp|flags|comment|user',
383 ApiBase :: PARAM_TYPE => array (
384 'ids',
385 'flags',
386 'timestamp',
387 'user',
388 'size',
389 'comment',
390 'content',
393 'limit' => array (
394 ApiBase :: PARAM_TYPE => 'limit',
395 ApiBase :: PARAM_MIN => 1,
396 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
397 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
399 'startid' => array (
400 ApiBase :: PARAM_TYPE => 'integer'
402 'endid' => array (
403 ApiBase :: PARAM_TYPE => 'integer'
405 'start' => array (
406 ApiBase :: PARAM_TYPE => 'timestamp'
408 'end' => array (
409 ApiBase :: PARAM_TYPE => 'timestamp'
411 'dir' => array (
412 ApiBase :: PARAM_DFLT => 'older',
413 ApiBase :: PARAM_TYPE => array (
414 'newer',
415 'older'
418 'user' => array(
419 ApiBase :: PARAM_TYPE => 'user'
421 'excludeuser' => array(
422 ApiBase :: PARAM_TYPE => 'user'
424 'expandtemplates' => false,
425 'generatexml' => false,
426 'section' => null,
427 'token' => array(
428 ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions()),
429 ApiBase :: PARAM_ISMULTI => true
431 'continue' => null,
435 public function getParamDescription() {
436 return array (
437 'prop' => 'Which properties to get for each revision.',
438 'limit' => 'limit how many revisions will be returned (enum)',
439 'startid' => 'from which revision id to start enumeration (enum)',
440 'endid' => 'stop revision enumeration on this revid (enum)',
441 'start' => 'from which revision timestamp to start enumeration (enum)',
442 'end' => 'enumerate up to this timestamp (enum)',
443 'dir' => 'direction of enumeration - towards "newer" or "older" revisions (enum)',
444 'user' => 'only include revisions made by user',
445 'excludeuser' => 'exclude revisions made by user',
446 'expandtemplates' => 'expand templates in revision content',
447 'generatexml' => 'generate XML parse tree for revision content',
448 'section' => 'only retrieve the content of this section',
449 'token' => 'Which tokens to obtain for each revision',
450 'continue' => 'When more results are available, use this to continue',
454 public function getDescription() {
455 return array (
456 'Get revision information.',
457 'This module may be used in several ways:',
458 ' 1) Get data about a set of pages (last revision), by setting titles or pageids parameter.',
459 ' 2) Get revisions for one given page, by using titles/pageids with start/end/limit params.',
460 ' 3) Get data about a set of revisions by setting their IDs with revids parameter.',
461 'All parameters marked as (enum) may only be used with a single page (#2).'
465 protected function getExamples() {
466 return array (
467 'Get data with content for the last revision of titles "API" and "Main Page":',
468 ' api.php?action=query&prop=revisions&titles=API|Main%20Page&rvprop=timestamp|user|comment|content',
469 'Get last 5 revisions of the "Main Page":',
470 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment',
471 'Get first 5 revisions of the "Main Page":',
472 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer',
473 'Get first 5 revisions of the "Main Page" made after 2006-05-01:',
474 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer&rvstart=20060501000000',
475 'Get first 5 revisions of the "Main Page" that were not made made by anonymous user "127.0.0.1"',
476 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1',
477 'Get first 5 revisions of the "Main Page" that were made by the user "MediaWiki default"',
478 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvuser=MediaWiki%20default',
482 public function getVersion() {
483 return __CLASS__ . ': $Id$';