* API: (bug 15935) Add action=userrights to the API
[lhc/web/wiklou.git] / includes / api / ApiQueryRecentChanges.php
1 <?php
2
3 /*
4 * Created on Oct 19, 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 the recent changes that were done to the wiki.
33 * Various filters are supported.
34 *
35 * @ingroup API
36 */
37 class ApiQueryRecentChanges extends ApiQueryBase {
38
39 public function __construct($query, $moduleName) {
40 parent :: __construct($query, $moduleName, 'rc');
41 }
42
43 private $fld_comment = false, $fld_user = false, $fld_flags = false,
44 $fld_timestamp = false, $fld_title = false, $fld_ids = false,
45 $fld_sizes = false;
46 /**
47 * Get an array mapping token names to their handler functions.
48 * The prototype for a token function is func($pageid, $title, $rc)
49 * it should return a token or false (permission denied)
50 * @return array(tokenname => function)
51 */
52 protected function getTokenFunctions() {
53 // Don't call the hooks twice
54 if(isset($this->tokenFunctions))
55 return $this->tokenFunctions;
56
57 // If we're in JSON callback mode, no tokens can be obtained
58 if(!is_null($this->getMain()->getRequest()->getVal('callback')))
59 return array();
60
61 $this->tokenFunctions = array(
62 'patrol' => array( 'ApiQueryRecentChanges', 'getPatrolToken' )
63 );
64 wfRunHooks('APIQueryRecentChangesTokens', array(&$this->tokenFunctions));
65 return $this->tokenFunctions;
66 }
67
68 public static function getPatrolToken($pageid, $title, $rc)
69 {
70 global $wgUser;
71 if(!$wgUser->useRCPatrol() && !$wgUser->useNPPatrol())
72 return false;
73
74 // The patrol token is always the same, let's exploit that
75 static $cachedPatrolToken = null;
76 if(!is_null($cachedPatrolToken))
77 return $cachedPatrolToken;
78
79 $cachedPatrolToken = $wgUser->editToken();
80 return $cachedPatrolToken;
81 }
82
83 /**
84 * Generates and outputs the result of this query based upon the provided parameters.
85 */
86 public function execute() {
87 /* Get the parameters of the request. */
88 $params = $this->extractRequestParams();
89
90 /* Build our basic query. Namely, something along the lines of:
91 * SELECT * FROM recentchanges WHERE rc_timestamp > $start
92 * AND rc_timestamp < $end AND rc_namespace = $namespace
93 * AND rc_deleted = '0'
94 */
95 $db = $this->getDB();
96 $this->addTables('recentchanges');
97 $this->addOption('USE INDEX', array('recentchanges' => 'rc_timestamp'));
98 $this->addWhereRange('rc_timestamp', $params['dir'], $params['start'], $params['end']);
99 $this->addWhereFld('rc_namespace', $params['namespace']);
100 $this->addWhereFld('rc_deleted', 0);
101
102 if(!is_null($params['type']))
103 $this->addWhereFld('rc_type', $this->parseRCType($params['type']));
104
105 if (!is_null($params['show'])) {
106 $show = array_flip($params['show']);
107
108 /* Check for conflicting parameters. */
109 if ((isset ($show['minor']) && isset ($show['!minor']))
110 || (isset ($show['bot']) && isset ($show['!bot']))
111 || (isset ($show['anon']) && isset ($show['!anon']))
112 || (isset ($show['redirect']) && isset ($show['!redirect']))
113 || (isset ($show['patrolled']) && isset ($show['!patrolled']))) {
114
115 $this->dieUsage("Incorrect parameter - mutually exclusive values may not be supplied", 'show');
116 }
117
118 // Check permissions
119 global $wgUser;
120 if((isset($show['patrolled']) || isset($show['!patrolled'])) && !$wgUser->useRCPatrol() && !$wgUser->useNPPatrol())
121 $this->dieUsage("You need the patrol right to request the patrolled flag", 'permissiondenied');
122
123 /* Add additional conditions to query depending upon parameters. */
124 $this->addWhereIf('rc_minor = 0', isset ($show['!minor']));
125 $this->addWhereIf('rc_minor != 0', isset ($show['minor']));
126 $this->addWhereIf('rc_bot = 0', isset ($show['!bot']));
127 $this->addWhereIf('rc_bot != 0', isset ($show['bot']));
128 $this->addWhereIf('rc_user = 0', isset ($show['anon']));
129 $this->addWhereIf('rc_user != 0', isset ($show['!anon']));
130 $this->addWhereIf('rc_patrolled = 0', isset($show['!patrolled']));
131 $this->addWhereIf('rc_patrolled != 0', isset($show['patrolled']));
132 $this->addWhereIf('page_is_redirect = 1', isset ($show['redirect']));
133 // Don't throw log entries out the window here
134 $this->addWhereIf('page_is_redirect = 0 OR page_is_redirect IS NULL', isset ($show['!redirect']));
135 }
136
137 /* Add the fields we're concerned with to out query. */
138 $this->addFields(array (
139 'rc_timestamp',
140 'rc_namespace',
141 'rc_title',
142 'rc_cur_id',
143 'rc_type',
144 'rc_moved_to_ns',
145 'rc_moved_to_title'
146 ));
147
148 /* Determine what properties we need to display. */
149 if (!is_null($params['prop'])) {
150 $prop = array_flip($params['prop']);
151
152 /* Set up internal members based upon params. */
153 $this->fld_comment = isset ($prop['comment']);
154 $this->fld_user = isset ($prop['user']);
155 $this->fld_flags = isset ($prop['flags']);
156 $this->fld_timestamp = isset ($prop['timestamp']);
157 $this->fld_title = isset ($prop['title']);
158 $this->fld_ids = isset ($prop['ids']);
159 $this->fld_sizes = isset ($prop['sizes']);
160 $this->fld_redirect = isset($prop['redirect']);
161 $this->fld_patrolled = isset($prop['patrolled']);
162 $this->fld_loginfo = isset($prop['loginfo']);
163
164 global $wgUser;
165 if($this->fld_patrolled && !$wgUser->useRCPatrol() && !$wgUser->useNPPatrol())
166 $this->dieUsage("You need the patrol right to request the patrolled flag", 'permissiondenied');
167
168 /* Add fields to our query if they are specified as a needed parameter. */
169 $this->addFieldsIf('rc_id', $this->fld_ids);
170 $this->addFieldsIf('rc_this_oldid', $this->fld_ids);
171 $this->addFieldsIf('rc_last_oldid', $this->fld_ids);
172 $this->addFieldsIf('rc_comment', $this->fld_comment);
173 $this->addFieldsIf('rc_user', $this->fld_user);
174 $this->addFieldsIf('rc_user_text', $this->fld_user);
175 $this->addFieldsIf('rc_minor', $this->fld_flags);
176 $this->addFieldsIf('rc_bot', $this->fld_flags);
177 $this->addFieldsIf('rc_new', $this->fld_flags);
178 $this->addFieldsIf('rc_old_len', $this->fld_sizes);
179 $this->addFieldsIf('rc_new_len', $this->fld_sizes);
180 $this->addFieldsIf('rc_patrolled', $this->fld_patrolled);
181 $this->addFieldsIf('rc_logid', $this->fld_loginfo);
182 $this->addFieldsIf('rc_log_type', $this->fld_loginfo);
183 $this->addFieldsIf('rc_log_action', $this->fld_loginfo);
184 $this->addFieldsIf('rc_params', $this->fld_loginfo);
185 if($this->fld_redirect || isset($show['redirect']) || isset($show['!redirect']))
186 {
187 $this->addTables('page');
188 $this->addJoinConds(array('page' => array('LEFT JOIN', array('rc_namespace=page_namespace', 'rc_title=page_title'))));
189 $this->addFields('page_is_redirect');
190 }
191 }
192 $this->token = $params['token'];
193 $this->addOption('LIMIT', $params['limit'] +1);
194
195 $count = 0;
196 /* Perform the actual query. */
197 $db = $this->getDB();
198 $res = $this->select(__METHOD__);
199
200 /* Iterate through the rows, adding data extracted from them to our query result. */
201 while ($row = $db->fetchObject($res)) {
202 if (++ $count > $params['limit']) {
203 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
204 $this->setContinueEnumParameter('start', wfTimestamp(TS_ISO_8601, $row->rc_timestamp));
205 break;
206 }
207
208 /* Extract the data from a single row. */
209 $vals = $this->extractRowInfo($row);
210
211 /* Add that row's data to our final output. */
212 if(!$vals)
213 continue;
214 $fit = $this->getResult()->addValue(array('query', $this->getModuleName()), null, $vals);
215 if(!$fit)
216 {
217 $this->setContinueEnumParameter('start', wfTimestamp(TS_ISO_8601, $row->rc_timestamp));
218 break;
219 }
220 }
221
222 $db->freeResult($res);
223
224 /* Format the result */
225 $this->getResult()->setIndexedTagName_internal(array('query', $this->getModuleName()), 'rc');
226 }
227
228 /**
229 * Extracts from a single sql row the data needed to describe one recent change.
230 *
231 * @param $row The row from which to extract the data.
232 * @return An array mapping strings (descriptors) to their respective string values.
233 * @access private
234 */
235 private function extractRowInfo($row) {
236 /* If page was moved somewhere, get the title of the move target. */
237 $movedToTitle = false;
238 if (isset($row->rc_moved_to_title) && $row->rc_moved_to_title !== '')
239 $movedToTitle = Title :: makeTitle($row->rc_moved_to_ns, $row->rc_moved_to_title);
240
241 /* Determine the title of the page that has been changed. */
242 $title = Title :: makeTitle($row->rc_namespace, $row->rc_title);
243
244 /* Our output data. */
245 $vals = array ();
246
247 $type = intval ( $row->rc_type );
248
249 /* Determine what kind of change this was. */
250 switch ( $type ) {
251 case RC_EDIT: $vals['type'] = 'edit'; break;
252 case RC_NEW: $vals['type'] = 'new'; break;
253 case RC_MOVE: $vals['type'] = 'move'; break;
254 case RC_LOG: $vals['type'] = 'log'; break;
255 case RC_MOVE_OVER_REDIRECT: $vals['type'] = 'move over redirect'; break;
256 default: $vals['type'] = $type;
257 }
258
259 /* Create a new entry in the result for the title. */
260 if ($this->fld_title) {
261 ApiQueryBase :: addTitleInfo($vals, $title);
262 if ($movedToTitle)
263 ApiQueryBase :: addTitleInfo($vals, $movedToTitle, "new_");
264 }
265
266 /* Add ids, such as rcid, pageid, revid, and oldid to the change's info. */
267 if ($this->fld_ids) {
268 $vals['rcid'] = intval($row->rc_id);
269 $vals['pageid'] = intval($row->rc_cur_id);
270 $vals['revid'] = intval($row->rc_this_oldid);
271 $vals['old_revid'] = intval( $row->rc_last_oldid );
272 }
273
274 /* Add user data and 'anon' flag, if use is anonymous. */
275 if ($this->fld_user) {
276 $vals['user'] = $row->rc_user_text;
277 if(!$row->rc_user)
278 $vals['anon'] = '';
279 }
280
281 /* Add flags, such as new, minor, bot. */
282 if ($this->fld_flags) {
283 if ($row->rc_bot)
284 $vals['bot'] = '';
285 if ($row->rc_new)
286 $vals['new'] = '';
287 if ($row->rc_minor)
288 $vals['minor'] = '';
289 }
290
291 /* Add sizes of each revision. (Only available on 1.10+) */
292 if ($this->fld_sizes) {
293 $vals['oldlen'] = intval($row->rc_old_len);
294 $vals['newlen'] = intval($row->rc_new_len);
295 }
296
297 /* Add the timestamp. */
298 if ($this->fld_timestamp)
299 $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $row->rc_timestamp);
300
301 /* Add edit summary / log summary. */
302 if ($this->fld_comment && isset($row->rc_comment)) {
303 $vals['comment'] = $row->rc_comment;
304 }
305
306 if ($this->fld_redirect)
307 if($row->page_is_redirect)
308 $vals['redirect'] = '';
309
310 /* Add the patrolled flag */
311 if ($this->fld_patrolled && $row->rc_patrolled == 1)
312 $vals['patrolled'] = '';
313
314 if ($this->fld_loginfo && $row->rc_type == RC_LOG) {
315 $vals['logid'] = intval($row->rc_logid);
316 $vals['logtype'] = $row->rc_log_type;
317 $vals['logaction'] = $row->rc_log_action;
318 ApiQueryLogEvents::addLogParams($this->getResult(),
319 $vals, $row->rc_params,
320 $row->rc_log_type, $row->rc_timestamp);
321 }
322
323 if(!is_null($this->token))
324 {
325 $tokenFunctions = $this->getTokenFunctions();
326 foreach($this->token as $t)
327 {
328 $val = call_user_func($tokenFunctions[$t], $row->rc_cur_id,
329 $title, RecentChange::newFromRow($row));
330 if($val === false)
331 $this->setWarning("Action '$t' is not allowed for the current user");
332 else
333 $vals[$t . 'token'] = $val;
334 }
335 }
336
337 return $vals;
338 }
339
340 private function parseRCType($type)
341 {
342 if(is_array($type))
343 {
344 $retval = array();
345 foreach($type as $t)
346 $retval[] = $this->parseRCType($t);
347 return $retval;
348 }
349 switch($type)
350 {
351 case 'edit': return RC_EDIT;
352 case 'new': return RC_NEW;
353 case 'log': return RC_LOG;
354 }
355 }
356
357 public function getAllowedParams() {
358 return array (
359 'start' => array (
360 ApiBase :: PARAM_TYPE => 'timestamp'
361 ),
362 'end' => array (
363 ApiBase :: PARAM_TYPE => 'timestamp'
364 ),
365 'dir' => array (
366 ApiBase :: PARAM_DFLT => 'older',
367 ApiBase :: PARAM_TYPE => array (
368 'newer',
369 'older'
370 )
371 ),
372 'namespace' => array (
373 ApiBase :: PARAM_ISMULTI => true,
374 ApiBase :: PARAM_TYPE => 'namespace'
375 ),
376 'prop' => array (
377 ApiBase :: PARAM_ISMULTI => true,
378 ApiBase :: PARAM_DFLT => 'title|timestamp|ids',
379 ApiBase :: PARAM_TYPE => array (
380 'user',
381 'comment',
382 'flags',
383 'timestamp',
384 'title',
385 'ids',
386 'sizes',
387 'redirect',
388 'patrolled',
389 'loginfo',
390 )
391 ),
392 'token' => array(
393 ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions()),
394 ApiBase :: PARAM_ISMULTI => true
395 ),
396 'show' => array (
397 ApiBase :: PARAM_ISMULTI => true,
398 ApiBase :: PARAM_TYPE => array (
399 'minor',
400 '!minor',
401 'bot',
402 '!bot',
403 'anon',
404 '!anon',
405 'redirect',
406 '!redirect',
407 'patrolled',
408 '!patrolled'
409 )
410 ),
411 'limit' => array (
412 ApiBase :: PARAM_DFLT => 10,
413 ApiBase :: PARAM_TYPE => 'limit',
414 ApiBase :: PARAM_MIN => 1,
415 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
416 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
417 ),
418 'type' => array (
419 ApiBase :: PARAM_ISMULTI => true,
420 ApiBase :: PARAM_TYPE => array (
421 'edit',
422 'new',
423 'log'
424 )
425 )
426 );
427 }
428
429 public function getParamDescription() {
430 return array (
431 'start' => 'The timestamp to start enumerating from.',
432 'end' => 'The timestamp to end enumerating.',
433 'dir' => 'In which direction to enumerate.',
434 'namespace' => 'Filter log entries to only this namespace(s)',
435 'prop' => 'Include additional pieces of information',
436 'token' => 'Which tokens to obtain for each change',
437 'show' => array (
438 'Show only items that meet this criteria.',
439 'For example, to see only minor edits done by logged-in users, set show=minor|!anon'
440 ),
441 'type' => 'Which types of changes to show.',
442 'limit' => 'How many total changes to return.'
443 );
444 }
445
446 public function getDescription() {
447 return 'Enumerate recent changes';
448 }
449
450 protected function getExamples() {
451 return array (
452 'api.php?action=query&list=recentchanges'
453 );
454 }
455
456 public function getVersion() {
457 return __CLASS__ . ': $Id$';
458 }
459 }