Remove invalid example from ApiQueryRevisions
[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 * @addtogroup 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 public function execute() {
48 $limit = $startid = $endid = $start = $end = $dir = $prop = $user = $excludeuser = $diffto = $difftoprev = $diffformat = $token = null;
49 extract($this->extractRequestParams());
50
51 // If any of those parameters are used, work in 'enumeration' mode.
52 // Enum mode can only be used when exactly one page is provided.
53 // Enumerating revisions on multiple pages make it extremely
54 // difficult to manage continuations and require additional SQL indexes
55 $enumRevMode = (!is_null($user) || !is_null($excludeuser) || !is_null($limit) || !is_null($startid) || !is_null($endid) || $dir === 'newer' || !is_null($start) || !is_null($end) | $difftoprev);
56
57
58 $pageSet = $this->getPageSet();
59 $pageCount = $pageSet->getGoodTitleCount();
60 $revCount = $pageSet->getRevisionCount();
61
62 // Optimization -- nothing to do
63 if ($revCount === 0 && $pageCount === 0)
64 return;
65
66 if ($revCount > 0 && $enumRevMode)
67 $this->dieUsage('The revids= parameter may not be used with the list options (limit, startid, endid, dirNewer, start, end).', 'revids');
68
69 if ($pageCount > 1 && $enumRevMode)
70 $this->dieUsage('titles, pageids or a generator was used to supply multiple pages, but the limit, startid, endid, dirNewer, user, excludeuser, start, end and difftoprev parameters may only be used on a single page.', 'multpages');
71
72 $this->addTables('revision');
73 $this->addWhere('rev_deleted=0');
74
75 $prop = array_flip($prop);
76
77 // These field are needed regardless of the client requesting them
78 $this->addFields('rev_id');
79 $this->addFields('rev_page');
80
81 // Optional fields
82 $this->fld_ids = isset ($prop['ids']);
83 // $this->addFieldsIf('rev_text_id', $this->fld_ids); // should this be exposed?
84 $this->fld_flags = $this->addFieldsIf('rev_minor_edit', isset ($prop['flags']));
85 $this->fld_timestamp = $this->addFieldsIf('rev_timestamp', isset ($prop['timestamp']));
86 $this->fld_comment = $this->addFieldsIf('rev_comment', isset ($prop['comment']));
87 $this->fld_size = $this->addFieldsIf('rev_len', isset ($prop['size']));
88 if(!is_null($token))
89 {
90 $this->tok_rollback = $this->getTokenFlag($token, 'rollback');
91 }
92
93 if($diffto || $difftoprev)
94 switch($diffformat)
95 {
96 // To add your own formatter, create a subclass of DiffFormatter
97 // in DifferenceEngine.php, then add it here
98 case 'traditional':
99 $this->formatter = new DiffFormatter;
100 break;
101 case 'unified':
102 $this->formatter = new UnifiedDiffFormatter;
103 break;
104 case 'array':
105 $this->formatter = new ArrayDiffFormatter;
106 break;
107 }
108 if($diffto)
109 {
110 global $wgContLang;
111 $difftoRev = Revision::newFromID($diffto);
112 if(!($difftoRev instanceof Revision))
113 $this->dieUsage("There is no revision with ID $diffto", 'nosuchrev');
114 $this->diffOldText = $difftoRev->revText();
115 if($this->diffOldText == '') // deleted revision
116 $this->dieUsage("There is no revision with ID $diffto", 'nosuchrev'); // fake non-existence
117 $this->diffOldText = explode("\n", $wgContLang->segmentForDiff($this->diffOldText));
118 $this->diffto = $diffto;
119 }
120 else
121 $this->diffto = false;
122 if($difftoprev)
123 {
124 $this->revCache = array();
125 $this->difftoprev = true;
126 }
127 else
128 $this->difftoprev = false;
129
130 if (isset ($prop['user'])) {
131 $this->addFields('rev_user');
132 $this->addFields('rev_user_text');
133 $this->fld_user = true;
134 }
135 else if($this->tok_rollback)
136 $this->addFields('rev_user_text');
137
138 if (isset ($prop['content']) || !is_null($diffto) || $difftoprev) {
139
140 // For each page we will request, the user must have read rights for that page
141 foreach ($pageSet->getGoodTitles() as $title) {
142 if( !$title->userCanRead() )
143 $this->dieUsage(
144 'The current user is not allowed to read ' . $title->getPrefixedText(),
145 'accessdenied');
146 }
147
148 $this->addTables('text');
149 $this->addWhere('rev_text_id=old_id');
150 $this->addFields('old_id');
151 $this->addFields('old_text');
152 $this->addFields('old_flags');
153
154 $this->fld_content = isset($prop['content']);
155
156 $this->expandTemplates = $expandtemplates;
157 }
158
159 $userMax = ($this->fld_content || $diffto || $difftoprev ? 50 : 500);
160 $botMax = ($this->fld_content || $diffto || $difftoprev ? 200 : 10000);
161
162 if ($enumRevMode) {
163
164 // This is mostly to prevent parameter errors (and optimize SQL?)
165 if (!is_null($startid) && !is_null($start))
166 $this->dieUsage('start and startid cannot be used together', 'badparams');
167
168 if (!is_null($endid) && !is_null($end))
169 $this->dieUsage('end and endid cannot be used together', 'badparams');
170
171 if(!is_null($user) && !is_null( $excludeuser))
172 $this->dieUsage('user and excludeuser cannot be used together', 'badparams');
173
174 // This code makes an assumption that sorting by rev_id and rev_timestamp produces
175 // the same result. This way users may request revisions starting at a given time,
176 // but to page through results use the rev_id returned after each page.
177 // Switching to rev_id removes the potential problem of having more than
178 // one row with the same timestamp for the same page.
179 // The order needs to be the same as start parameter to avoid SQL filesort.
180
181 if (is_null($startid) && is_null($endid))
182 $this->addWhereRange('rev_timestamp', $dir, $start, $end);
183 else
184 $this->addWhereRange('rev_id', $dir, $startid, $endid);
185
186 // must manually initialize unset limit
187 if (is_null($limit))
188 $limit = 10;
189 $this->validateLimit('limit', $limit, 1, $userMax, $botMax);
190
191 // There is only one ID, use it
192 $this->addWhereFld('rev_page', current(array_keys($pageSet->getGoodTitles())));
193
194 if(!is_null($user)) {
195 $this->addWhereFld('rev_user_text', $user);
196 } elseif (!is_null( $excludeuser)) {
197 $this->addWhere('rev_user_text != ' . $this->getDB()->addQuotes($excludeuser));
198 }
199 }
200 elseif ($revCount > 0) {
201 $this->validateLimit('rev_count', $revCount, 1, $userMax, $botMax);
202
203 // Get all revision IDs
204 $this->addWhereFld('rev_id', array_keys($pageSet->getRevisionIDs()));
205
206 // assumption testing -- we should never get more then $revCount rows.
207 $limit = $revCount;
208 }
209 elseif ($pageCount > 0) {
210 // When working in multi-page non-enumeration mode,
211 // limit to the latest revision only
212 $this->addTables('page');
213 $this->addWhere('page_id=rev_page');
214 $this->addWhere('page_latest=rev_id');
215 $this->validateLimit('page_count', $pageCount, 1, $userMax, $botMax);
216
217 // Get all page IDs
218 $this->addWhereFld('page_id', array_keys($pageSet->getGoodTitles()));
219
220 // assumption testing -- we should never get more then $pageCount rows.
221 $limit = $pageCount;
222 } else
223 ApiBase :: dieDebug(__METHOD__, 'param validation?');
224
225 $this->addOption('LIMIT', $limit +1);
226
227 $data = array ();
228 $count = 0;
229 $res = $this->select(__METHOD__);
230
231 $db = $this->getDB();
232 while ($row = $db->fetchObject($res)) {
233
234 if (++ $count > $limit) {
235 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
236 if (!$enumRevMode)
237 ApiBase :: dieDebug(__METHOD__, 'Got more rows then expected'); // bug report
238 $this->setContinueEnumParameter('startid', intval($row->rev_id));
239 break;
240 }
241
242 $this->getResult()->addValue(
243 array (
244 'query',
245 'pages',
246 intval($row->rev_page),
247 'revisions'),
248 null,
249 $this->extractRowInfo($row));
250 }
251 $db->freeResult($res);
252
253 if($this->difftoprev)
254 {
255 global $wgContLang;
256 ksort($this->revCache, SORT_NUMERIC);
257 $previousRevID = null;
258 $oldText = null;
259 $data =& $this->getResult()->getData();
260 $pageID = current(array_keys($pageSet->getGoodTitles()));
261 $this->diffArr = array();
262 foreach($this->revCache as $revid => $revtext)
263 {
264 $r = array();
265 if(is_null($previousRevID))
266 {
267 // First run
268 $previousRevID = $revid;
269 $oldText = explode("\n", $wgContLang->segmentForDiff($revtext));
270 continue;
271 }
272 $newText = explode("\n", $wgContLang->segmentForDiff($revtext));
273 $diff = new Diff($oldText, $newText);
274 $r['from'] = $previousRevID;
275 $formatted = $this->formatter->format($diff);
276 if(!is_array($formatted))
277 ApiResult::setContent($r, $wgContLang->unsegmentForDiff($this->formatter->format($diff)));
278 else
279 {
280 $r['differences'] = $formatted;
281 $this->getResult()->setIndexedTagName($r['differences'], 'diff');
282 }
283 $this->diffArr[$revid] = $r;
284
285 $previousRevID = $revid;
286 $oldText = $newText;
287 }
288
289 if ( $this->diffArr ) {
290 # Populate the query result with the contents of $this->diffArr.
291 $knownrevs = array_keys($this->diffArr);
292 $i = count($knownrevs) - 1;
293 foreach($data['query']['pages'][$pageID]['revisions'] as &$rev) {
294 if ( $i >= 0 && isset ( $this->diffArr[$knownrevs[$i]] ) )
295 $rev['difftoprev'] = $this->diffArr[$knownrevs[$i]];
296 $i --;
297 }
298 }
299 }
300
301 // Ensure that all revisions are shown as '<rev>' elements
302 $result = $this->getResult();
303 if ($result->getIsRawMode()) {
304 $data =& $result->getData();
305 foreach ($data['query']['pages'] as & $page) {
306 if (is_array($page) && array_key_exists('revisions', $page)) {
307 $result->setIndexedTagName($page['revisions'], 'rev');
308 }
309 }
310 }
311 }
312
313 private function extractRowInfo($row) {
314
315 $vals = array ();
316
317 if ($this->fld_ids) {
318 $vals['revid'] = intval($row->rev_id);
319 // $vals['oldid'] = intval($row->rev_text_id); // todo: should this be exposed?
320 }
321
322 if ($this->fld_flags && $row->rev_minor_edit)
323 $vals['minor'] = '';
324
325 if ($this->fld_user) {
326 $vals['user'] = $row->rev_user_text;
327 if (!$row->rev_user)
328 $vals['anon'] = '';
329 }
330
331 if ($this->fld_timestamp) {
332 $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $row->rev_timestamp);
333 }
334
335 if ($this->fld_size && !is_null($row->rev_len)) {
336 $vals['size'] = intval($row->rev_len);
337 }
338
339 if ($this->fld_comment && !empty ($row->rev_comment)) {
340 $vals['comment'] = $row->rev_comment;
341 }
342
343 if($this->tok_rollback || ($this->fld_content && $this->expandTemplates))
344 $title = Title::newFromID($row->rev_page);
345
346 if($this->tok_rollback) {
347 global $wgUser;
348 $vals['rollbacktoken'] = $wgUser->editToken(array($title->getPrefixedText(), $row->rev_user_text));
349 }
350
351 if ($this->fld_content || $this->diffto || $this->difftoprev)
352 $text = Revision :: getRevisionText($row);
353 if ($this->fld_content) {
354 if ($this->expandTemplates) {
355 global $wgParser;
356 $text = $wgParser->preprocess( $text, $title, new ParserOptions() );
357 }
358 ApiResult :: setContent($vals, $text);
359 }
360
361 if($this->diffto)
362 {
363 global $wgContLang;
364 $newText = explode("\n", $wgContLang->segmentForDiff($text));
365 $diff = new Diff($this->diffOldText, $newText);
366 $vals['diffto']['from'] = $this->diffto;
367 $arraydiff = $this->formatter instanceof ArrayDiffFormatter;
368 if( $arraydiff ) {
369 $changes = $wgContLang->unsegmentForDiff($this->formatter->format($diff));
370 $this->getResult()->setIndexedTagName( $changes, 'change' );
371 $vals['diffto'] = $changes;
372 } else {
373 ApiResult::setContent($vals['diffto'], $wgContLang->unsegmentForDiff($this->formatter->format($diff)));
374 }
375 }
376 if($this->difftoprev)
377 // Cache the revision's content for later use
378 $this->revCache[$row->rev_id] = $text;
379
380 return $vals;
381 }
382
383 protected function getAllowedParams() {
384 return array (
385 'prop' => array (
386 ApiBase :: PARAM_ISMULTI => true,
387 ApiBase :: PARAM_DFLT => 'ids|timestamp|flags|comment|user',
388 ApiBase :: PARAM_TYPE => array (
389 'ids',
390 'flags',
391 'timestamp',
392 'user',
393 'size',
394 'comment',
395 'content',
396 )
397 ),
398 'limit' => array (
399 ApiBase :: PARAM_TYPE => 'limit',
400 ApiBase :: PARAM_MIN => 1,
401 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
402 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
403 ),
404 'startid' => array (
405 ApiBase :: PARAM_TYPE => 'integer'
406 ),
407 'endid' => array (
408 ApiBase :: PARAM_TYPE => 'integer'
409 ),
410 'start' => array (
411 ApiBase :: PARAM_TYPE => 'timestamp'
412 ),
413 'end' => array (
414 ApiBase :: PARAM_TYPE => 'timestamp'
415 ),
416 'dir' => array (
417 ApiBase :: PARAM_DFLT => 'older',
418 ApiBase :: PARAM_TYPE => array (
419 'newer',
420 'older'
421 )
422 ),
423 'user' => array(
424 ApiBase :: PARAM_TYPE => 'user'
425 ),
426 'excludeuser' => array(
427 ApiBase :: PARAM_TYPE => 'user'
428 ),
429
430 'expandtemplates' => false,
431 'diffto' => array(
432 ApiBase :: PARAM_TYPE => 'integer'
433 ),
434 'difftoprev' => false,
435 'diffformat' => array(
436 ApiBase :: PARAM_TYPE => array(
437 'traditional',
438 'unified',
439 'array',
440 ),
441 ApiBase :: PARAM_DFLT => 'unified'
442 ),
443 'token' => array(
444 ApiBase :: PARAM_TYPE => array(
445 'rollback'
446 ),
447 ApiBase :: PARAM_ISMULTI => true
448 ),
449 );
450 }
451
452 protected function getParamDescription() {
453 return array (
454 'prop' => 'Which properties to get for each revision.',
455 'limit' => 'limit how many revisions will be returned (enum)',
456 'startid' => 'from which revision id to start enumeration (enum)',
457 'endid' => 'stop revision enumeration on this revid (enum)',
458 'start' => 'from which revision timestamp to start enumeration (enum)',
459 'end' => 'enumerate up to this timestamp (enum)',
460 'dir' => 'direction of enumeration - towards "newer" or "older" revisions (enum)',
461 'user' => 'only include revisions made by user',
462 'excludeuser' => 'exclude revisions made by user',
463 'expandtemplates' => 'expand templates in revision content',
464 'diffto' => 'Revision number to compare all revisions with',
465 'difftoprev' => 'Diff each revision to the previous one (enum)',
466 'diffformat' => 'Format to use for diffs',
467 'token' => 'Which tokens to obtain for each revision',
468 );
469 }
470
471 protected function getDescription() {
472 return array (
473 'Get revision information.',
474 'This module may be used in several ways:',
475 ' 1) Get data about a set of pages (last revision), by setting titles or pageids parameter.',
476 ' 2) Get revisions for one given page, by using titles/pageids with start/end/limit params.',
477 ' 3) Get data about a set of revisions by setting their IDs with revids parameter.',
478 'All parameters marked as (enum) may only be used with a single page (#2).'
479 );
480 }
481
482 protected function getExamples() {
483 return array (
484 'Get data with content for the last revision of the "Main Page":',
485 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvprop=timestamp|user|comment|content',
486 'Get last 5 revisions of the "Main Page":',
487 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment',
488 'Get first 5 revisions of the "Main Page":',
489 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer',
490 'Get first 5 revisions of the "Main Page" made after 2006-05-01:',
491 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer&rvstart=20060501000000',
492 'Get first 5 revisions of the "Main Page" that were not made made by anonymous user "127.0.0.1"',
493 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1',
494 'Get first 5 revisions of the "Main Page" that were made by the user "MediaWiki default"',
495 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvuser=MediaWiki%20default',
496 );
497 }
498
499 public function getVersion() {
500 return __CLASS__ . ': $Id$';
501 }
502 }
503