API: (bug 16516) Made rvsection=T-2 work rather than being interpreted as rvsection=0
[lhc/web/wiklou.git] / includes / api / ApiQueryRevisions.php
1 <?php
2
3 /*
4 * Created on Sep 7, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
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.
14 *
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.
19 *
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
24 */
25
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiQueryBase.php');
29 }
30
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.
35 *
36 * @ingroup API
37 */
38 class ApiQueryRevisions extends ApiQueryBase {
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, $fld_size = false,
45 $fld_comment = false, $fld_user = false, $fld_content = false;
46
47 protected function getTokenFunctions() {
48 // tokenname => function
49 // function prototype is func($pageid, $title, $rev)
50 // should return token or false
51
52 // Don't call the hooks twice
53 if(isset($this->tokenFunctions))
54 return $this->tokenFunctions;
55
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();
59
60 $this->tokenFunctions = array(
61 'rollback' => array( 'ApiQueryRevisions', 'getRollbackToken' )
62 );
63 wfRunHooks('APIQueryRevisionsTokens', array(&$this->tokenFunctions));
64 return $this->tokenFunctions;
65 }
66
67 public static function getRollbackToken($pageid, $title, $rev)
68 {
69 global $wgUser;
70 if(!$wgUser->isAllowed('rollback'))
71 return false;
72 return $wgUser->editToken(array($title->getPrefixedText(),
73 $rev->getUserText()));
74 }
75
76 public function execute() {
77 $limit = $startid = $endid = $start = $end = $dir = $prop = $user = $excludeuser = $expandtemplates = $generatexml = $section = $token = null;
78 extract($this->extractRequestParams(false));
79
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));
85
86
87 $pageSet = $this->getPageSet();
88 $pageCount = $pageSet->getGoodTitleCount();
89 $revCount = $pageSet->getRevisionCount();
90
91 // Optimization -- nothing to do
92 if ($revCount === 0 && $pageCount === 0)
93 return;
94
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');
97
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');
100
101 $this->addTables('revision');
102 $this->addFields( Revision::selectFields() );
103 $this->addTables( 'page' );
104 $this->addWhere('page_id = rev_page');
105
106 $prop = array_flip($prop);
107
108 // Optional fields
109 $this->fld_ids = isset ($prop['ids']);
110 // $this->addFieldsIf('rev_text_id', $this->fld_ids); // should this be exposed?
111 $this->fld_flags = isset ($prop['flags']);
112 $this->fld_timestamp = isset ($prop['timestamp']);
113 $this->fld_comment = isset ($prop['comment']);
114 $this->fld_size = isset ($prop['size']);
115 $this->fld_user = isset ($prop['user']);
116 $this->token = $token;
117
118 if ( !is_null($this->token) || $pageCount > 0) {
119 $this->addFields( Revision::selectPageFields() );
120 }
121
122 if (isset ($prop['content'])) {
123
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() )
127 $this->dieUsage(
128 'The current user is not allowed to read ' . $title->getPrefixedText(),
129 'accessdenied');
130 }
131
132 $this->addTables('text');
133 $this->addWhere('rev_text_id=old_id');
134 $this->addFields('old_id');
135 $this->addFields( Revision::selectTextFields() );
136
137 $this->fld_content = true;
138
139 $this->expandTemplates = $expandtemplates;
140 $this->generateXML = $generatexml;
141 if(isset($section))
142 $this->section = $section;
143 else
144 $this->section = false;
145 }
146
147 $userMax = ( $this->fld_content ? ApiBase::LIMIT_SML1 : ApiBase::LIMIT_BIG1 );
148 $botMax = ( $this->fld_content ? ApiBase::LIMIT_SML2 : ApiBase::LIMIT_BIG2 );
149 if( $limit == 'max' ) {
150 $limit = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
151 $this->getResult()->addValue( 'limits', $this->getModuleName(), $limit );
152 }
153
154 if ($enumRevMode) {
155
156 // This is mostly to prevent parameter errors (and optimize SQL?)
157 if (!is_null($startid) && !is_null($start))
158 $this->dieUsage('start and startid cannot be used together', 'badparams');
159
160 if (!is_null($endid) && !is_null($end))
161 $this->dieUsage('end and endid cannot be used together', 'badparams');
162
163 if(!is_null($user) && !is_null( $excludeuser))
164 $this->dieUsage('user and excludeuser cannot be used together', 'badparams');
165
166 // This code makes an assumption that sorting by rev_id and rev_timestamp produces
167 // the same result. This way users may request revisions starting at a given time,
168 // but to page through results use the rev_id returned after each page.
169 // Switching to rev_id removes the potential problem of having more than
170 // one row with the same timestamp for the same page.
171 // The order needs to be the same as start parameter to avoid SQL filesort.
172
173 if (is_null($startid) && is_null($endid))
174 $this->addWhereRange('rev_timestamp', $dir, $start, $end);
175 else
176 $this->addWhereRange('rev_id', $dir, $startid, $endid);
177
178 // must manually initialize unset limit
179 if (is_null($limit))
180 $limit = 10;
181 $this->validateLimit('limit', $limit, 1, $userMax, $botMax);
182
183 // There is only one ID, use it
184 $this->addWhereFld('rev_page', current(array_keys($pageSet->getGoodTitles())));
185
186 if(!is_null($user)) {
187 $this->addWhereFld('rev_user_text', $user);
188 } elseif (!is_null( $excludeuser)) {
189 $this->addWhere('rev_user_text != ' . $this->getDB()->addQuotes($excludeuser));
190 }
191 }
192 elseif ($revCount > 0) {
193 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
194 $revs = $pageSet->getRevisionIDs();
195 if(self::truncateArray($revs, $max))
196 $this->setWarning("Too many values supplied for parameter 'revids': the limit is $max");
197
198 // Get all revision IDs
199 $this->addWhereFld('rev_id', array_keys($revs));
200
201 // assumption testing -- we should never get more then $revCount rows.
202 $limit = $revCount;
203 }
204 elseif ($pageCount > 0) {
205 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
206 $titles = $pageSet->getGoodTitles();
207 if(self::truncateArray($titles, $max))
208 $this->setWarning("Too many values supplied for parameter 'titles': the limit is $max");
209
210 // When working in multi-page non-enumeration mode,
211 // limit to the latest revision only
212 $this->addWhere('page_id=rev_page');
213 $this->addWhere('page_latest=rev_id');
214
215 // Get all page IDs
216 $this->addWhereFld('page_id', array_keys($titles));
217
218 // assumption testing -- we should never get more then $pageCount rows.
219 $limit = $pageCount;
220 } else
221 ApiBase :: dieDebug(__METHOD__, 'param validation?');
222
223 $this->addOption('LIMIT', $limit +1);
224
225 $data = array ();
226 $count = 0;
227 $res = $this->select(__METHOD__);
228
229 $db = $this->getDB();
230 while ($row = $db->fetchObject($res)) {
231
232 if (++ $count > $limit) {
233 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
234 if (!$enumRevMode)
235 ApiBase :: dieDebug(__METHOD__, 'Got more rows then expected'); // bug report
236 $this->setContinueEnumParameter('startid', intval($row->rev_id));
237 break;
238 }
239
240 $revision = new Revision( $row );
241 $this->getResult()->addValue(
242 array (
243 'query',
244 'pages',
245 $revision->getPage(),
246 'revisions'),
247 null,
248 $this->extractRowInfo( $revision ));
249 }
250 $db->freeResult($res);
251
252 // Ensure that all revisions are shown as '<rev>' elements
253 $result = $this->getResult();
254 if ($result->getIsRawMode()) {
255 $data =& $result->getData();
256 foreach ($data['query']['pages'] as & $page) {
257 if (is_array($page) && array_key_exists('revisions', $page)) {
258 $result->setIndexedTagName($page['revisions'], 'rev');
259 }
260 }
261 }
262 }
263
264 private function extractRowInfo( $revision ) {
265
266 $vals = array ();
267
268 if ($this->fld_ids) {
269 $vals['revid'] = $revision->getId();
270 // $vals['oldid'] = intval($row->rev_text_id); // todo: should this be exposed?
271 }
272
273 if ($this->fld_flags && $revision->isMinor())
274 $vals['minor'] = '';
275
276 if ($this->fld_user) {
277 $vals['user'] = $revision->getUserText();
278 if (!$revision->getUser())
279 $vals['anon'] = '';
280 }
281
282 if ($this->fld_timestamp) {
283 $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $revision->getTimestamp());
284 }
285
286 if ($this->fld_size && !is_null($revision->getSize())) {
287 $vals['size'] = $revision->getSize();
288 }
289
290 if ($this->fld_comment) {
291 $comment = $revision->getComment();
292 if (strval($comment) !== '')
293 $vals['comment'] = $comment;
294 }
295
296 if(!is_null($this->token) || ($this->fld_content && $this->expandTemplates))
297 $title = $revision->getTitle();
298
299 if(!is_null($this->token))
300 {
301 $tokenFunctions = $this->getTokenFunctions();
302 foreach($this->token as $t)
303 {
304 $val = call_user_func($tokenFunctions[$t], $title->getArticleID(), $title, $revision);
305 if($val === false)
306 $this->setWarning("Action '$t' is not allowed for the current user");
307 else
308 $vals[$t . 'token'] = $val;
309 }
310 }
311
312 if ($this->fld_content) {
313 global $wgParser;
314 $text = $revision->getText();
315 # Expand templates after getting section content because
316 # template-added sections don't count and Parser::preprocess()
317 # will have less input
318 if ($this->section !== false) {
319 $text = $wgParser->getSection( $text, $this->section, false);
320 if($text === false)
321 $this->dieUsage("There is no section {$this->section} in r".$revision->getId(), 'nosuchsection');
322 }
323 if ($this->generateXML) {
324 $wgParser->startExternalParse( $title, new ParserOptions(), OT_PREPROCESS );
325 $dom = $wgParser->preprocessToDom( $text );
326 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
327 $xml = $dom->saveXML();
328 } else {
329 $xml = $dom->__toString();
330 }
331 $vals['parsetree'] = $xml;
332
333 }
334 if ($this->expandTemplates) {
335 $text = $wgParser->preprocess( $text, $title, new ParserOptions() );
336 }
337 ApiResult :: setContent($vals, $text);
338 }
339 return $vals;
340 }
341
342 public function getAllowedParams() {
343 return array (
344 'prop' => array (
345 ApiBase :: PARAM_ISMULTI => true,
346 ApiBase :: PARAM_DFLT => 'ids|timestamp|flags|comment|user',
347 ApiBase :: PARAM_TYPE => array (
348 'ids',
349 'flags',
350 'timestamp',
351 'user',
352 'size',
353 'comment',
354 'content',
355 )
356 ),
357 'limit' => array (
358 ApiBase :: PARAM_TYPE => 'limit',
359 ApiBase :: PARAM_MIN => 1,
360 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
361 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
362 ),
363 'startid' => array (
364 ApiBase :: PARAM_TYPE => 'integer'
365 ),
366 'endid' => array (
367 ApiBase :: PARAM_TYPE => 'integer'
368 ),
369 'start' => array (
370 ApiBase :: PARAM_TYPE => 'timestamp'
371 ),
372 'end' => array (
373 ApiBase :: PARAM_TYPE => 'timestamp'
374 ),
375 'dir' => array (
376 ApiBase :: PARAM_DFLT => 'older',
377 ApiBase :: PARAM_TYPE => array (
378 'newer',
379 'older'
380 )
381 ),
382 'user' => array(
383 ApiBase :: PARAM_TYPE => 'user'
384 ),
385 'excludeuser' => array(
386 ApiBase :: PARAM_TYPE => 'user'
387 ),
388 'expandtemplates' => false,
389 'generatexml' => false,
390 'section' => null,
391 'token' => array(
392 ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions()),
393 ApiBase :: PARAM_ISMULTI => true
394 ),
395 );
396 }
397
398 public function getParamDescription() {
399 return array (
400 'prop' => 'Which properties to get for each revision.',
401 'limit' => 'limit how many revisions will be returned (enum)',
402 'startid' => 'from which revision id to start enumeration (enum)',
403 'endid' => 'stop revision enumeration on this revid (enum)',
404 'start' => 'from which revision timestamp to start enumeration (enum)',
405 'end' => 'enumerate up to this timestamp (enum)',
406 'dir' => 'direction of enumeration - towards "newer" or "older" revisions (enum)',
407 'user' => 'only include revisions made by user',
408 'excludeuser' => 'exclude revisions made by user',
409 'expandtemplates' => 'expand templates in revision content',
410 'generatexml' => 'generate XML parse tree for revision content',
411 'section' => 'only retrieve the content of this section',
412 'token' => 'Which tokens to obtain for each revision',
413 );
414 }
415
416 public function getDescription() {
417 return array (
418 'Get revision information.',
419 'This module may be used in several ways:',
420 ' 1) Get data about a set of pages (last revision), by setting titles or pageids parameter.',
421 ' 2) Get revisions for one given page, by using titles/pageids with start/end/limit params.',
422 ' 3) Get data about a set of revisions by setting their IDs with revids parameter.',
423 'All parameters marked as (enum) may only be used with a single page (#2).'
424 );
425 }
426
427 protected function getExamples() {
428 return array (
429 'Get data with content for the last revision of titles "API" and "Main Page":',
430 ' api.php?action=query&prop=revisions&titles=API|Main%20Page&rvprop=timestamp|user|comment|content',
431 'Get last 5 revisions of the "Main Page":',
432 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment',
433 'Get first 5 revisions of the "Main Page":',
434 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer',
435 'Get first 5 revisions of the "Main Page" made after 2006-05-01:',
436 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer&rvstart=20060501000000',
437 'Get first 5 revisions of the "Main Page" that were not made made by anonymous user "127.0.0.1"',
438 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1',
439 'Get first 5 revisions of the "Main Page" that were made by the user "MediaWiki default"',
440 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvuser=MediaWiki%20default',
441 );
442 }
443
444 public function getVersion() {
445 return __CLASS__ . ': $Id$';
446 }
447 }