Added bitwise operations to DatabaseBase and overloaded in DatabaseOracle.
[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 $params = $this->extractRequestParams(false);
78
79 // If any of those parameters are used, work in 'enumeration' mode.
80 // Enum mode can only be used when exactly one page is provided.
81 // Enumerating revisions on multiple pages make it extremely
82 // difficult to manage continuations and require additional SQL indexes
83 $enumRevMode = (!is_null($params['user']) || !is_null($params['excludeuser']) ||
84 !is_null($params['limit']) || !is_null($params['startid']) ||
85 !is_null($params['endid']) || $params['dir'] === 'newer' ||
86 !is_null($params['start']) || !is_null($params['end']));
87
88
89 $pageSet = $this->getPageSet();
90 $pageCount = $pageSet->getGoodTitleCount();
91 $revCount = $pageSet->getRevisionCount();
92
93 // Optimization -- nothing to do
94 if ($revCount === 0 && $pageCount === 0)
95 return;
96
97 if ($revCount > 0 && $enumRevMode)
98 $this->dieUsage('The revids= parameter may not be used with the list options (limit, startid, endid, dirNewer, start, end).', 'revids');
99
100 if ($pageCount > 1 && $enumRevMode)
101 $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');
102
103 if (!is_null($params['diffto'])) {
104 if ($params['diffto'] == 'cur')
105 $params['diffto'] = 0;
106 if ((!ctype_digit($params['diffto']) || $params['diffto'] < 0)
107 && $params['diffto'] != 'prev' && $params['diffto'] != 'next')
108 $this->dieUsage('rvdiffto must be set to a non-negative number, "prev", "next" or "cur"', 'diffto');
109 // Check whether the revision exists and is readable,
110 // DifferenceEngine returns a rather ambiguous empty
111 // string if that's not the case
112 if ($params['diffto'] != 0) {
113 $difftoRev = Revision::newFromID($params['diffto']);
114 if (!$difftoRev)
115 $this->dieUsageMsg(array('nosuchrevid', $params['diffto']));
116 if (!$difftoRev->userCan(Revision::DELETED_TEXT)) {
117 $this->setWarning("Couldn't diff to r{$difftoRev->getID()}: content is hidden");
118 $params['diffto'] = null;
119 }
120 }
121 }
122
123 $db = $this->getDB();
124 $this->addTables('revision');
125 $this->addFields(Revision::selectFields());
126 $this->addTables('page');
127 $this->addWhere('page_id = rev_page');
128
129 $prop = array_flip($params['prop']);
130
131 // Optional fields
132 $this->fld_ids = isset ($prop['ids']);
133 // $this->addFieldsIf('rev_text_id', $this->fld_ids); // should this be exposed?
134 $this->fld_flags = isset ($prop['flags']);
135 $this->fld_timestamp = isset ($prop['timestamp']);
136 $this->fld_comment = isset ($prop['comment']);
137 $this->fld_size = isset ($prop['size']);
138 $this->fld_user = isset ($prop['user']);
139 $this->token = $params['token'];
140 $this->diffto = $params['diffto'];
141
142 if ( !is_null($this->token) || $pageCount > 0) {
143 $this->addFields( Revision::selectPageFields() );
144 }
145
146 if (isset ($prop['content'])) {
147
148 // For each page we will request, the user must have read rights for that page
149 foreach ($pageSet->getGoodTitles() as $title) {
150 if( !$title->userCanRead() )
151 $this->dieUsage(
152 'The current user is not allowed to read ' . $title->getPrefixedText(),
153 'accessdenied');
154 }
155
156 $this->addTables('text');
157 $this->addWhere('rev_text_id=old_id');
158 $this->addFields('old_id');
159 $this->addFields(Revision::selectTextFields());
160
161 $this->fld_content = true;
162
163 $this->expandTemplates = $params['expandtemplates'];
164 $this->generateXML = $params['generatexml'];
165 if(isset($params['section']))
166 $this->section = $params['section'];
167 else
168 $this->section = false;
169 }
170
171 $userMax = ( $this->fld_content ? ApiBase::LIMIT_SML1 : ApiBase::LIMIT_BIG1 );
172 $botMax = ( $this->fld_content ? ApiBase::LIMIT_SML2 : ApiBase::LIMIT_BIG2 );
173 $limit = $params['limit'];
174 if( $limit == 'max' ) {
175 $limit = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
176 $this->getResult()->addValue( 'limits', $this->getModuleName(), $limit );
177 }
178
179 if ($enumRevMode) {
180
181 // This is mostly to prevent parameter errors (and optimize SQL?)
182 if (!is_null($params['startid']) && !is_null($params['start']))
183 $this->dieUsage('start and startid cannot be used together', 'badparams');
184
185 if (!is_null($params['endid']) && !is_null($params['end']))
186 $this->dieUsage('end and endid cannot be used together', 'badparams');
187
188 if(!is_null($params['user']) && !is_null($params['excludeuser']))
189 $this->dieUsage('user and excludeuser cannot be used together', 'badparams');
190
191 // This code makes an assumption that sorting by rev_id and rev_timestamp produces
192 // the same result. This way users may request revisions starting at a given time,
193 // but to page through results use the rev_id returned after each page.
194 // Switching to rev_id removes the potential problem of having more than
195 // one row with the same timestamp for the same page.
196 // The order needs to be the same as start parameter to avoid SQL filesort.
197
198 if (is_null($params['startid']) && is_null($params['endid']))
199 $this->addWhereRange('rev_timestamp', $params['dir'],
200 $params['start'], $params['end']);
201 else {
202 $this->addWhereRange('rev_id', $params['dir'],
203 $params['startid'], $params['endid']);
204 // One of start and end can be set
205 // If neither is set, this does nothing
206 $this->addWhereRange('rev_timestamp', $params['dir'],
207 $params['start'], $params['end'], false);
208 }
209
210 // must manually initialize unset limit
211 if (is_null($limit))
212 $limit = 10;
213 $this->validateLimit('limit', $limit, 1, $userMax, $botMax);
214
215 // There is only one ID, use it
216 $ids = array_keys($pageSet->getGoodTitles());
217 $this->addWhereFld('rev_page', reset($ids));
218
219 if(!is_null($params['user'])) {
220 $this->addWhereFld('rev_user_text', $params['user']);
221 } elseif (!is_null($params['excludeuser'])) {
222 $this->addWhere('rev_user_text != ' .
223 $db->addQuotes($params['excludeuser']));
224 }
225 if(!is_null($params['user']) || !is_null($params['excludeuser'])) {
226 // Paranoia: avoid brute force searches (bug 17342)
227 $this->addWhere($db->bitAnd('rev_deleted',Revision::DELETED_USER) . ' = 0');
228 }
229 }
230 elseif ($revCount > 0) {
231 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
232 $revs = $pageSet->getRevisionIDs();
233 if(self::truncateArray($revs, $max))
234 $this->setWarning("Too many values supplied for parameter 'revids': the limit is $max");
235
236 // Get all revision IDs
237 $this->addWhereFld('rev_id', array_keys($revs));
238
239 if(!is_null($params['continue']))
240 $this->addWhere("rev_id >= '" . intval($params['continue']) . "'");
241 $this->addOption('ORDER BY', 'rev_id');
242
243 // assumption testing -- we should never get more then $revCount rows.
244 $limit = $revCount;
245 }
246 elseif ($pageCount > 0) {
247 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
248 $titles = $pageSet->getGoodTitles();
249 if(self::truncateArray($titles, $max))
250 $this->setWarning("Too many values supplied for parameter 'titles': the limit is $max");
251
252 // When working in multi-page non-enumeration mode,
253 // limit to the latest revision only
254 $this->addWhere('page_id=rev_page');
255 $this->addWhere('page_latest=rev_id');
256
257 // Get all page IDs
258 $this->addWhereFld('page_id', array_keys($titles));
259 // Every time someone relies on equality propagation, god kills a kitten :)
260 $this->addWhereFld('rev_page', array_keys($titles));
261
262 if(!is_null($params['continue']))
263 {
264 $cont = explode('|', $params['continue']);
265 if(count($cont) != 2)
266 $this->dieUsage("Invalid continue param. You should pass the original " .
267 "value returned by the previous query", "_badcontinue");
268 $pageid = intval($cont[0]);
269 $revid = intval($cont[1]);
270 $this->addWhere("rev_page > '$pageid' OR " .
271 "(rev_page = '$pageid' AND " .
272 "rev_id >= '$revid')");
273 }
274 $this->addOption('ORDER BY', 'rev_page, rev_id');
275
276 // assumption testing -- we should never get more then $pageCount rows.
277 $limit = $pageCount;
278 } else
279 ApiBase :: dieDebug(__METHOD__, 'param validation?');
280
281 $this->addOption('LIMIT', $limit +1);
282
283 $data = array ();
284 $count = 0;
285 $res = $this->select(__METHOD__);
286
287 while ($row = $db->fetchObject($res)) {
288
289 if (++ $count > $limit) {
290 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
291 if (!$enumRevMode)
292 ApiBase :: dieDebug(__METHOD__, 'Got more rows then expected'); // bug report
293 $this->setContinueEnumParameter('startid', intval($row->rev_id));
294 break;
295 }
296 $revision = new Revision( $row );
297 //
298 $fit = $this->addPageSubItem($revision->getPage(), $this->extractRowInfo($revision), 'rev');
299 if(!$fit)
300 {
301 if($enumRevMode)
302 $this->setContinueEnumParameter('startid', intval($row->rev_id));
303 else if($revCount > 0)
304 $this->setContinueEnumParameter('continue', intval($row->rev_id));
305 else
306 $this->setContinueEnumParameter('continue', intval($row->rev_page) .
307 '|' . intval($row->rev_id));
308 break;
309 }
310 }
311 $db->freeResult($res);
312 }
313
314 private function extractRowInfo( $revision ) {
315 $title = $revision->getTitle();
316 $vals = array ();
317
318 if ($this->fld_ids) {
319 $vals['revid'] = intval($revision->getId());
320 // $vals['oldid'] = intval($row->rev_text_id); // todo: should this be exposed?
321 if (!is_null($revision->getParentId()))
322 $vals['parentid'] = intval($revision->getParentId());
323 }
324
325 if ($this->fld_flags && $revision->isMinor())
326 $vals['minor'] = '';
327
328 if ($this->fld_user) {
329 if ($revision->isDeleted(Revision::DELETED_USER)) {
330 $vals['userhidden'] = '';
331 } else {
332 $vals['user'] = $revision->getUserText();
333 if (!$revision->getUser())
334 $vals['anon'] = '';
335 }
336 }
337
338 if ($this->fld_timestamp) {
339 $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $revision->getTimestamp());
340 }
341
342 if ($this->fld_size && !is_null($revision->getSize())) {
343 $vals['size'] = intval($revision->getSize());
344 }
345
346 if ($this->fld_comment) {
347 if ($revision->isDeleted(Revision::DELETED_COMMENT)) {
348 $vals['commenthidden'] = '';
349 } else {
350 $comment = $revision->getComment();
351 if (strval($comment) !== '')
352 $vals['comment'] = $comment;
353 }
354 }
355
356 if(!is_null($this->token))
357 {
358 $tokenFunctions = $this->getTokenFunctions();
359 foreach($this->token as $t)
360 {
361 $val = call_user_func($tokenFunctions[$t], $title->getArticleID(), $title, $revision);
362 if($val === false)
363 $this->setWarning("Action '$t' is not allowed for the current user");
364 else
365 $vals[$t . 'token'] = $val;
366 }
367 }
368
369 if ($this->fld_content && !$revision->isDeleted(Revision::DELETED_TEXT)) {
370 global $wgParser;
371 $text = $revision->getText();
372 # Expand templates after getting section content because
373 # template-added sections don't count and Parser::preprocess()
374 # will have less input
375 if ($this->section !== false) {
376 $text = $wgParser->getSection( $text, $this->section, false);
377 if($text === false)
378 $this->dieUsage("There is no section {$this->section} in r".$revision->getId(), 'nosuchsection');
379 }
380 if ($this->generateXML) {
381 $wgParser->startExternalParse( $title, new ParserOptions(), OT_PREPROCESS );
382 $dom = $wgParser->preprocessToDom( $text );
383 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
384 $xml = $dom->saveXML();
385 } else {
386 $xml = $dom->__toString();
387 }
388 $vals['parsetree'] = $xml;
389
390 }
391 if ($this->expandTemplates) {
392 $text = $wgParser->preprocess( $text, $title, new ParserOptions() );
393 }
394 ApiResult :: setContent($vals, $text);
395 } else if ($this->fld_content) {
396 $vals['texthidden'] = '';
397 }
398
399 if (!is_null($this->diffto)) {
400 global $wgAPIMaxUncachedDiffs;
401 static $n = 0; // Numer of uncached diffs we've had
402 if($n< $wgAPIMaxUncachedDiffs) {
403 $engine = new DifferenceEngine($title, $revision->getID(), $this->diffto);
404 $difftext = $engine->getDiffBody();
405 $vals['diff']['from'] = $engine->getOldid();
406 $vals['diff']['to'] = $engine->getNewid();
407 ApiResult::setContent($vals['diff'], $difftext);
408 if(!$engine->wasCacheHit())
409 $n++;
410 } else {
411 $vals['diff']['notcached'] = '';
412 }
413 }
414 return $vals;
415 }
416
417 public function getAllowedParams() {
418 return array (
419 'prop' => array (
420 ApiBase :: PARAM_ISMULTI => true,
421 ApiBase :: PARAM_DFLT => 'ids|timestamp|flags|comment|user',
422 ApiBase :: PARAM_TYPE => array (
423 'ids',
424 'flags',
425 'timestamp',
426 'user',
427 'size',
428 'comment',
429 'content',
430 )
431 ),
432 'limit' => array (
433 ApiBase :: PARAM_TYPE => 'limit',
434 ApiBase :: PARAM_MIN => 1,
435 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
436 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
437 ),
438 'startid' => array (
439 ApiBase :: PARAM_TYPE => 'integer'
440 ),
441 'endid' => array (
442 ApiBase :: PARAM_TYPE => 'integer'
443 ),
444 'start' => array (
445 ApiBase :: PARAM_TYPE => 'timestamp'
446 ),
447 'end' => array (
448 ApiBase :: PARAM_TYPE => 'timestamp'
449 ),
450 'dir' => array (
451 ApiBase :: PARAM_DFLT => 'older',
452 ApiBase :: PARAM_TYPE => array (
453 'newer',
454 'older'
455 )
456 ),
457 'user' => array(
458 ApiBase :: PARAM_TYPE => 'user'
459 ),
460 'excludeuser' => array(
461 ApiBase :: PARAM_TYPE => 'user'
462 ),
463 'expandtemplates' => false,
464 'generatexml' => false,
465 'section' => null,
466 'token' => array(
467 ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions()),
468 ApiBase :: PARAM_ISMULTI => true
469 ),
470 'continue' => null,
471 'diffto' => null,
472 );
473 }
474
475 public function getParamDescription() {
476 return array (
477 'prop' => 'Which properties to get for each revision.',
478 'limit' => 'limit how many revisions will be returned (enum)',
479 'startid' => 'from which revision id to start enumeration (enum)',
480 'endid' => 'stop revision enumeration on this revid (enum)',
481 'start' => 'from which revision timestamp to start enumeration (enum)',
482 'end' => 'enumerate up to this timestamp (enum)',
483 'dir' => 'direction of enumeration - towards "newer" or "older" revisions (enum)',
484 'user' => 'only include revisions made by user',
485 'excludeuser' => 'exclude revisions made by user',
486 'expandtemplates' => 'expand templates in revision content',
487 'generatexml' => 'generate XML parse tree for revision content',
488 'section' => 'only retrieve the content of this section',
489 'token' => 'Which tokens to obtain for each revision',
490 'continue' => 'When more results are available, use this to continue',
491 'diffto' => array('Revision ID to diff each revision to.',
492 'Use "prev", "next" and "cur" for the previous, next and current revision respectively.'),
493 );
494 }
495
496 public function getDescription() {
497 return array (
498 'Get revision information.',
499 'This module may be used in several ways:',
500 ' 1) Get data about a set of pages (last revision), by setting titles or pageids parameter.',
501 ' 2) Get revisions for one given page, by using titles/pageids with start/end/limit params.',
502 ' 3) Get data about a set of revisions by setting their IDs with revids parameter.',
503 'All parameters marked as (enum) may only be used with a single page (#2).'
504 );
505 }
506
507 protected function getExamples() {
508 return array (
509 'Get data with content for the last revision of titles "API" and "Main Page":',
510 ' api.php?action=query&prop=revisions&titles=API|Main%20Page&rvprop=timestamp|user|comment|content',
511 'Get last 5 revisions of the "Main Page":',
512 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment',
513 'Get first 5 revisions of the "Main Page":',
514 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer',
515 'Get first 5 revisions of the "Main Page" made after 2006-05-01:',
516 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer&rvstart=20060501000000',
517 'Get first 5 revisions of the "Main Page" that were not made made by anonymous user "127.0.0.1"',
518 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1',
519 'Get first 5 revisions of the "Main Page" that were made by the user "MediaWiki default"',
520 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvuser=MediaWiki%20default',
521 );
522 }
523
524 public function getVersion() {
525 return __CLASS__ . ': $Id$';
526 }
527 }