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