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