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