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