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