]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blobdiff - includes/api/ApiQueryRevisions.php
MediaWiki 1.15.0
[autoinstallsdev/mediawiki.git] / includes / api / ApiQueryRevisions.php
index 2672478ba51d882d37fe99ae82bd82139eb8f919..ca9152adc940a80c8e9e3e0c0525a67507f58f4b 100644 (file)
@@ -30,10 +30,10 @@ if (!defined('MEDIAWIKI')) {
 
 /**
  * A query action to enumerate revisions of a given page, or show top revisions of multiple pages.
- * Various pieces of information may be shown - flags, comments, and the actual wiki markup of the rev. 
- * In the enumeration mode, ranges of revisions may be requested and filtered. 
- * 
- * @addtogroup API
+ * Various pieces of information may be shown - flags, comments, and the actual wiki markup of the rev.
+ * In the enumeration mode, ranges of revisions may be requested and filtered.
+ *
+ * @ingroup API
  */
 class ApiQueryRevisions extends ApiQueryBase {
 
@@ -44,15 +44,47 @@ class ApiQueryRevisions extends ApiQueryBase {
        private $fld_ids = false, $fld_flags = false, $fld_timestamp = false, $fld_size = false,
                        $fld_comment = false, $fld_user = false, $fld_content = false;
 
+       protected function getTokenFunctions() {
+               // tokenname => function
+               // function prototype is func($pageid, $title, $rev)
+               // should return token or false
+
+               // Don't call the hooks twice
+               if(isset($this->tokenFunctions))
+                       return $this->tokenFunctions;
+
+               // If we're in JSON callback mode, no tokens can be obtained
+               if(!is_null($this->getMain()->getRequest()->getVal('callback')))
+                       return array();
+
+               $this->tokenFunctions = array(
+                       'rollback' => array( 'ApiQueryRevisions', 'getRollbackToken' )
+               );
+               wfRunHooks('APIQueryRevisionsTokens', array(&$this->tokenFunctions));
+               return $this->tokenFunctions;
+       }
+
+       public static function getRollbackToken($pageid, $title, $rev)
+       {
+               global $wgUser;
+               if(!$wgUser->isAllowed('rollback'))
+                       return false;
+               return $wgUser->editToken(array($title->getPrefixedText(),
+                                               $rev->getUserText()));
+       }
+
        public function execute() {
-               $limit = $startid = $endid = $start = $end = $dir = $prop = $user = $excludeuser = null;
-               extract($this->extractRequestParams());
+               $params = $this->extractRequestParams(false);
 
                // If any of those parameters are used, work in 'enumeration' mode.
                // Enum mode can only be used when exactly one page is provided.
-               // Enumerating revisions on multiple pages make it extremelly 
-               // difficult to manage continuations and require additional sql indexes  
-               $enumRevMode = (!is_null($user) || !is_null($excludeuser) || !is_null($limit) || !is_null($startid) || !is_null($endid) || $dir === 'newer' || !is_null($start) || !is_null($end));
+               // Enumerating revisions on multiple pages make it extremely
+               // difficult to manage continuations and require additional SQL indexes
+               $enumRevMode = (!is_null($params['user']) || !is_null($params['excludeuser']) ||
+                               !is_null($params['limit']) || !is_null($params['startid']) ||
+                               !is_null($params['endid']) || $params['dir'] === 'newer' ||
+                               !is_null($params['start']) || !is_null($params['end']));
+
 
                $pageSet = $this->getPageSet();
                $pageCount = $pageSet->getGoodTitleCount();
@@ -66,30 +98,50 @@ class ApiQueryRevisions extends ApiQueryBase {
                        $this->dieUsage('The revids= parameter may not be used with the list options (limit, startid, endid, dirNewer, start, end).', 'revids');
 
                if ($pageCount > 1 && $enumRevMode)
-                       $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');
+                       $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');
+
+               if (!is_null($params['diffto'])) {
+                       if ($params['diffto'] == 'cur')
+                               $params['diffto'] = 0;
+                       if ((!ctype_digit($params['diffto']) || $params['diffto'] < 0) 
+                                       && $params['diffto'] != 'prev' && $params['diffto'] != 'next')
+                               $this->dieUsage('rvdiffto must be set to a non-negative number, "prev", "next" or "cur"', 'diffto');
+                       // Check whether the revision exists and is readable,
+                       // DifferenceEngine returns a rather ambiguous empty
+                       // string if that's not the case
+                       if ($params['diffto'] != 0) {
+                               $difftoRev = Revision::newFromID($params['diffto']);
+                               if (!$difftoRev)
+                                       $this->dieUsageMsg(array('nosuchrevid', $params['diffto']));
+                               if (!$difftoRev->userCan(Revision::DELETED_TEXT)) {
+                                       $this->setWarning("Couldn't diff to r{$difftoRev->getID()}: content is hidden");
+                                       $params['diffto'] = null;
+                               }
+                       }
+               }
 
                $this->addTables('revision');
-               $this->addWhere('rev_deleted=0');
-
-               $prop = array_flip($prop);
+               $this->addFields(Revision::selectFields());
+               $this->addTables('page');
+               $this->addWhere('page_id = rev_page');
 
-               // These field are needed regardless of the client requesting them
-               $this->addFields('rev_id');
-               $this->addFields('rev_page');
+               $prop = array_flip($params['prop']);
 
                // Optional fields
                $this->fld_ids = isset ($prop['ids']);
                // $this->addFieldsIf('rev_text_id', $this->fld_ids); // should this be exposed?
-               $this->fld_flags = $this->addFieldsIf('rev_minor_edit', isset ($prop['flags']));
-               $this->fld_timestamp = $this->addFieldsIf('rev_timestamp', isset ($prop['timestamp']));
-               $this->fld_comment = $this->addFieldsIf('rev_comment', isset ($prop['comment']));
-               $this->fld_size = $this->addFieldsIf('rev_len', isset ($prop['size']));
-
-               if (isset ($prop['user'])) {
-                       $this->addFields('rev_user');
-                       $this->addFields('rev_user_text');
-                       $this->fld_user = true;
+               $this->fld_flags = isset ($prop['flags']);
+               $this->fld_timestamp = isset ($prop['timestamp']);
+               $this->fld_comment = isset ($prop['comment']);
+               $this->fld_size = isset ($prop['size']);
+               $this->fld_user = isset ($prop['user']);
+               $this->token = $params['token'];
+               $this->diffto = $params['diffto'];
+
+               if ( !is_null($this->token) || $pageCount > 0) {
+                       $this->addFields( Revision::selectPageFields() );
                }
+
                if (isset ($prop['content'])) {
 
                        // For each page we will request, the user must have read rights for that page
@@ -103,37 +155,56 @@ class ApiQueryRevisions extends ApiQueryBase {
                        $this->addTables('text');
                        $this->addWhere('rev_text_id=old_id');
                        $this->addFields('old_id');
-                       $this->addFields('old_text');
-                       $this->addFields('old_flags');
+                       $this->addFields(Revision::selectTextFields());
+
                        $this->fld_content = true;
+
+                       $this->expandTemplates = $params['expandtemplates'];
+                       $this->generateXML = $params['generatexml'];
+                       if(isset($params['section']))
+                               $this->section = $params['section'];
+                       else
+                               $this->section = false;
                }
 
-               $userMax = ($this->fld_content ? 50 : 500);
-               $botMax = ($this->fld_content ? 200 : 10000);
+               $userMax = ( $this->fld_content ? ApiBase::LIMIT_SML1 : ApiBase::LIMIT_BIG1 );
+               $botMax  = ( $this->fld_content ? ApiBase::LIMIT_SML2 : ApiBase::LIMIT_BIG2 );
+               $limit = $params['limit'];
+               if( $limit == 'max' ) {
+                       $limit = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
+                       $this->getResult()->addValue( 'limits', $this->getModuleName(), $limit );
+               }
 
                if ($enumRevMode) {
 
-                       // This is mostly to prevent parameter errors (and optimize sql?)
-                       if (!is_null($startid) && !is_null($start))
+                       // This is mostly to prevent parameter errors (and optimize SQL?)
+                       if (!is_null($params['startid']) && !is_null($params['start']))
                                $this->dieUsage('start and startid cannot be used together', 'badparams');
 
-                       if (!is_null($endid) && !is_null($end))
+                       if (!is_null($params['endid']) && !is_null($params['end']))
                                $this->dieUsage('end and endid cannot be used together', 'badparams');
 
-                       if(!is_null($user) && !is_null( $excludeuser))
-                               $this->dieUsage('user and excludeuser cannot be used together', 'badparams');                   
-                       
+                       if(!is_null($params['user']) && !is_null($params['excludeuser']))
+                               $this->dieUsage('user and excludeuser cannot be used together', 'badparams');
+
                        // This code makes an assumption that sorting by rev_id and rev_timestamp produces
                        // the same result. This way users may request revisions starting at a given time,
                        // but to page through results use the rev_id returned after each page.
-                       // Switching to rev_id removes the potential problem of having more than 
-                       // one row with the same timestamp for the same page. 
+                       // Switching to rev_id removes the potential problem of having more than
+                       // one row with the same timestamp for the same page.
                        // The order needs to be the same as start parameter to avoid SQL filesort.
 
-                       if (is_null($startid))
-                               $this->addWhereRange('rev_timestamp', $dir, $start, $end);
-                       else
-                               $this->addWhereRange('rev_id', $dir, $startid, $endid);
+                       if (is_null($params['startid']) && is_null($params['endid']))
+                               $this->addWhereRange('rev_timestamp', $params['dir'],
+                                       $params['start'], $params['end']);
+                       else {
+                               $this->addWhereRange('rev_id', $params['dir'],
+                                       $params['startid'], $params['endid']);
+                               // One of start and end can be set
+                               // If neither is set, this does nothing
+                               $this->addWhereRange('rev_timestamp', $params['dir'],
+                                       $params['start'], $params['end'], false);
+                       }
 
                        // must manually initialize unset limit
                        if (is_null($limit))
@@ -141,33 +212,64 @@ class ApiQueryRevisions extends ApiQueryBase {
                        $this->validateLimit('limit', $limit, 1, $userMax, $botMax);
 
                        // There is only one ID, use it
-                       $this->addWhereFld('rev_page', current(array_keys($pageSet->getGoodTitles())));
-                       
-                       if(!is_null($user)) {
-                               $this->addWhereFld('rev_user_text', $user);
-                       } elseif (!is_null( $excludeuser)) {
-                               $this->addWhere('rev_user_text != ' . $this->getDB()->addQuotes($excludeuser));
+                       $this->addWhereFld('rev_page', reset(array_keys($pageSet->getGoodTitles())));
+
+                       if(!is_null($params['user'])) {
+                               $this->addWhereFld('rev_user_text', $params['user']);
+                       } elseif (!is_null($params['excludeuser'])) {
+                               $this->addWhere('rev_user_text != ' .
+                                       $this->getDB()->addQuotes($params['excludeuser']));
+                       }
+                       if(!is_null($params['user']) || !is_null($params['excludeuser'])) {
+                               // Paranoia: avoid brute force searches (bug 17342)
+                               $this->addWhere('rev_deleted & ' . Revision::DELETED_USER . ' = 0');
                        }
                }
                elseif ($revCount > 0) {
-                       $this->validateLimit('rev_count', $revCount, 1, $userMax, $botMax);
+                       $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
+                       $revs = $pageSet->getRevisionIDs();
+                       if(self::truncateArray($revs, $max))
+                               $this->setWarning("Too many values supplied for parameter 'revids': the limit is $max"); 
 
                        // Get all revision IDs
-                       $this->addWhereFld('rev_id', array_keys($pageSet->getRevisionIDs()));
+                       $this->addWhereFld('rev_id', array_keys($revs));
+
+                       if(!is_null($params['continue']))
+                               $this->addWhere("rev_id >= '" . intval($params['continue']) . "'");
+                       $this->addOption('ORDER BY', 'rev_id');
 
                        // assumption testing -- we should never get more then $revCount rows.
                        $limit = $revCount;
                }
                elseif ($pageCount > 0) {
+                       $max = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
+                       $titles = $pageSet->getGoodTitles();
+                       if(self::truncateArray($titles, $max))
+                               $this->setWarning("Too many values supplied for parameter 'titles': the limit is $max");
+                       
                        // When working in multi-page non-enumeration mode,
                        // limit to the latest revision only
-                       $this->addTables('page');
                        $this->addWhere('page_id=rev_page');
                        $this->addWhere('page_latest=rev_id');
-                       $this->validateLimit('page_count', $pageCount, 1, $userMax, $botMax);
-
+                       
                        // Get all page IDs
-                       $this->addWhereFld('page_id', array_keys($pageSet->getGoodTitles()));
+                       $this->addWhereFld('page_id', array_keys($titles));
+                       // Every time someone relies on equality propagation, god kills a kitten :)
+                       $this->addWhereFld('rev_page', array_keys($titles));
+                       
+                       if(!is_null($params['continue']))
+                       {
+                               $cont = explode('|', $params['continue']);
+                               if(count($cont) != 2)
+                                       $this->dieUsage("Invalid continue param. You should pass the original " .
+                                                       "value returned by the previous query", "_badcontinue");
+                               $pageid = intval($cont[0]);
+                               $revid = intval($cont[1]);
+                               $this->addWhere("rev_page > '$pageid' OR " .
+                                               "(rev_page = '$pageid' AND " .
+                                               "rev_id >= '$revid')");
+                       }
+                       $this->addOption('ORDER BY', 'rev_page, rev_id');
 
                        // assumption testing -- we should never get more then $pageCount rows.
                        $limit = $pageCount;
@@ -190,68 +292,126 @@ class ApiQueryRevisions extends ApiQueryBase {
                                $this->setContinueEnumParameter('startid', intval($row->rev_id));
                                break;
                        }
-
-                       $this->getResult()->addValue(
-                               array (
-                                       'query',
-                                       'pages',
-                                       intval($row->rev_page),
-                                       'revisions'),
-                               null,
-                               $this->extractRowInfo($row));
-               }
-               $db->freeResult($res);
-
-               // Ensure that all revisions are shown as '<rev>' elements
-               $result = $this->getResult();
-               if ($result->getIsRawMode()) {
-                       $data =& $result->getData();
-                       foreach ($data['query']['pages'] as & $page) {
-                               if (is_array($page) && array_key_exists('revisions', $page)) {
-                                       $result->setIndexedTagName($page['revisions'], 'rev');
-                               }
+                       $revision = new Revision( $row );
+                       //
+                       $fit = $this->addPageSubItem($revision->getPage(), $this->extractRowInfo($revision), 'rev');
+                       if(!$fit)
+                       {
+                               if($enumRevMode)
+                                       $this->setContinueEnumParameter('startid', intval($row->rev_id));
+                               else if($revCount > 0)
+                                       $this->setContinueEnumParameter('continue', intval($row->rev_id));
+                               else
+                                       $this->setContinueEnumParameter('continue', intval($row->rev_page) .
+                                               '|' . intval($row->rev_id));
+                               break;
                        }
                }
+               $db->freeResult($res);
        }
 
-       private function extractRowInfo($row) {
-
+       private function extractRowInfo( $revision ) {
+               $title = $revision->getTitle();
                $vals = array ();
 
                if ($this->fld_ids) {
-                       $vals['revid'] = intval($row->rev_id);
+                       $vals['revid'] = intval($revision->getId());
                        // $vals['oldid'] = intval($row->rev_text_id);  // todo: should this be exposed?
                }
-               
-               if ($this->fld_flags && $row->rev_minor_edit)
+
+               if ($this->fld_flags && $revision->isMinor())
                        $vals['minor'] = '';
 
                if ($this->fld_user) {
-                       $vals['user'] = $row->rev_user_text;
-                       if (!$row->rev_user)
-                               $vals['anon'] = '';
+                       if ($revision->isDeleted(Revision::DELETED_USER)) {
+                               $vals['userhidden'] = '';
+                       } else {
+                               $vals['user'] = $revision->getUserText();
+                               if (!$revision->getUser())
+                                       $vals['anon'] = '';
+                       }
                }
 
                if ($this->fld_timestamp) {
-                       $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $row->rev_timestamp);
+                       $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $revision->getTimestamp());
                }
-               
-               if ($this->fld_size && !is_null($row->rev_len)) {
-                       $vals['size'] = intval($row->rev_len);
+
+               if ($this->fld_size && !is_null($revision->getSize())) {
+                       $vals['size'] = intval($revision->getSize());
                }
 
-               if ($this->fld_comment && !empty ($row->rev_comment)) {
-                       $vals['comment'] = $row->rev_comment;
+               if ($this->fld_comment) {
+                       if ($revision->isDeleted(Revision::DELETED_COMMENT)) {
+                               $vals['commenthidden'] = '';
+                       } else {
+                               $comment = $revision->getComment();
+                               if (strval($comment) !== '')
+                                       $vals['comment'] = $comment;
+                       }
+               }       
+
+               if(!is_null($this->token))
+               {
+                       $tokenFunctions = $this->getTokenFunctions();
+                       foreach($this->token as $t)
+                       {
+                               $val = call_user_func($tokenFunctions[$t], $title->getArticleID(), $title, $revision);
+                               if($val === false)
+                                       $this->setWarning("Action '$t' is not allowed for the current user");
+                               else
+                                       $vals[$t . 'token'] = $val;
+                       }
                }
                
-               if ($this->fld_content) {
-                       ApiResult :: setContent($vals, Revision :: getRevisionText($row));
+               if ($this->fld_content && !$revision->isDeleted(Revision::DELETED_TEXT)) {
+                       global $wgParser;
+                       $text = $revision->getText();
+                       # Expand templates after getting section content because
+                       # template-added sections don't count and Parser::preprocess()
+                       # will have less input
+                       if ($this->section !== false) {
+                               $text = $wgParser->getSection( $text, $this->section, false);
+                               if($text === false)
+                                       $this->dieUsage("There is no section {$this->section} in r".$revision->getId(), 'nosuchsection');
+                       }
+                       if ($this->generateXML) {
+                               $wgParser->startExternalParse( $title, new ParserOptions(), OT_PREPROCESS );
+                               $dom = $wgParser->preprocessToDom( $text );
+                               if ( is_callable( array( $dom, 'saveXML' ) ) ) {
+                                       $xml = $dom->saveXML();
+                               } else {
+                                       $xml = $dom->__toString();
+                               }
+                               $vals['parsetree'] = $xml;
+                               
+                       }
+                       if ($this->expandTemplates) {
+                               $text = $wgParser->preprocess( $text, $title, new ParserOptions() );
+                       }
+                       ApiResult :: setContent($vals, $text);
+               } else if ($this->fld_content) {
+                       $vals['texthidden'] = '';
+               }
+
+               if (!is_null($this->diffto)) {
+                       global $wgAPIMaxUncachedDiffs;
+                       static $n = 0; // Numer of uncached diffs we've had
+                       if($n< $wgAPIMaxUncachedDiffs) {
+                               $engine = new DifferenceEngine($title, $revision->getID(), $this->diffto);
+                               $difftext = $engine->getDiffBody();
+                               $vals['diff']['from'] = $engine->getOldid();
+                               $vals['diff']['to'] = $engine->getNewid();
+                               ApiResult::setContent($vals['diff'], $difftext);
+                               if(!$engine->wasCacheHit())
+                                       $n++;
+                       } else {
+                               $vals['diff']['notcached'] = '';
+                       }
                }
-               
                return $vals;
        }
 
-       protected function getAllowedParams() {
+       public function getAllowedParams() {
                return array (
                        'prop' => array (
                                ApiBase :: PARAM_ISMULTI => true,
@@ -269,8 +429,8 @@ class ApiQueryRevisions extends ApiQueryBase {
                        'limit' => array (
                                ApiBase :: PARAM_TYPE => 'limit',
                                ApiBase :: PARAM_MIN => 1,
-                               ApiBase :: PARAM_MAX => ApiBase :: LIMIT_SML1,
-                               ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_SML2
+                               ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
+                               ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
                        ),
                        'startid' => array (
                                ApiBase :: PARAM_TYPE => 'integer'
@@ -296,11 +456,20 @@ class ApiQueryRevisions extends ApiQueryBase {
                        ),
                        'excludeuser' => array(
                                ApiBase :: PARAM_TYPE => 'user'
-                       )
+                       ),
+                       'expandtemplates' => false,
+                       'generatexml' => false,
+                       'section' => null,
+                       'token' => array(
+                               ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions()),
+                               ApiBase :: PARAM_ISMULTI => true
+                       ),
+                       'continue' => null,
+                       'diffto' => null,
                );
        }
 
-       protected function getParamDescription() {
+       public function getParamDescription() {
                return array (
                        'prop' => 'Which properties to get for each revision.',
                        'limit' => 'limit how many revisions will be returned (enum)',
@@ -311,10 +480,17 @@ class ApiQueryRevisions extends ApiQueryBase {
                        'dir' => 'direction of enumeration - towards "newer" or "older" revisions (enum)',
                        'user' => 'only include revisions made by user',
                        'excludeuser' => 'exclude revisions made by user',
+                       'expandtemplates' => 'expand templates in revision content',
+                       'generatexml' => 'generate XML parse tree for revision content',
+                       'section' => 'only retrieve the content of this section',
+                       'token' => 'Which tokens to obtain for each revision',
+                       'continue' => 'When more results are available, use this to continue',
+                       'diffto' => array('Revision ID to diff each revision to.',
+                               'Use "prev", "next" and "cur" for the previous, next and current revision respectively.'),
                );
        }
 
-       protected function getDescription() {
+       public function getDescription() {
                return array (
                        'Get revision information.',
                        'This module may be used in several ways:',
@@ -343,7 +519,6 @@ class ApiQueryRevisions extends ApiQueryBase {
        }
 
        public function getVersion() {
-               return __CLASS__ . ': $Id: ApiQueryRevisions.php 25407 2007-09-02 14:00:11Z tstarling $';
+               return __CLASS__ . ': $Id: ApiQueryRevisions.php 48642 2009-03-20 20:21:38Z midom $';
        }
 }
-