Actually, page not always selected. Add this only when needed.
[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 = $expandtemplates = $section = $token = null;
49 extract($this->extractRequestParams(false));
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));
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 and end parameters may only be used on a single page.', 'multpages');
71
72 $this->addTables('revision');
73 $this->addFields( Revision::selectFields() );
74
75 $prop = array_flip($prop);
76
77 // Optional fields
78 $this->fld_ids = isset ($prop['ids']);
79 // $this->addFieldsIf('rev_text_id', $this->fld_ids); // should this be exposed?
80 $this->fld_flags = isset ($prop['flags']);
81 $this->fld_timestamp = isset ($prop['timestamp']);
82 $this->fld_comment = isset ($prop['comment']);
83 $this->fld_size = isset ($prop['size']);
84 $this->tok_rollback = false; // Prevent PHP undefined property notice
85 if(!is_null($token))
86 $this->tok_rollback = $this->getTokenFlag($token, 'rollback');
87 $this->fld_user = isset ($prop['user']);
88
89 if ( $this->tok_rollback || ( $this->fld_content && $this->expandTemplates ) || $pageCount > 0) {
90 $this->addTables( 'page' );
91 $this->addWhere('page_id=rev_page');
92 $this->addFields( Revision::selectPageFields() );
93 }
94
95 if (isset ($prop['content'])) {
96
97 // For each page we will request, the user must have read rights for that page
98 foreach ($pageSet->getGoodTitles() as $title) {
99 if( !$title->userCanRead() )
100 $this->dieUsage(
101 'The current user is not allowed to read ' . $title->getPrefixedText(),
102 'accessdenied');
103 }
104
105 $this->addTables('text');
106 $this->addWhere('rev_text_id=old_id');
107 $this->addFields('old_id');
108 $this->addFields( Revision::selectTextFields() );
109
110 $this->fld_content = true;
111
112 $this->expandTemplates = $expandtemplates;
113 if(isset($section))
114 $this->section = $section;
115 else
116 $this->section = false;
117 }
118
119 $userMax = ( $this->fld_content ? ApiBase::LIMIT_SML1 : ApiBase::LIMIT_BIG1 );
120 $botMax = ( $this->fld_content ? ApiBase::LIMIT_SML2 : ApiBase::LIMIT_BIG2 );
121 if( $limit == 'max' ) {
122 $limit = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
123 $this->getResult()->addValue( 'limits', $this->getModuleName(), $limit );
124 }
125
126 if ($enumRevMode) {
127
128 // This is mostly to prevent parameter errors (and optimize SQL?)
129 if (!is_null($startid) && !is_null($start))
130 $this->dieUsage('start and startid cannot be used together', 'badparams');
131
132 if (!is_null($endid) && !is_null($end))
133 $this->dieUsage('end and endid cannot be used together', 'badparams');
134
135 if(!is_null($user) && !is_null( $excludeuser))
136 $this->dieUsage('user and excludeuser cannot be used together', 'badparams');
137
138 // This code makes an assumption that sorting by rev_id and rev_timestamp produces
139 // the same result. This way users may request revisions starting at a given time,
140 // but to page through results use the rev_id returned after each page.
141 // Switching to rev_id removes the potential problem of having more than
142 // one row with the same timestamp for the same page.
143 // The order needs to be the same as start parameter to avoid SQL filesort.
144
145 if (is_null($startid) && is_null($endid))
146 $this->addWhereRange('rev_timestamp', $dir, $start, $end);
147 else
148 $this->addWhereRange('rev_id', $dir, $startid, $endid);
149
150 // must manually initialize unset limit
151 if (is_null($limit))
152 $limit = 10;
153 $this->validateLimit('limit', $limit, 1, $userMax, $botMax);
154
155 // There is only one ID, use it
156 $this->addWhereFld('rev_page', current(array_keys($pageSet->getGoodTitles())));
157
158 if(!is_null($user)) {
159 $this->addWhereFld('rev_user_text', $user);
160 } elseif (!is_null( $excludeuser)) {
161 $this->addWhere('rev_user_text != ' . $this->getDB()->addQuotes($excludeuser));
162 }
163 }
164 elseif ($revCount > 0) {
165 $this->validateLimit('rev_count', $revCount, 1, $userMax, $botMax);
166
167 // Get all revision IDs
168 $this->addWhereFld('rev_id', array_keys($pageSet->getRevisionIDs()));
169
170 // assumption testing -- we should never get more then $revCount rows.
171 $limit = $revCount;
172 }
173 elseif ($pageCount > 0) {
174 // When working in multi-page non-enumeration mode,
175 // limit to the latest revision only
176 $this->addWhere('page_id=rev_page');
177 $this->addWhere('page_latest=rev_id');
178 $this->validateLimit('page_count', $pageCount, 1, $userMax, $botMax);
179
180 // Get all page IDs
181 $this->addWhereFld('page_id', array_keys($pageSet->getGoodTitles()));
182
183 // assumption testing -- we should never get more then $pageCount rows.
184 $limit = $pageCount;
185 } else
186 ApiBase :: dieDebug(__METHOD__, 'param validation?');
187
188 $this->addOption('LIMIT', $limit +1);
189
190 $data = array ();
191 $count = 0;
192 $res = $this->select(__METHOD__);
193
194 $db = $this->getDB();
195 while ($row = $db->fetchObject($res)) {
196
197 if (++ $count > $limit) {
198 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
199 if (!$enumRevMode)
200 ApiBase :: dieDebug(__METHOD__, 'Got more rows then expected'); // bug report
201 $this->setContinueEnumParameter('startid', intval($row->rev_id));
202 break;
203 }
204
205 $revision = new Revision( $row );
206 $this->getResult()->addValue(
207 array (
208 'query',
209 'pages',
210 $revision->getPage(),
211 'revisions'),
212 null,
213 $this->extractRowInfo( $revision ));
214 }
215 $db->freeResult($res);
216
217 // Ensure that all revisions are shown as '<rev>' elements
218 $result = $this->getResult();
219 if ($result->getIsRawMode()) {
220 $data =& $result->getData();
221 foreach ($data['query']['pages'] as & $page) {
222 if (is_array($page) && array_key_exists('revisions', $page)) {
223 $result->setIndexedTagName($page['revisions'], 'rev');
224 }
225 }
226 }
227 }
228
229 private function extractRowInfo( $revision ) {
230
231 $vals = array ();
232
233 if ($this->fld_ids) {
234 $vals['revid'] = $revision->getId();
235 // $vals['oldid'] = intval($row->rev_text_id); // todo: should this be exposed?
236 }
237
238 if ($this->fld_flags && $revision->isMinor())
239 $vals['minor'] = '';
240
241 if ($this->fld_user) {
242 $vals['user'] = $revision->getUserText();
243 if (!$revision->getUser())
244 $vals['anon'] = '';
245 }
246
247 if ($this->fld_timestamp) {
248 $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $revision->getTimestamp());
249 }
250
251 if ($this->fld_size && !is_null($revision->getSize())) {
252 $vals['size'] = $revision->getSize();
253 }
254
255 if ($this->fld_comment) {
256 $comment = $revision->getComment();
257 if (!empty($comment))
258 $vals['comment'] = $comment;
259 }
260
261 if($this->tok_rollback || ($this->fld_content && $this->expandTemplates))
262 $title = $revision->getTitle();
263
264 if($this->tok_rollback) {
265 global $wgUser;
266 $vals['rollbacktoken'] = $wgUser->editToken( array(
267 $title->getPrefixedText(),
268 $revision->getUserText(),
269 ) );
270 }
271
272
273 if ($this->fld_content) {
274 global $wgParser;
275 $text = $revision->getText();
276 # Expand templates after getting section content because
277 # template-added sections don't count and Parser::preprocess()
278 # will have less input
279 if ($this->section !== false) {
280 $text = $wgParser->getSection( $text, $this->section, false);
281 if($text === false)
282 $this->dieUsage("There is no section {$this->section} in r".$revision->getId(), 'nosuchsection');
283 }
284 if ($this->expandTemplates) {
285 $text = $wgParser->preprocess( $text, $title, new ParserOptions() );
286 }
287 ApiResult :: setContent($vals, $text);
288 }
289 return $vals;
290 }
291
292 public function getAllowedParams() {
293 return array (
294 'prop' => array (
295 ApiBase :: PARAM_ISMULTI => true,
296 ApiBase :: PARAM_DFLT => 'ids|timestamp|flags|comment|user',
297 ApiBase :: PARAM_TYPE => array (
298 'ids',
299 'flags',
300 'timestamp',
301 'user',
302 'size',
303 'comment',
304 'content',
305 )
306 ),
307 'limit' => array (
308 ApiBase :: PARAM_TYPE => 'limit',
309 ApiBase :: PARAM_MIN => 1,
310 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
311 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
312 ),
313 'startid' => array (
314 ApiBase :: PARAM_TYPE => 'integer'
315 ),
316 'endid' => array (
317 ApiBase :: PARAM_TYPE => 'integer'
318 ),
319 'start' => array (
320 ApiBase :: PARAM_TYPE => 'timestamp'
321 ),
322 'end' => array (
323 ApiBase :: PARAM_TYPE => 'timestamp'
324 ),
325 'dir' => array (
326 ApiBase :: PARAM_DFLT => 'older',
327 ApiBase :: PARAM_TYPE => array (
328 'newer',
329 'older'
330 )
331 ),
332 'user' => array(
333 ApiBase :: PARAM_TYPE => 'user'
334 ),
335 'excludeuser' => array(
336 ApiBase :: PARAM_TYPE => 'user'
337 ),
338
339 'expandtemplates' => false,
340 'section' => array(
341 ApiBase :: PARAM_TYPE => 'integer'
342 ),
343 'token' => array(
344 ApiBase :: PARAM_TYPE => array(
345 'rollback'
346 ),
347 ApiBase :: PARAM_ISMULTI => true
348 ),
349 );
350 }
351
352 public function getParamDescription() {
353 return array (
354 'prop' => 'Which properties to get for each revision.',
355 'limit' => 'limit how many revisions will be returned (enum)',
356 'startid' => 'from which revision id to start enumeration (enum)',
357 'endid' => 'stop revision enumeration on this revid (enum)',
358 'start' => 'from which revision timestamp to start enumeration (enum)',
359 'end' => 'enumerate up to this timestamp (enum)',
360 'dir' => 'direction of enumeration - towards "newer" or "older" revisions (enum)',
361 'user' => 'only include revisions made by user',
362 'excludeuser' => 'exclude revisions made by user',
363 'expandtemplates' => 'expand templates in revision content',
364 'section' => 'only retrieve the content of this section',
365 'token' => 'Which tokens to obtain for each revision',
366 );
367 }
368
369 public function getDescription() {
370 return array (
371 'Get revision information.',
372 'This module may be used in several ways:',
373 ' 1) Get data about a set of pages (last revision), by setting titles or pageids parameter.',
374 ' 2) Get revisions for one given page, by using titles/pageids with start/end/limit params.',
375 ' 3) Get data about a set of revisions by setting their IDs with revids parameter.',
376 'All parameters marked as (enum) may only be used with a single page (#2).'
377 );
378 }
379
380 protected function getExamples() {
381 return array (
382 'Get data with content for the last revision of titles "API" and "Main Page":',
383 ' api.php?action=query&prop=revisions&titles=API|Main%20Page&rvprop=timestamp|user|comment|content',
384 'Get last 5 revisions of the "Main Page":',
385 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment',
386 'Get first 5 revisions of the "Main Page":',
387 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer',
388 'Get first 5 revisions of the "Main Page" made after 2006-05-01:',
389 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer&rvstart=20060501000000',
390 'Get first 5 revisions of the "Main Page" that were not made made by anonymous user "127.0.0.1"',
391 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1',
392 'Get first 5 revisions of the "Main Page" that were made by the user "MediaWiki default"',
393 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvuser=MediaWiki%20default',
394 );
395 }
396
397 public function getVersion() {
398 return __CLASS__ . ': $Id$';
399 }
400 }