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