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
;
56 // If we're in JSON callback mode, no tokens can be obtained
57 if(!is_null($this->getMain()->getRequest()->getVal('callback')))
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)
70 if(!$wgUser->isAllowed('rollback'))
72 return $wgUser->editToken(array($title->getPrefixedText(),
73 $rev->getUserText()));
76 public function execute() {
77 $limit = $startid = $endid = $start = $end = $dir = $prop = $user = $excludeuser = $expandtemplates = $section = $token = null;
78 extract($this->extractRequestParams(false));
80 // If any of those parameters are used, work in 'enumeration' mode.
81 // Enum mode can only be used when exactly one page is provided.
82 // Enumerating revisions on multiple pages make it extremely
83 // difficult to manage continuations and require additional SQL indexes
84 $enumRevMode = (!is_null($user) ||
!is_null($excludeuser) ||
!is_null($limit) ||
!is_null($startid) ||
!is_null($endid) ||
$dir === 'newer' ||
!is_null($start) ||
!is_null($end));
87 $pageSet = $this->getPageSet();
88 $pageCount = $pageSet->getGoodTitleCount();
89 $revCount = $pageSet->getRevisionCount();
91 // Optimization -- nothing to do
92 if ($revCount === 0 && $pageCount === 0)
95 if ($revCount > 0 && $enumRevMode)
96 $this->dieUsage('The revids= parameter may not be used with the list options (limit, startid, endid, dirNewer, start, end).', 'revids');
98 if ($pageCount > 1 && $enumRevMode)
99 $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');
101 $this->addTables('revision');
102 $this->addFields( Revision
::selectFields() );
104 $prop = array_flip($prop);
107 $this->fld_ids
= isset ($prop['ids']);
108 // $this->addFieldsIf('rev_text_id', $this->fld_ids); // should this be exposed?
109 $this->fld_flags
= isset ($prop['flags']);
110 $this->fld_timestamp
= isset ($prop['timestamp']);
111 $this->fld_comment
= isset ($prop['comment']);
112 $this->fld_size
= isset ($prop['size']);
113 $this->fld_user
= isset ($prop['user']);
114 $this->token
= $token;
116 if ( !is_null($this->token
) ||
( $this->fld_content
&& $this->expandTemplates
) ||
$pageCount > 0) {
117 $this->addTables( 'page' );
118 $this->addWhere('page_id=rev_page');
119 $this->addFields( Revision
::selectPageFields() );
122 if (isset ($prop['content'])) {
124 // For each page we will request, the user must have read rights for that page
125 foreach ($pageSet->getGoodTitles() as $title) {
126 if( !$title->userCanRead() )
128 'The current user is not allowed to read ' . $title->getPrefixedText(),
132 $this->addTables('text');
133 $this->addWhere('rev_text_id=old_id');
134 $this->addFields('old_id');
135 $this->addFields( Revision
::selectTextFields() );
137 $this->fld_content
= true;
139 $this->expandTemplates
= $expandtemplates;
141 $this->section
= $section;
143 $this->section
= false;
146 $userMax = ( $this->fld_content ? ApiBase
::LIMIT_SML1
: ApiBase
::LIMIT_BIG1
);
147 $botMax = ( $this->fld_content ? ApiBase
::LIMIT_SML2
: ApiBase
::LIMIT_BIG2
);
148 if( $limit == 'max' ) {
149 $limit = $this->getMain()->canApiHighLimits() ?
$botMax : $userMax;
150 $this->getResult()->addValue( 'limits', $this->getModuleName(), $limit );
155 // This is mostly to prevent parameter errors (and optimize SQL?)
156 if (!is_null($startid) && !is_null($start))
157 $this->dieUsage('start and startid cannot be used together', 'badparams');
159 if (!is_null($endid) && !is_null($end))
160 $this->dieUsage('end and endid cannot be used together', 'badparams');
162 if(!is_null($user) && !is_null( $excludeuser))
163 $this->dieUsage('user and excludeuser cannot be used together', 'badparams');
165 // This code makes an assumption that sorting by rev_id and rev_timestamp produces
166 // the same result. This way users may request revisions starting at a given time,
167 // but to page through results use the rev_id returned after each page.
168 // Switching to rev_id removes the potential problem of having more than
169 // one row with the same timestamp for the same page.
170 // The order needs to be the same as start parameter to avoid SQL filesort.
172 if (is_null($startid) && is_null($endid))
173 $this->addWhereRange('rev_timestamp', $dir, $start, $end);
175 $this->addWhereRange('rev_id', $dir, $startid, $endid);
177 // must manually initialize unset limit
180 $this->validateLimit('limit', $limit, 1, $userMax, $botMax);
182 // There is only one ID, use it
183 $this->addWhereFld('rev_page', current(array_keys($pageSet->getGoodTitles())));
185 if(!is_null($user)) {
186 $this->addWhereFld('rev_user_text', $user);
187 } elseif (!is_null( $excludeuser)) {
188 $this->addWhere('rev_user_text != ' . $this->getDB()->addQuotes($excludeuser));
191 elseif ($revCount > 0) {
192 $this->validateLimit('rev_count', $revCount, 1, $userMax, $botMax);
194 // Get all revision IDs
195 $this->addWhereFld('rev_id', array_keys($pageSet->getRevisionIDs()));
197 // assumption testing -- we should never get more then $revCount rows.
200 elseif ($pageCount > 0) {
201 // When working in multi-page non-enumeration mode,
202 // limit to the latest revision only
203 $this->addWhere('page_id=rev_page');
204 $this->addWhere('page_latest=rev_id');
205 $this->validateLimit('page_count', $pageCount, 1, $userMax, $botMax);
208 $this->addWhereFld('page_id', array_keys($pageSet->getGoodTitles()));
210 // assumption testing -- we should never get more then $pageCount rows.
213 ApiBase
:: dieDebug(__METHOD__
, 'param validation?');
215 $this->addOption('LIMIT', $limit +
1);
219 $res = $this->select(__METHOD__
);
221 $db = $this->getDB();
222 while ($row = $db->fetchObject($res)) {
224 if (++
$count > $limit) {
225 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
227 ApiBase
:: dieDebug(__METHOD__
, 'Got more rows then expected'); // bug report
228 $this->setContinueEnumParameter('startid', intval($row->rev_id
));
232 $revision = new Revision( $row );
233 $this->getResult()->addValue(
237 $revision->getPage(),
240 $this->extractRowInfo( $revision ));
242 $db->freeResult($res);
244 // Ensure that all revisions are shown as '<rev>' elements
245 $result = $this->getResult();
246 if ($result->getIsRawMode()) {
247 $data =& $result->getData();
248 foreach ($data['query']['pages'] as & $page) {
249 if (is_array($page) && array_key_exists('revisions', $page)) {
250 $result->setIndexedTagName($page['revisions'], 'rev');
256 private function extractRowInfo( $revision ) {
260 if ($this->fld_ids
) {
261 $vals['revid'] = $revision->getId();
262 // $vals['oldid'] = intval($row->rev_text_id); // todo: should this be exposed?
265 if ($this->fld_flags
&& $revision->isMinor())
268 if ($this->fld_user
) {
269 $vals['user'] = $revision->getUserText();
270 if (!$revision->getUser())
274 if ($this->fld_timestamp
) {
275 $vals['timestamp'] = wfTimestamp(TS_ISO_8601
, $revision->getTimestamp());
278 if ($this->fld_size
&& !is_null($revision->getSize())) {
279 $vals['size'] = $revision->getSize();
282 if ($this->fld_comment
) {
283 $comment = $revision->getComment();
284 if (!empty($comment))
285 $vals['comment'] = $comment;
288 if(!is_null($this->token
) ||
($this->fld_content
&& $this->expandTemplates
))
289 $title = $revision->getTitle();
291 if(!is_null($this->token
))
293 $tokenFunctions = $this->getTokenFunctions();
294 foreach($this->token
as $t)
296 $val = call_user_func($tokenFunctions[$t], $title->getArticleID(), $title, $revision);
298 $this->setWarning("Action '$t' is not allowed for the current user");
300 $vals[$t . 'token'] = $val;
304 if ($this->fld_content
) {
306 $text = $revision->getText();
307 # Expand templates after getting section content because
308 # template-added sections don't count and Parser::preprocess()
309 # will have less input
310 if ($this->section
!== false) {
311 $text = $wgParser->getSection( $text, $this->section
, false);
313 $this->dieUsage("There is no section {$this->section} in r".$revision->getId(), 'nosuchsection');
315 if ($this->expandTemplates
) {
316 $text = $wgParser->preprocess( $text, $title, new ParserOptions() );
318 ApiResult
:: setContent($vals, $text);
323 public function getAllowedParams() {
326 ApiBase
:: PARAM_ISMULTI
=> true,
327 ApiBase
:: PARAM_DFLT
=> 'ids|timestamp|flags|comment|user',
328 ApiBase
:: PARAM_TYPE
=> array (
339 ApiBase
:: PARAM_TYPE
=> 'limit',
340 ApiBase
:: PARAM_MIN
=> 1,
341 ApiBase
:: PARAM_MAX
=> ApiBase
:: LIMIT_BIG1
,
342 ApiBase
:: PARAM_MAX2
=> ApiBase
:: LIMIT_BIG2
345 ApiBase
:: PARAM_TYPE
=> 'integer'
348 ApiBase
:: PARAM_TYPE
=> 'integer'
351 ApiBase
:: PARAM_TYPE
=> 'timestamp'
354 ApiBase
:: PARAM_TYPE
=> 'timestamp'
357 ApiBase
:: PARAM_DFLT
=> 'older',
358 ApiBase
:: PARAM_TYPE
=> array (
364 ApiBase
:: PARAM_TYPE
=> 'user'
366 'excludeuser' => array(
367 ApiBase
:: PARAM_TYPE
=> 'user'
370 'expandtemplates' => false,
372 ApiBase
:: PARAM_TYPE
=> 'integer'
375 ApiBase
:: PARAM_TYPE
=> array_keys($this->getTokenFunctions()),
376 ApiBase
:: PARAM_ISMULTI
=> true
381 public function getParamDescription() {
383 'prop' => 'Which properties to get for each revision.',
384 'limit' => 'limit how many revisions will be returned (enum)',
385 'startid' => 'from which revision id to start enumeration (enum)',
386 'endid' => 'stop revision enumeration on this revid (enum)',
387 'start' => 'from which revision timestamp to start enumeration (enum)',
388 'end' => 'enumerate up to this timestamp (enum)',
389 'dir' => 'direction of enumeration - towards "newer" or "older" revisions (enum)',
390 'user' => 'only include revisions made by user',
391 'excludeuser' => 'exclude revisions made by user',
392 'expandtemplates' => 'expand templates in revision content',
393 'section' => 'only retrieve the content of this section',
394 'token' => 'Which tokens to obtain for each revision',
398 public function getDescription() {
400 'Get revision information.',
401 'This module may be used in several ways:',
402 ' 1) Get data about a set of pages (last revision), by setting titles or pageids parameter.',
403 ' 2) Get revisions for one given page, by using titles/pageids with start/end/limit params.',
404 ' 3) Get data about a set of revisions by setting their IDs with revids parameter.',
405 'All parameters marked as (enum) may only be used with a single page (#2).'
409 protected function getExamples() {
411 'Get data with content for the last revision of titles "API" and "Main Page":',
412 ' api.php?action=query&prop=revisions&titles=API|Main%20Page&rvprop=timestamp|user|comment|content',
413 'Get last 5 revisions of the "Main Page":',
414 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment',
415 'Get first 5 revisions of the "Main Page":',
416 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer',
417 'Get first 5 revisions of the "Main Page" made after 2006-05-01:',
418 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer&rvstart=20060501000000',
419 'Get first 5 revisions of the "Main Page" that were not made made by anonymous user "127.0.0.1"',
420 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1',
421 'Get first 5 revisions of the "Main Page" that were made by the user "MediaWiki default"',
422 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvuser=MediaWiki%20default',
426 public function getVersion() {
427 return __CLASS__
. ': $Id$';