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