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