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