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