00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026 if (!defined('MEDIAWIKI')) {
00027
00028 require_once ('ApiQueryBase.php');
00029 }
00030
00038 class ApiQueryRevisions extends ApiQueryBase {
00039
00040 public function __construct($query, $moduleName) {
00041 parent :: __construct($query, $moduleName, 'rv');
00042 }
00043
00044 private $fld_ids = false, $fld_flags = false, $fld_timestamp = false, $fld_size = false,
00045 $fld_comment = false, $fld_user = false, $fld_content = false;
00046
00047 protected function getTokenFunctions() {
00048
00049
00050
00051
00052
00053 if(isset($this->tokenFunctions))
00054 return $this->tokenFunctions;
00055
00056
00057 if(!is_null($this->getMain()->getRequest()->getVal('callback')))
00058 return array();
00059
00060 $this->tokenFunctions = array(
00061 'rollback' => array( 'ApiQueryRevisions', 'getRollbackToken' )
00062 );
00063 wfRunHooks('APIQueryRevisionsTokens', array(&$this->tokenFunctions));
00064 return $this->tokenFunctions;
00065 }
00066
00067 public static function getRollbackToken($pageid, $title, $rev)
00068 {
00069 global $wgUser;
00070 if(!$wgUser->isAllowed('rollback'))
00071 return false;
00072 return $wgUser->editToken(array($title->getPrefixedText(),
00073 $rev->getUserText()));
00074 }
00075
00076 public function execute() {
00077 $params = $this->extractRequestParams(false);
00078
00079
00080
00081
00082
00083 $enumRevMode = (!is_null($params['user']) || !is_null($params['excludeuser']) ||
00084 !is_null($params['limit']) || !is_null($params['startid']) ||
00085 !is_null($params['endid']) || $params['dir'] === 'newer' ||
00086 !is_null($params['start']) || !is_null($params['end']));
00087
00088
00089 $pageSet = $this->getPageSet();
00090 $pageCount = $pageSet->getGoodTitleCount();
00091 $revCount = $pageSet->getRevisionCount();
00092
00093
00094 if ($revCount === 0 && $pageCount === 0)
00095 return;
00096
00097 if ($revCount > 0 && $enumRevMode)
00098 $this->dieUsage('The revids= parameter may not be used with the list options (limit, startid, endid, dirNewer, start, end).', 'revids');
00099
00100 if ($pageCount > 1 && $enumRevMode)
00101 $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');
00102
00103 if (!is_null($params['diffto'])) {
00104 if ($params['diffto'] == 'cur')
00105 $params['diffto'] = 0;
00106 if ((!ctype_digit($params['diffto']) || $params['diffto'] < 0)
00107 && $params['diffto'] != 'prev' && $params['diffto'] != 'next')
00108 $this->dieUsage('rvdiffto must be set to a non-negative number, "prev", "next" or "cur"', 'diffto');
00109
00110
00111
00112 if ($params['diffto'] != 0) {
00113 $difftoRev = Revision::newFromID($params['diffto']);
00114 if (!$difftoRev)
00115 $this->dieUsageMsg(array('nosuchrevid', $params['diffto']));
00116 if (!$difftoRev->userCan(Revision::DELETED_TEXT)) {
00117 $this->setWarning("Couldn't diff to r{$difftoRev->getID()}: content is hidden");
00118 $params['diffto'] = null;
00119 }
00120 }
00121 }
00122
00123 $this->addTables('revision');
00124 $this->addFields(Revision::selectFields());
00125 $this->addTables('page');
00126 $this->addWhere('page_id = rev_page');
00127
00128 $prop = array_flip($params['prop']);
00129
00130
00131 $this->fld_ids = isset ($prop['ids']);
00132
00133 $this->fld_flags = isset ($prop['flags']);
00134 $this->fld_timestamp = isset ($prop['timestamp']);
00135 $this->fld_comment = isset ($prop['comment']);
00136 $this->fld_size = isset ($prop['size']);
00137 $this->fld_user = isset ($prop['user']);
00138 $this->token = $params['token'];
00139 $this->diffto = $params['diffto'];
00140
00141 if ( !is_null($this->token) || $pageCount > 0) {
00142 $this->addFields( Revision::selectPageFields() );
00143 }
00144
00145 if (isset ($prop['content'])) {
00146
00147
00148 foreach ($pageSet->getGoodTitles() as $title) {
00149 if( !$title->userCanRead() )
00150 $this->dieUsage(
00151 'The current user is not allowed to read ' . $title->getPrefixedText(),
00152 'accessdenied');
00153 }
00154
00155 $this->addTables('text');
00156 $this->addWhere('rev_text_id=old_id');
00157 $this->addFields('old_id');
00158 $this->addFields(Revision::selectTextFields());
00159
00160 $this->fld_content = true;
00161
00162 $this->expandTemplates = $params['expandtemplates'];
00163 $this->generateXML = $params['generatexml'];
00164 if(isset($params['section']))
00165 $this->section = $params['section'];
00166 else
00167 $this->section = false;
00168 }
00169
00170 $userMax = ( $this->fld_content ? ApiBase::LIMIT_SML1 : ApiBase::LIMIT_BIG1 );
00171 $botMax = ( $this->fld_content ? ApiBase::LIMIT_SML2 : ApiBase::LIMIT_BIG2 );
00172 $limit = $params['limit'];
00173 if( $limit == 'max' ) {
00174 $limit = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
00175 $this->getResult()->addValue( 'limits', $this->getModuleName(), $limit );
00176 }
00177
00178 if ($enumRevMode) {
00179
00180
00181 if (!is_null($params['startid']) && !is_null($params['start']))
00182 $this->dieUsage('start and startid cannot be used together', 'badparams');
00183
00184 if (!is_null($params['endid']) && !is_null($params['end']))
00185 $this->dieUsage('end and endid cannot be used together', 'badparams');
00186
00187 if(!is_null($params['user']) && !is_null($params['excludeuser']))
00188 $this->dieUsage('user and excludeuser cannot be used together', 'badparams');
00189
00190
00191
00192
00193
00194
00195
00196
00197 if (is_null($params['startid']) && is_null($params['endid']))
00198 $this->addWhereRange('rev_timestamp', $params['dir'],
00199 $params['start'], $params['end']);
00200 else {
00201 $this->addWhereRange('rev_id', $params['dir'],
00202 $params['startid'], $params['endid']);
00203
00204
00205 $this->addWhereRange('rev_timestamp', $params['dir'],
00206 $params['start'], $params['end'], false);
00207 }
00208
00209
00210 if (is_null($limit))
00211 $limit = 10;
00212 $this->validateLimit('limit', $limit, 1, $userMax, $botMax);
00213
00214
00215 $this->addWhereFld('rev_page', reset(array_keys($pageSet->getGoodTitles())));
00216
00217 if(!is_null($params['user'])) {
00218 $this->addWhereFld('rev_user_text', $params['user']);
00219 } elseif (!is_null($params['excludeuser'])) {
00220 $this->addWhere('rev_user_text != ' .
00221 $this->getDB()->addQuotes($params['excludeuser']));
00222 }
00223 if(!is_null($params['user']) || !is_null($params['excludeuser'])) {
00224
00225 $this->addWhere('rev_deleted & ' . Revision::DELETED_USER . ' = 0');
00226 }
00227 }
00228 elseif ($revCount > 0) {
00229 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
00230 $revs = $pageSet->getRevisionIDs();
00231 if(self::truncateArray($revs, $max))
00232 $this->setWarning("Too many values supplied for parameter 'revids': the limit is $max");
00233
00234
00235 $this->addWhereFld('rev_id', array_keys($revs));
00236
00237 if(!is_null($params['continue']))
00238 $this->addWhere("rev_id >= '" . intval($params['continue']) . "'");
00239 $this->addOption('ORDER BY', 'rev_id');
00240
00241
00242 $limit = $revCount;
00243 }
00244 elseif ($pageCount > 0) {
00245 $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
00246 $titles = $pageSet->getGoodTitles();
00247 if(self::truncateArray($titles, $max))
00248 $this->setWarning("Too many values supplied for parameter 'titles': the limit is $max");
00249
00250
00251
00252 $this->addWhere('page_id=rev_page');
00253 $this->addWhere('page_latest=rev_id');
00254
00255
00256 $this->addWhereFld('page_id', array_keys($titles));
00257
00258 $this->addWhereFld('rev_page', array_keys($titles));
00259
00260 if(!is_null($params['continue']))
00261 {
00262 $cont = explode('|', $params['continue']);
00263 if(count($cont) != 2)
00264 $this->dieUsage("Invalid continue param. You should pass the original " .
00265 "value returned by the previous query", "_badcontinue");
00266 $pageid = intval($cont[0]);
00267 $revid = intval($cont[1]);
00268 $this->addWhere("rev_page > '$pageid' OR " .
00269 "(rev_page = '$pageid' AND " .
00270 "rev_id >= '$revid')");
00271 }
00272 $this->addOption('ORDER BY', 'rev_page, rev_id');
00273
00274
00275 $limit = $pageCount;
00276 } else
00277 ApiBase :: dieDebug(__METHOD__, 'param validation?');
00278
00279 $this->addOption('LIMIT', $limit +1);
00280
00281 $data = array ();
00282 $count = 0;
00283 $res = $this->select(__METHOD__);
00284
00285 $db = $this->getDB();
00286 while ($row = $db->fetchObject($res)) {
00287
00288 if (++ $count > $limit) {
00289
00290 if (!$enumRevMode)
00291 ApiBase :: dieDebug(__METHOD__, 'Got more rows then expected');
00292 $this->setContinueEnumParameter('startid', intval($row->rev_id));
00293 break;
00294 }
00295 $revision = new Revision( $row );
00296
00297 $fit = $this->addPageSubItem($revision->getPage(), $this->extractRowInfo($revision), 'rev');
00298 if(!$fit)
00299 {
00300 if($enumRevMode)
00301 $this->setContinueEnumParameter('startid', intval($row->rev_id));
00302 else if($revCount > 0)
00303 $this->setContinueEnumParameter('continue', intval($row->rev_id));
00304 else
00305 $this->setContinueEnumParameter('continue', intval($row->rev_page) .
00306 '|' . intval($row->rev_id));
00307 break;
00308 }
00309 }
00310 $db->freeResult($res);
00311 }
00312
00313 private function extractRowInfo( $revision ) {
00314 $title = $revision->getTitle();
00315 $vals = array ();
00316
00317 if ($this->fld_ids) {
00318 $vals['revid'] = intval($revision->getId());
00319
00320 }
00321
00322 if ($this->fld_flags && $revision->isMinor())
00323 $vals['minor'] = '';
00324
00325 if ($this->fld_user) {
00326 if ($revision->isDeleted(Revision::DELETED_USER)) {
00327 $vals['userhidden'] = '';
00328 } else {
00329 $vals['user'] = $revision->getUserText();
00330 if (!$revision->getUser())
00331 $vals['anon'] = '';
00332 }
00333 }
00334
00335 if ($this->fld_timestamp) {
00336 $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $revision->getTimestamp());
00337 }
00338
00339 if ($this->fld_size && !is_null($revision->getSize())) {
00340 $vals['size'] = intval($revision->getSize());
00341 }
00342
00343 if ($this->fld_comment) {
00344 if ($revision->isDeleted(Revision::DELETED_COMMENT)) {
00345 $vals['commenthidden'] = '';
00346 } else {
00347 $comment = $revision->getComment();
00348 if (strval($comment) !== '')
00349 $vals['comment'] = $comment;
00350 }
00351 }
00352
00353 if(!is_null($this->token))
00354 {
00355 $tokenFunctions = $this->getTokenFunctions();
00356 foreach($this->token as $t)
00357 {
00358 $val = call_user_func($tokenFunctions[$t], $title->getArticleID(), $title, $revision);
00359 if($val === false)
00360 $this->setWarning("Action '$t' is not allowed for the current user");
00361 else
00362 $vals[$t . 'token'] = $val;
00363 }
00364 }
00365
00366 if ($this->fld_content && !$revision->isDeleted(Revision::DELETED_TEXT)) {
00367 global $wgParser;
00368 $text = $revision->getText();
00369 # Expand templates after getting section content because
00370 # template-added sections don't count and Parser::preprocess()
00371 # will have less input
00372 if ($this->section !== false) {
00373 $text = $wgParser->getSection( $text, $this->section, false);
00374 if($text === false)
00375 $this->dieUsage("There is no section {$this->section} in r".$revision->getId(), 'nosuchsection');
00376 }
00377 if ($this->generateXML) {
00378 $wgParser->startExternalParse( $title, new ParserOptions(), OT_PREPROCESS );
00379 $dom = $wgParser->preprocessToDom( $text );
00380 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
00381 $xml = $dom->saveXML();
00382 } else {
00383 $xml = $dom->__toString();
00384 }
00385 $vals['parsetree'] = $xml;
00386
00387 }
00388 if ($this->expandTemplates) {
00389 $text = $wgParser->preprocess( $text, $title, new ParserOptions() );
00390 }
00391 ApiResult :: setContent($vals, $text);
00392 } else if ($this->fld_content) {
00393 $vals['texthidden'] = '';
00394 }
00395
00396 if (!is_null($this->diffto)) {
00397 global $wgAPIMaxUncachedDiffs;
00398 static $n = 0;
00399 if($n< $wgAPIMaxUncachedDiffs) {
00400 $engine = new DifferenceEngine($title, $revision->getID(), $this->diffto);
00401 $difftext = $engine->getDiffBody();
00402 $vals['diff']['from'] = $engine->getOldid();
00403 $vals['diff']['to'] = $engine->getNewid();
00404 ApiResult::setContent($vals['diff'], $difftext);
00405 if(!$engine->wasCacheHit())
00406 $n++;
00407 } else {
00408 $vals['diff']['notcached'] = '';
00409 }
00410 }
00411 return $vals;
00412 }
00413
00414 public function getAllowedParams() {
00415 return array (
00416 'prop' => array (
00417 ApiBase :: PARAM_ISMULTI => true,
00418 ApiBase :: PARAM_DFLT => 'ids|timestamp|flags|comment|user',
00419 ApiBase :: PARAM_TYPE => array (
00420 'ids',
00421 'flags',
00422 'timestamp',
00423 'user',
00424 'size',
00425 'comment',
00426 'content',
00427 )
00428 ),
00429 'limit' => array (
00430 ApiBase :: PARAM_TYPE => 'limit',
00431 ApiBase :: PARAM_MIN => 1,
00432 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
00433 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
00434 ),
00435 'startid' => array (
00436 ApiBase :: PARAM_TYPE => 'integer'
00437 ),
00438 'endid' => array (
00439 ApiBase :: PARAM_TYPE => 'integer'
00440 ),
00441 'start' => array (
00442 ApiBase :: PARAM_TYPE => 'timestamp'
00443 ),
00444 'end' => array (
00445 ApiBase :: PARAM_TYPE => 'timestamp'
00446 ),
00447 'dir' => array (
00448 ApiBase :: PARAM_DFLT => 'older',
00449 ApiBase :: PARAM_TYPE => array (
00450 'newer',
00451 'older'
00452 )
00453 ),
00454 'user' => array(
00455 ApiBase :: PARAM_TYPE => 'user'
00456 ),
00457 'excludeuser' => array(
00458 ApiBase :: PARAM_TYPE => 'user'
00459 ),
00460 'expandtemplates' => false,
00461 'generatexml' => false,
00462 'section' => null,
00463 'token' => array(
00464 ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions()),
00465 ApiBase :: PARAM_ISMULTI => true
00466 ),
00467 'continue' => null,
00468 'diffto' => null,
00469 );
00470 }
00471
00472 public function getParamDescription() {
00473 return array (
00474 'prop' => 'Which properties to get for each revision.',
00475 'limit' => 'limit how many revisions will be returned (enum)',
00476 'startid' => 'from which revision id to start enumeration (enum)',
00477 'endid' => 'stop revision enumeration on this revid (enum)',
00478 'start' => 'from which revision timestamp to start enumeration (enum)',
00479 'end' => 'enumerate up to this timestamp (enum)',
00480 'dir' => 'direction of enumeration - towards "newer" or "older" revisions (enum)',
00481 'user' => 'only include revisions made by user',
00482 'excludeuser' => 'exclude revisions made by user',
00483 'expandtemplates' => 'expand templates in revision content',
00484 'generatexml' => 'generate XML parse tree for revision content',
00485 'section' => 'only retrieve the content of this section',
00486 'token' => 'Which tokens to obtain for each revision',
00487 'continue' => 'When more results are available, use this to continue',
00488 'diffto' => array('Revision ID to diff each revision to.',
00489 'Use "prev", "next" and "cur" for the previous, next and current revision respectively.'),
00490 );
00491 }
00492
00493 public function getDescription() {
00494 return array (
00495 'Get revision information.',
00496 'This module may be used in several ways:',
00497 ' 1) Get data about a set of pages (last revision), by setting titles or pageids parameter.',
00498 ' 2) Get revisions for one given page, by using titles/pageids with start/end/limit params.',
00499 ' 3) Get data about a set of revisions by setting their IDs with revids parameter.',
00500 'All parameters marked as (enum) may only be used with a single page (#2).'
00501 );
00502 }
00503
00504 protected function getExamples() {
00505 return array (
00506 'Get data with content for the last revision of titles "API" and "Main Page":',
00507 ' api.php?action=query&prop=revisions&titles=API|Main%20Page&rvprop=timestamp|user|comment|content',
00508 'Get last 5 revisions of the "Main Page":',
00509 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment',
00510 'Get first 5 revisions of the "Main Page":',
00511 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer',
00512 'Get first 5 revisions of the "Main Page" made after 2006-05-01:',
00513 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvdir=newer&rvstart=20060501000000',
00514 'Get first 5 revisions of the "Main Page" that were not made made by anonymous user "127.0.0.1"',
00515 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1',
00516 'Get first 5 revisions of the "Main Page" that were made by the user "MediaWiki default"',
00517 ' api.php?action=query&prop=revisions&titles=Main%20Page&rvlimit=5&rvprop=timestamp|user|comment&rvuser=MediaWiki%20default',
00518 );
00519 }
00520
00521 public function getVersion() {
00522 return __CLASS__ . ': $Id: ApiQueryRevisions.php 48642 2009-03-20 20:21:38Z midom $';
00523 }
00524 }