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');
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.
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
;
55 $this->tokenFunctions
= array(
56 'rollback' => 'ApiQueryRevisions::getRollbackToken'
58 wfRunHooks('APIQueryRevisionsTokens', array(&$this->tokenFunctions
));
59 return $this->tokenFunctions
;
62 public static function getRollbackToken($pageid, $title, $rev)
65 if(!$wgUser->isAllowed('rollback'))
67 return $wgUser->editToken($title->getPrefixedText(),
71 public function execute() {
72 $limit = $startid = $endid = $start = $end = $dir = $prop = $user = $excludeuser = $expandtemplates = $section = $token = null;
73 extract($this->extractRequestParams(false));
75 // If any of those parameters are used, work in 'enumeration' mode.
76 // Enum mode can only be used when exactly one page is provided.
77 // Enumerating revisions on multiple pages make it extremely
78 // difficult to manage continuations and require additional SQL indexes
79 $enumRevMode = (!is_null($user) ||
!is_null($excludeuser) ||
!is_null($limit) ||
!is_null($startid) ||
!is_null($endid) ||
$dir === 'newer' ||
!is_null($start) ||
!is_null($end));
82 $pageSet = $this->getPageSet();
83 $pageCount = $pageSet->getGoodTitleCount();
84 $revCount = $pageSet->getRevisionCount();
86 // Optimization -- nothing to do
87 if ($revCount === 0 && $pageCount === 0)
90 if ($revCount > 0 && $enumRevMode)
91 $this->dieUsage('The revids= parameter may not be used with the list options (limit, startid, endid, dirNewer, start, end).', 'revids');
93 if ($pageCount > 1 && $enumRevMode)
94 $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');
96 $this->addTables('revision');
97 $this->addFields( Revision
::selectFields() );
99 $prop = array_flip($prop);
102 $this->fld_ids
= isset ($prop['ids']);
103 // $this->addFieldsIf('rev_text_id', $this->fld_ids); // should this be exposed?
104 $this->fld_flags
= isset ($prop['flags']);
105 $this->fld_timestamp
= isset ($prop['timestamp']);
106 $this->fld_comment
= isset ($prop['comment']);
107 $this->fld_size
= isset ($prop['size']);
108 $this->fld_user
= isset ($prop['user']);
109 $this->token
= $token;
111 if ( !is_null($this->token
) ||
( $this->fld_content
&& $this->expandTemplates
) ||
$pageCount > 0) {
112 $this->addTables( 'page' );
113 $this->addWhere('page_id=rev_page');
114 $this->addFields( Revision
::selectPageFields() );
117 if (isset ($prop['content'])) {
119 // For each page we will request, the user must have read rights for that page
120 foreach ($pageSet->getGoodTitles() as $title) {
121 if( !$title->userCanRead() )
123 'The current user is not allowed to read ' . $title->getPrefixedText(),
127 $this->addTables('text');
128 $this->addWhere('rev_text_id=old_id');
129 $this->addFields('old_id');
130 $this->addFields( Revision
::selectTextFields() );
132 $this->fld_content
= true;
134 $this->expandTemplates
= $expandtemplates;
136 $this->section
= $section;
138 $this->section
= false;
141 $userMax = ( $this->fld_content ? ApiBase
::LIMIT_SML1
: ApiBase
::LIMIT_BIG1
);
142 $botMax = ( $this->fld_content ? ApiBase
::LIMIT_SML2
: ApiBase
::LIMIT_BIG2
);
143 if( $limit == 'max' ) {
144 $limit = $this->getMain()->canApiHighLimits() ?
$botMax : $userMax;
145 $this->getResult()->addValue( 'limits', $this->getModuleName(), $limit );
150 // This is mostly to prevent parameter errors (and optimize SQL?)
151 if (!is_null($startid) && !is_null($start))
152 $this->dieUsage('start and startid cannot be used together', 'badparams');
154 if (!is_null($endid) && !is_null($end))
155 $this->dieUsage('end and endid cannot be used together', 'badparams');
157 if(!is_null($user) && !is_null( $excludeuser))
158 $this->dieUsage('user and excludeuser cannot be used together', 'badparams');
160 // This code makes an assumption that sorting by rev_id and rev_timestamp produces
161 // the same result. This way users may request revisions starting at a given time,
162 // but to page through results use the rev_id returned after each page.
163 // Switching to rev_id removes the potential problem of having more than
164 // one row with the same timestamp for the same page.
165 // The order needs to be the same as start parameter to avoid SQL filesort.
167 if (is_null($startid) && is_null($endid))
168 $this->addWhereRange('rev_timestamp', $dir, $start, $end);
170 $this->addWhereRange('rev_id', $dir, $startid, $endid);
172 // must manually initialize unset limit
175 $this->validateLimit('limit', $limit, 1, $userMax, $botMax);
177 // There is only one ID, use it
178 $this->addWhereFld('rev_page', current(array_keys($pageSet->getGoodTitles())));
180 if(!is_null($user)) {
181 $this->addWhereFld('rev_user_text', $user);
182 } elseif (!is_null( $excludeuser)) {
183 $this->addWhere('rev_user_text != ' . $this->getDB()->addQuotes($excludeuser));
186 elseif ($revCount > 0) {
187 $this->validateLimit('rev_count', $revCount, 1, $userMax, $botMax);
189 // Get all revision IDs
190 $this->addWhereFld('rev_id', array_keys($pageSet->getRevisionIDs()));
192 // assumption testing -- we should never get more then $revCount rows.
195 elseif ($pageCount > 0) {
196 // When working in multi-page non-enumeration mode,
197 // limit to the latest revision only
198 $this->addWhere('page_id=rev_page');
199 $this->addWhere('page_latest=rev_id');
200 $this->validateLimit('page_count', $pageCount, 1, $userMax, $botMax);
203 $this->addWhereFld('page_id', array_keys($pageSet->getGoodTitles()));
205 // assumption testing -- we should never get more then $pageCount rows.
208 ApiBase
:: dieDebug(__METHOD__
, 'param validation?');
210 $this->addOption('LIMIT', $limit +
1);
214 $res = $this->select(__METHOD__
);
216 $db = $this->getDB();
217 while ($row = $db->fetchObject($res)) {
219 if (++
$count > $limit) {
220 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
222 ApiBase
:: dieDebug(__METHOD__
, 'Got more rows then expected'); // bug report
223 $this->setContinueEnumParameter('startid', intval($row->rev_id
));
227 $revision = new Revision( $row );
228 $this->getResult()->addValue(
232 $revision->getPage(),
235 $this->extractRowInfo( $revision ));
237 $db->freeResult($res);
239 // Ensure that all revisions are shown as '<rev>' elements
240 $result = $this->getResult();
241 if ($result->getIsRawMode()) {
242 $data =& $result->getData();
243 foreach ($data['query']['pages'] as & $page) {
244 if (is_array($page) && array_key_exists('revisions', $page)) {
245 $result->setIndexedTagName($page['revisions'], 'rev');
251 private function extractRowInfo( $revision ) {
255 if ($this->fld_ids
) {
256 $vals['revid'] = $revision->getId();
257 // $vals['oldid'] = intval($row->rev_text_id); // todo: should this be exposed?
260 if ($this->fld_flags
&& $revision->isMinor())
263 if ($this->fld_user
) {
264 $vals['user'] = $revision->getUserText();
265 if (!$revision->getUser())
269 if ($this->fld_timestamp
) {
270 $vals['timestamp'] = wfTimestamp(TS_ISO_8601
, $revision->getTimestamp());
273 if ($this->fld_size
&& !is_null($revision->getSize())) {
274 $vals['size'] = $revision->getSize();
277 if ($this->fld_comment
) {
278 $comment = $revision->getComment();
279 if (!empty($comment))
280 $vals['comment'] = $comment;
283 if(!is_null($this->token
) ||
($this->fld_content
&& $this->expandTemplates
))
284 $title = $revision->getTitle();
286 if(!is_null($this->token
))
288 $tokenFunctions = $this->getTokenFunctions();
289 foreach($this->token
as $t)
291 $val = call_user_func($tokenFunctions[$t], $title->getArticleID(), $title, $revision);
293 $this->setWarning("Action '$t' is not allowed for the current user");
295 $vals[$t . 'token'] = $val;
299 if ($this->fld_content
) {
301 $text = $revision->getText();
302 # Expand templates after getting section content because
303 # template-added sections don't count and Parser::preprocess()
304 # will have less input
305 if ($this->section
!== false) {
306 $text = $wgParser->getSection( $text, $this->section
, false);
308 $this->dieUsage("There is no section {$this->section} in r".$revision->getId(), 'nosuchsection');
310 if ($this->expandTemplates
) {
311 $text = $wgParser->preprocess( $text, $title, new ParserOptions() );
313 ApiResult
:: setContent($vals, $text);
318 public function getAllowedParams() {
321 ApiBase
:: PARAM_ISMULTI
=> true,
322 ApiBase
:: PARAM_DFLT
=> 'ids|timestamp|flags|comment|user',
323 ApiBase
:: PARAM_TYPE
=> array (
334 ApiBase
:: PARAM_TYPE
=> 'limit',
335 ApiBase
:: PARAM_MIN
=> 1,
336 ApiBase
:: PARAM_MAX
=> ApiBase
:: LIMIT_BIG1
,
337 ApiBase
:: PARAM_MAX2
=> ApiBase
:: LIMIT_BIG2
340 ApiBase
:: PARAM_TYPE
=> 'integer'
343 ApiBase
:: PARAM_TYPE
=> 'integer'
346 ApiBase
:: PARAM_TYPE
=> 'timestamp'
349 ApiBase
:: PARAM_TYPE
=> 'timestamp'
352 ApiBase
:: PARAM_DFLT
=> 'older',
353 ApiBase
:: PARAM_TYPE
=> array (
359 ApiBase
:: PARAM_TYPE
=> 'user'
361 'excludeuser' => array(
362 ApiBase
:: PARAM_TYPE
=> 'user'
365 'expandtemplates' => false,
367 ApiBase
:: PARAM_TYPE
=> 'integer'
370 ApiBase
:: PARAM_TYPE
=> array_keys($this->getTokenFunctions()),
371 ApiBase
:: PARAM_ISMULTI
=> true
376 public function getParamDescription() {
378 'prop' => 'Which properties to get for each revision.',
379 'limit' => 'limit how many revisions will be returned (enum)',
380 'startid' => 'from which revision id to start enumeration (enum)',
381 'endid' => 'stop revision enumeration on this revid (enum)',
382 'start' => 'from which revision timestamp to start enumeration (enum)',
383 'end' => 'enumerate up to this timestamp (enum)',
384 'dir' => 'direction of enumeration - towards "newer" or "older" revisions (enum)',
385 'user' => 'only include revisions made by user',
386 'excludeuser' => 'exclude revisions made by user',
387 'expandtemplates' => 'expand templates in revision content',
388 'section' => 'only retrieve the content of this section',
389 'token' => 'Which tokens to obtain for each revision',
393 public function getDescription() {
395 'Get revision information.',
396 'This module may be used in several ways:',
397 ' 1) Get data about a set of pages (last revision), by setting titles or pageids parameter.',
398 ' 2) Get revisions for one given page, by using titles/pageids with start/end/limit params.',
399 ' 3) Get data about a set of revisions by setting their IDs with revids parameter.',
400 'All parameters marked as (enum) may only be used with a single page (#2).'
404 protected function getExamples() {
406 'Get data with content for the last revision of titles "API" and "Main Page":',
407 ' api.php?action=query&prop=revisions&titles=API|Main%20Page&rvprop=timestamp|user|comment|content',
408 'Get last 5 revisions of the "Main Page":',
409 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment',
410 'Get first 5 revisions of the "Main Page":',
411 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer',
412 'Get first 5 revisions of the "Main Page" made after 2006-05-01:',
413 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer&rvstart=20060501000000',
414 'Get first 5 revisions of the "Main Page" that were not made made by anonymous user "127.0.0.1"',
415 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1',
416 'Get first 5 revisions of the "Main Page" that were made by the user "MediaWiki default"',
417 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvuser=MediaWiki%20default',
421 public function getVersion() {
422 return __CLASS__
. ': $Id$';