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