]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/api/ApiQueryRecentChanges.php
MediaWiki 1.14.0
[autoinstalls/mediawiki.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                 /* Get the parameters of the request. */
87                 $params = $this->extractRequestParams();
88
89                 /* Build our basic query. Namely, something along the lines of:
90                  * SELECT * FROM recentchanges WHERE rc_timestamp > $start
91                  *              AND rc_timestamp < $end AND rc_namespace = $namespace
92                  *              AND rc_deleted = '0'
93                  */
94                 $db = $this->getDB();
95                 $this->addTables('recentchanges');
96                 $this->addOption('USE INDEX', array('recentchanges' => 'rc_timestamp'));
97                 $this->addWhereRange('rc_timestamp', $params['dir'], $params['start'], $params['end']);
98                 $this->addWhereFld('rc_namespace', $params['namespace']);
99                 $this->addWhereFld('rc_deleted', 0);
100                 if($params['titles'])
101                 {
102                         $lb = new LinkBatch;
103                         foreach($params['titles'] as $t)
104                         {
105                                 $obj = Title::newFromText($t);
106                                 $lb->addObj($obj);
107                                 if($obj->getNamespace() < 0)
108                                 {
109                                         // LinkBatch refuses these, but we need them anyway
110                                         if(!array_key_exists($obj->getNamespace(), $lb->data))
111                                                 $lb->data[$obj->getNamespace()] = array();
112                                         $lb->data[$obj->getNamespace()][$obj->getDBKey()] = 1;
113                                 }
114                         }
115                         $where = $lb->constructSet('rc', $this->getDB());
116                         if($where != '')
117                                 $this->addWhere($where);
118                 }
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                 /* Add the fields we're concerned with to out query. */
156                 $this->addFields(array (
157                         'rc_timestamp',
158                         'rc_namespace',
159                         'rc_title',
160                         'rc_cur_id',
161                         'rc_type',
162                         'rc_moved_to_ns',
163                         'rc_moved_to_title'
164                 ));
165
166                 /* Determine what properties we need to display. */
167                 if (!is_null($params['prop'])) {
168                         $prop = array_flip($params['prop']);
169
170                         /* Set up internal members based upon params. */
171                         $this->fld_comment = isset ($prop['comment']);
172                         $this->fld_user = isset ($prop['user']);
173                         $this->fld_flags = isset ($prop['flags']);
174                         $this->fld_timestamp = isset ($prop['timestamp']);
175                         $this->fld_title = isset ($prop['title']);
176                         $this->fld_ids = isset ($prop['ids']);
177                         $this->fld_sizes = isset ($prop['sizes']);
178                         $this->fld_redirect = isset($prop['redirect']);
179                         $this->fld_patrolled = isset($prop['patrolled']);
180                         $this->fld_loginfo = isset($prop['loginfo']);
181
182                         global $wgUser;
183                         if($this->fld_patrolled && !$wgUser->useRCPatrol() && !$wgUser->useNPPatrol())
184                                 $this->dieUsage("You need the patrol right to request the patrolled flag", 'permissiondenied');
185
186                         /* Add fields to our query if they are specified as a needed parameter. */
187                         $this->addFieldsIf('rc_id', $this->fld_ids);
188                         $this->addFieldsIf('rc_this_oldid', $this->fld_ids);
189                         $this->addFieldsIf('rc_last_oldid', $this->fld_ids);
190                         $this->addFieldsIf('rc_comment', $this->fld_comment);
191                         $this->addFieldsIf('rc_user', $this->fld_user);
192                         $this->addFieldsIf('rc_user_text', $this->fld_user);
193                         $this->addFieldsIf('rc_minor', $this->fld_flags);
194                         $this->addFieldsIf('rc_bot', $this->fld_flags);
195                         $this->addFieldsIf('rc_new', $this->fld_flags);
196                         $this->addFieldsIf('rc_old_len', $this->fld_sizes);
197                         $this->addFieldsIf('rc_new_len', $this->fld_sizes);
198                         $this->addFieldsIf('rc_patrolled', $this->fld_patrolled);
199                         $this->addFieldsIf('rc_logid', $this->fld_loginfo);
200                         $this->addFieldsIf('rc_log_type', $this->fld_loginfo);
201                         $this->addFieldsIf('rc_log_action', $this->fld_loginfo);
202                         $this->addFieldsIf('rc_params', $this->fld_loginfo);
203                         if($this->fld_redirect || isset($show['redirect']) || isset($show['!redirect']))
204                         {
205                                 $this->addTables('page');
206                                 $this->addJoinConds(array('page' => array('LEFT JOIN', array('rc_namespace=page_namespace', 'rc_title=page_title'))));
207                                 $this->addFields('page_is_redirect');
208                         }
209                 }
210                 $this->token = $params['token'];
211                 $this->addOption('LIMIT', $params['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 > $params['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 (isset($row->rc_moved_to_title) && $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 && isset($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 ($this->fld_loginfo && $row->rc_type == RC_LOG) {
331                         $vals['logid'] = $row->rc_logid;
332                         $vals['logtype'] = $row->rc_log_type;
333                         $vals['logaction'] = $row->rc_log_action;
334                         ApiQueryLogEvents::addLogParams($this->getResult(),
335                                 $vals, $row->rc_params,
336                                 $row->rc_log_type, $row->rc_timestamp);
337                 }
338                 
339                 if(!is_null($this->token))
340                 {
341                         $tokenFunctions = $this->getTokenFunctions();
342                         foreach($this->token as $t)
343                         {
344                                 $val = call_user_func($tokenFunctions[$t], $row->rc_cur_id,
345                                         $title, RecentChange::newFromRow($row));
346                                 if($val === false)
347                                         $this->setWarning("Action '$t' is not allowed for the current user");
348                                 else
349                                         $vals[$t . 'token'] = $val;
350                         }
351                 }
352
353                 return $vals;
354         }
355
356         private function parseRCType($type)
357         {
358                         if(is_array($type))
359                         {
360                                         $retval = array();
361                                         foreach($type as $t)
362                                                         $retval[] = $this->parseRCType($t);
363                                         return $retval;
364                         }
365                         switch($type)
366                         {
367                                         case 'edit': return RC_EDIT;
368                                         case 'new': return RC_NEW;
369                                         case 'log': return RC_LOG;
370                         }
371         }
372
373         public function getAllowedParams() {
374                 return array (
375                         'start' => array (
376                                 ApiBase :: PARAM_TYPE => 'timestamp'
377                         ),
378                         'end' => array (
379                                 ApiBase :: PARAM_TYPE => 'timestamp'
380                         ),
381                         'dir' => array (
382                                 ApiBase :: PARAM_DFLT => 'older',
383                                 ApiBase :: PARAM_TYPE => array (
384                                         'newer',
385                                         'older'
386                                 )
387                         ),
388                         'namespace' => array (
389                                 ApiBase :: PARAM_ISMULTI => true,
390                                 ApiBase :: PARAM_TYPE => 'namespace'
391                         ),
392                         'titles' => array(
393                                 ApiBase :: PARAM_ISMULTI => true
394                         ),
395                         'prop' => array (
396                                 ApiBase :: PARAM_ISMULTI => true,
397                                 ApiBase :: PARAM_DFLT => 'title|timestamp|ids',
398                                 ApiBase :: PARAM_TYPE => array (
399                                         'user',
400                                         'comment',
401                                         'flags',
402                                         'timestamp',
403                                         'title',
404                                         'ids',
405                                         'sizes',
406                                         'redirect',
407                                         'patrolled',
408                                         'loginfo',
409                                 )
410                         ),
411                         'token' => array(
412                                 ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions()),
413                                 ApiBase :: PARAM_ISMULTI => true
414                         ),
415                         'show' => array (
416                                 ApiBase :: PARAM_ISMULTI => true,
417                                 ApiBase :: PARAM_TYPE => array (
418                                         'minor',
419                                         '!minor',
420                                         'bot',
421                                         '!bot',
422                                         'anon',
423                                         '!anon',
424                                         'redirect',
425                                         '!redirect',
426                                         'patrolled',
427                                         '!patrolled'
428                                 )
429                         ),
430                         'limit' => array (
431                                 ApiBase :: PARAM_DFLT => 10,
432                                 ApiBase :: PARAM_TYPE => 'limit',
433                                 ApiBase :: PARAM_MIN => 1,
434                                 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
435                                 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
436                         ),
437                         'type' => array (
438                                 ApiBase :: PARAM_ISMULTI => true,
439                                 ApiBase :: PARAM_TYPE => array (
440                                         'edit',
441                                         'new',
442                                         'log'
443                                 )
444                         )
445                 );
446         }
447
448         public function getParamDescription() {
449                 return array (
450                         'start' => 'The timestamp to start enumerating from.',
451                         'end' => 'The timestamp to end enumerating.',
452                         'dir' => 'In which direction to enumerate.',
453                         'namespace' => 'Filter log entries to only this namespace(s)',
454                         'titles' => 'Filter log entries to only these page titles',
455                         'prop' => 'Include additional pieces of information',
456                         'token' => 'Which tokens to obtain for each change',
457                         'show' => array (
458                                 'Show only items that meet this criteria.',
459                                 'For example, to see only minor edits done by logged-in users, set show=minor|!anon'
460                         ),
461                         'type' => 'Which types of changes to show.',
462                         'limit' => 'How many total changes to return.'
463                 );
464         }
465
466         public function getDescription() {
467                 return 'Enumerate recent changes';
468         }
469
470         protected function getExamples() {
471                 return array (
472                         'api.php?action=query&list=recentchanges'
473                 );
474         }
475
476         public function getVersion() {
477                 return __CLASS__ . ': $Id: ApiQueryRecentChanges.php 44719 2008-12-17 16:34:01Z catrope $';
478         }
479 }