* (bug 27670) Ordering by timestamp (and usage of start and end) isn't as clear in...
[lhc/web/wiklou.git] / includes / api / ApiQueryRecentChanges.php
1 <?php
2 /**
3 *
4 *
5 * Created on Oct 19, 2006
6 *
7 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiQueryBase.php' );
30 }
31
32 /**
33 * A query action to enumerate the recent changes that were done to the wiki.
34 * Various filters are supported.
35 *
36 * @ingroup API
37 */
38 class ApiQueryRecentChanges extends ApiQueryGeneratorBase {
39
40 public function __construct( $query, $moduleName ) {
41 parent::__construct( $query, $moduleName, 'rc' );
42 }
43
44 private $fld_comment = false, $fld_parsedcomment = false, $fld_user = false, $fld_userid = false,
45 $fld_flags = false, $fld_timestamp = false, $fld_title = false, $fld_ids = false,
46 $fld_sizes = false, $fld_redirect = false, $fld_patrolled = false, $fld_loginfo = false,
47 $fld_tags = false, $token = array();
48
49 private $tokenFunctions;
50
51 /**
52 * Get an array mapping token names to their handler functions.
53 * The prototype for a token function is func($pageid, $title, $rc)
54 * it should return a token or false (permission denied)
55 * @return array(tokenname => function)
56 */
57 protected function getTokenFunctions() {
58 // Don't call the hooks twice
59 if ( isset( $this->tokenFunctions ) ) {
60 return $this->tokenFunctions;
61 }
62
63 // If we're in JSON callback mode, no tokens can be obtained
64 if ( !is_null( $this->getMain()->getRequest()->getVal( 'callback' ) ) ) {
65 return array();
66 }
67
68 $this->tokenFunctions = array(
69 'patrol' => array( 'ApiQueryRecentChanges', 'getPatrolToken' )
70 );
71 wfRunHooks( 'APIQueryRecentChangesTokens', array( &$this->tokenFunctions ) );
72 return $this->tokenFunctions;
73 }
74
75 /**
76 * @static
77 * @param $pageid
78 * @param $title
79 * @param $rc RecentChange
80 * @return bool|String
81 */
82 public static function getPatrolToken( $pageid, $title, $rc ) {
83 global $wgUser;
84 if ( !$wgUser->useRCPatrol() && ( !$wgUser->useNPPatrol() ||
85 $rc->getAttribute( 'rc_type' ) != RC_NEW ) )
86 {
87 return false;
88 }
89
90 // The patrol token is always the same, let's exploit that
91 static $cachedPatrolToken = null;
92 if ( is_null( $cachedPatrolToken ) ) {
93 $cachedPatrolToken = $wgUser->editToken( 'patrol' );
94 }
95
96 return $cachedPatrolToken;
97 }
98
99 /**
100 * Sets internal state to include the desired properties in the output.
101 * @param $prop Array associative array of properties, only keys are used here
102 */
103 public function initProperties( $prop ) {
104 $this->fld_comment = isset( $prop['comment'] );
105 $this->fld_parsedcomment = isset( $prop['parsedcomment'] );
106 $this->fld_user = isset( $prop['user'] );
107 $this->fld_userid = isset( $prop['userid'] );
108 $this->fld_flags = isset( $prop['flags'] );
109 $this->fld_timestamp = isset( $prop['timestamp'] );
110 $this->fld_title = isset( $prop['title'] );
111 $this->fld_ids = isset( $prop['ids'] );
112 $this->fld_sizes = isset( $prop['sizes'] );
113 $this->fld_redirect = isset( $prop['redirect'] );
114 $this->fld_patrolled = isset( $prop['patrolled'] );
115 $this->fld_loginfo = isset( $prop['loginfo'] );
116 $this->fld_tags = isset( $prop['tags'] );
117 }
118
119 public function execute() {
120 $this->run();
121 }
122
123 public function executeGenerator( $resultPageSet ) {
124 $this->run( $resultPageSet );
125 }
126
127 /**
128 * Generates and outputs the result of this query based upon the provided parameters.
129 *
130 * @param $resultPageSet ApiPageSet
131 */
132 public function run( $resultPageSet = null ) {
133 global $wgUser;
134 /* Get the parameters of the request. */
135 $params = $this->extractRequestParams();
136
137 /* Build our basic query. Namely, something along the lines of:
138 * SELECT * FROM recentchanges WHERE rc_timestamp > $start
139 * AND rc_timestamp < $end AND rc_namespace = $namespace
140 * AND rc_deleted = '0'
141 */
142 $this->addTables( 'recentchanges' );
143 $index = array( 'recentchanges' => 'rc_timestamp' ); // May change
144 $this->addWhereRange( 'rc_timestamp', $params['dir'], $params['start'], $params['end'] );
145 $this->addWhereFld( 'rc_namespace', $params['namespace'] );
146 $this->addWhereFld( 'rc_deleted', 0 );
147
148 if ( !is_null( $params['type'] ) ) {
149 $this->addWhereFld( 'rc_type', $this->parseRCType( $params['type'] ) );
150 }
151
152 if ( !is_null( $params['show'] ) ) {
153 $show = array_flip( $params['show'] );
154
155 /* Check for conflicting parameters. */
156 if ( ( isset( $show['minor'] ) && isset( $show['!minor'] ) )
157 || ( isset( $show['bot'] ) && isset( $show['!bot'] ) )
158 || ( isset( $show['anon'] ) && isset( $show['!anon'] ) )
159 || ( isset( $show['redirect'] ) && isset( $show['!redirect'] ) )
160 || ( isset( $show['patrolled'] ) && isset( $show['!patrolled'] ) )
161 )
162 {
163 $this->dieUsageMsg( array( 'show' ) );
164 }
165
166 // Check permissions
167 if ( isset( $show['patrolled'] ) || isset( $show['!patrolled'] ) ) {
168 if ( !$wgUser->useRCPatrol() && !$wgUser->useNPPatrol() ) {
169 $this->dieUsage( 'You need the patrol right to request the patrolled flag', 'permissiondenied' );
170 }
171 }
172
173 /* Add additional conditions to query depending upon parameters. */
174 $this->addWhereIf( 'rc_minor = 0', isset( $show['!minor'] ) );
175 $this->addWhereIf( 'rc_minor != 0', isset( $show['minor'] ) );
176 $this->addWhereIf( 'rc_bot = 0', isset( $show['!bot'] ) );
177 $this->addWhereIf( 'rc_bot != 0', isset( $show['bot'] ) );
178 $this->addWhereIf( 'rc_user = 0', isset( $show['anon'] ) );
179 $this->addWhereIf( 'rc_user != 0', isset( $show['!anon'] ) );
180 $this->addWhereIf( 'rc_patrolled = 0', isset( $show['!patrolled'] ) );
181 $this->addWhereIf( 'rc_patrolled != 0', isset( $show['patrolled'] ) );
182 $this->addWhereIf( 'page_is_redirect = 1', isset( $show['redirect'] ) );
183
184 // Don't throw log entries out the window here
185 $this->addWhereIf( 'page_is_redirect = 0 OR page_is_redirect IS NULL', isset( $show['!redirect'] ) );
186 }
187
188 if ( !is_null( $params['user'] ) && !is_null( $params['excludeuser'] ) ) {
189 $this->dieUsage( 'user and excludeuser cannot be used together', 'user-excludeuser' );
190 }
191
192 if ( !is_null( $params['user'] ) ) {
193 $this->addWhereFld( 'rc_user_text', $params['user'] );
194 $index['recentchanges'] = 'rc_user_text';
195 }
196
197 if ( !is_null( $params['excludeuser'] ) ) {
198 // We don't use the rc_user_text index here because
199 // * it would require us to sort by rc_user_text before rc_timestamp
200 // * the != condition doesn't throw out too many rows anyway
201 $this->addWhere( 'rc_user_text != ' . $this->getDB()->addQuotes( $params['excludeuser'] ) );
202 }
203
204 /* Add the fields we're concerned with to our query. */
205 $this->addFields( array(
206 'rc_timestamp',
207 'rc_namespace',
208 'rc_title',
209 'rc_cur_id',
210 'rc_type',
211 'rc_moved_to_ns',
212 'rc_moved_to_title',
213 'rc_deleted'
214 ) );
215
216 /* Determine what properties we need to display. */
217 if ( !is_null( $params['prop'] ) ) {
218 $prop = array_flip( $params['prop'] );
219
220 /* Set up internal members based upon params. */
221 $this->initProperties( $prop );
222
223 if ( $this->fld_patrolled && !$wgUser->useRCPatrol() && !$wgUser->useNPPatrol() ) {
224 $this->dieUsage( 'You need the patrol right to request the patrolled flag', 'permissiondenied' );
225 }
226
227 /* Add fields to our query if they are specified as a needed parameter. */
228 $this->addFieldsIf( 'rc_id', $this->fld_ids );
229 $this->addFieldsIf( 'rc_this_oldid', $this->fld_ids );
230 $this->addFieldsIf( 'rc_last_oldid', $this->fld_ids );
231 $this->addFieldsIf( 'rc_comment', $this->fld_comment || $this->fld_parsedcomment );
232 $this->addFieldsIf( 'rc_user', $this->fld_user );
233 $this->addFieldsIf( 'rc_user_text', $this->fld_user || $this->fld_userid );
234 $this->addFieldsIf( 'rc_minor', $this->fld_flags );
235 $this->addFieldsIf( 'rc_bot', $this->fld_flags );
236 $this->addFieldsIf( 'rc_new', $this->fld_flags );
237 $this->addFieldsIf( 'rc_old_len', $this->fld_sizes );
238 $this->addFieldsIf( 'rc_new_len', $this->fld_sizes );
239 $this->addFieldsIf( 'rc_patrolled', $this->fld_patrolled );
240 $this->addFieldsIf( 'rc_logid', $this->fld_loginfo );
241 $this->addFieldsIf( 'rc_log_type', $this->fld_loginfo );
242 $this->addFieldsIf( 'rc_log_action', $this->fld_loginfo );
243 $this->addFieldsIf( 'rc_params', $this->fld_loginfo );
244 if ( $this->fld_redirect || isset( $show['redirect'] ) || isset( $show['!redirect'] ) ) {
245 $this->addTables( 'page' );
246 $this->addJoinConds( array( 'page' => array( 'LEFT JOIN', array( 'rc_namespace=page_namespace', 'rc_title=page_title' ) ) ) );
247 $this->addFields( 'page_is_redirect' );
248 }
249 }
250
251 if ( $this->fld_tags ) {
252 $this->addTables( 'tag_summary' );
253 $this->addJoinConds( array( 'tag_summary' => array( 'LEFT JOIN', array( 'rc_id=ts_rc_id' ) ) ) );
254 $this->addFields( 'ts_tags' );
255 }
256
257 if ( !is_null( $params['tag'] ) ) {
258 $this->addTables( 'change_tag' );
259 $this->addJoinConds( array( 'change_tag' => array( 'INNER JOIN', array( 'rc_id=ct_rc_id' ) ) ) );
260 $this->addWhereFld( 'ct_tag' , $params['tag'] );
261 global $wgOldChangeTagsIndex;
262 $index['change_tag'] = $wgOldChangeTagsIndex ? 'ct_tag' : 'change_tag_tag_id';
263 }
264
265 $this->token = $params['token'];
266 $this->addOption( 'LIMIT', $params['limit'] + 1 );
267 $this->addOption( 'USE INDEX', $index );
268
269 $count = 0;
270 /* Perform the actual query. */
271 $res = $this->select( __METHOD__ );
272
273 $titles = array();
274
275 /* Iterate through the rows, adding data extracted from them to our query result. */
276 foreach ( $res as $row ) {
277 if ( ++ $count > $params['limit'] ) {
278 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
279 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->rc_timestamp ) );
280 break;
281 }
282
283 if ( is_null( $resultPageSet ) ) {
284 /* Extract the data from a single row. */
285 $vals = $this->extractRowInfo( $row );
286
287 /* Add that row's data to our final output. */
288 if ( !$vals ) {
289 continue;
290 }
291 $fit = $this->getResult()->addValue( array( 'query', $this->getModuleName() ), null, $vals );
292 if ( !$fit ) {
293 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->rc_timestamp ) );
294 break;
295 }
296 } else {
297 $titles[] = Title::makeTitle( $row->rc_namespace, $row->rc_title );
298 }
299 }
300
301 if ( is_null( $resultPageSet ) ) {
302 /* Format the result */
303 $this->getResult()->setIndexedTagName_internal( array( 'query', $this->getModuleName() ), 'rc' );
304 } else {
305 $resultPageSet->populateFromTitles( $titles );
306 }
307 }
308
309 /**
310 * Extracts from a single sql row the data needed to describe one recent change.
311 *
312 * @param $row The row from which to extract the data.
313 * @return An array mapping strings (descriptors) to their respective string values.
314 * @access public
315 */
316 public function extractRowInfo( $row ) {
317 /* If page was moved somewhere, get the title of the move target. */
318 $movedToTitle = false;
319 if ( isset( $row->rc_moved_to_title ) && $row->rc_moved_to_title !== '' ) {
320 $movedToTitle = Title::makeTitle( $row->rc_moved_to_ns, $row->rc_moved_to_title );
321 }
322
323 /* Determine the title of the page that has been changed. */
324 $title = Title::makeTitle( $row->rc_namespace, $row->rc_title );
325
326 /* Our output data. */
327 $vals = array();
328
329 $type = intval( $row->rc_type );
330
331 /* Determine what kind of change this was. */
332 switch ( $type ) {
333 case RC_EDIT:
334 $vals['type'] = 'edit';
335 break;
336 case RC_NEW:
337 $vals['type'] = 'new';
338 break;
339 case RC_MOVE:
340 $vals['type'] = 'move';
341 break;
342 case RC_LOG:
343 $vals['type'] = 'log';
344 break;
345 case RC_MOVE_OVER_REDIRECT:
346 $vals['type'] = 'move over redirect';
347 break;
348 default:
349 $vals['type'] = $type;
350 }
351
352 /* Create a new entry in the result for the title. */
353 if ( $this->fld_title ) {
354 ApiQueryBase::addTitleInfo( $vals, $title );
355 if ( $movedToTitle ) {
356 ApiQueryBase::addTitleInfo( $vals, $movedToTitle, 'new_' );
357 }
358 }
359
360 /* Add ids, such as rcid, pageid, revid, and oldid to the change's info. */
361 if ( $this->fld_ids ) {
362 $vals['rcid'] = intval( $row->rc_id );
363 $vals['pageid'] = intval( $row->rc_cur_id );
364 $vals['revid'] = intval( $row->rc_this_oldid );
365 $vals['old_revid'] = intval( $row->rc_last_oldid );
366 }
367
368 /* Add user data and 'anon' flag, if use is anonymous. */
369 if ( $this->fld_user || $this->fld_userid ) {
370
371 if ( $this->fld_user ) {
372 $vals['user'] = $row->rc_user_text;
373 }
374
375 if ( $this->fld_userid ) {
376 $vals['userid'] = $row->rc_user;
377 }
378
379 if ( !$row->rc_user ) {
380 $vals['anon'] = '';
381 }
382 }
383
384 /* Add flags, such as new, minor, bot. */
385 if ( $this->fld_flags ) {
386 if ( $row->rc_bot ) {
387 $vals['bot'] = '';
388 }
389 if ( $row->rc_new ) {
390 $vals['new'] = '';
391 }
392 if ( $row->rc_minor ) {
393 $vals['minor'] = '';
394 }
395 }
396
397 /* Add sizes of each revision. (Only available on 1.10+) */
398 if ( $this->fld_sizes ) {
399 $vals['oldlen'] = intval( $row->rc_old_len );
400 $vals['newlen'] = intval( $row->rc_new_len );
401 }
402
403 /* Add the timestamp. */
404 if ( $this->fld_timestamp ) {
405 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $row->rc_timestamp );
406 }
407
408 /* Add edit summary / log summary. */
409 if ( $this->fld_comment && isset( $row->rc_comment ) ) {
410 $vals['comment'] = $row->rc_comment;
411 }
412
413 if ( $this->fld_parsedcomment && isset( $row->rc_comment ) ) {
414 global $wgUser;
415 $vals['parsedcomment'] = $wgUser->getSkin()->formatComment( $row->rc_comment, $title );
416 }
417
418 if ( $this->fld_redirect ) {
419 if ( $row->page_is_redirect ) {
420 $vals['redirect'] = '';
421 }
422 }
423
424 /* Add the patrolled flag */
425 if ( $this->fld_patrolled && $row->rc_patrolled == 1 ) {
426 $vals['patrolled'] = '';
427 }
428
429 if ( $this->fld_loginfo && $row->rc_type == RC_LOG ) {
430 $vals['logid'] = intval( $row->rc_logid );
431 $vals['logtype'] = $row->rc_log_type;
432 $vals['logaction'] = $row->rc_log_action;
433 ApiQueryLogEvents::addLogParams(
434 $this->getResult(),
435 $vals, $row->rc_params,
436 $row->rc_log_type, $row->rc_timestamp
437 );
438 }
439
440 if ( $this->fld_tags ) {
441 if ( $row->ts_tags ) {
442 $tags = explode( ',', $row->ts_tags );
443 $this->getResult()->setIndexedTagName( $tags, 'tag' );
444 $vals['tags'] = $tags;
445 } else {
446 $vals['tags'] = array();
447 }
448 }
449
450 if ( !is_null( $this->token ) ) {
451 $tokenFunctions = $this->getTokenFunctions();
452 foreach ( $this->token as $t ) {
453 $val = call_user_func( $tokenFunctions[$t], $row->rc_cur_id,
454 $title, RecentChange::newFromRow( $row ) );
455 if ( $val === false ) {
456 $this->setWarning( "Action '$t' is not allowed for the current user" );
457 } else {
458 $vals[$t . 'token'] = $val;
459 }
460 }
461 }
462
463 return $vals;
464 }
465
466 private function parseRCType( $type ) {
467 if ( is_array( $type ) ) {
468 $retval = array();
469 foreach ( $type as $t ) {
470 $retval[] = $this->parseRCType( $t );
471 }
472 return $retval;
473 }
474 switch( $type ) {
475 case 'edit':
476 return RC_EDIT;
477 case 'new':
478 return RC_NEW;
479 case 'log':
480 return RC_LOG;
481 }
482 }
483
484 public function getCacheMode( $params ) {
485 if ( isset( $params['show'] ) ) {
486 foreach ( $params['show'] as $show ) {
487 if ( $show === 'patrolled' || $show === '!patrolled' ) {
488 return 'private';
489 }
490 }
491 }
492 if ( isset( $params['token'] ) ) {
493 return 'private';
494 }
495 if ( !is_null( $params['prop'] ) && in_array( 'parsedcomment', $params['prop'] ) ) {
496 // formatComment() calls wfMsg() among other things
497 return 'anon-public-user-private';
498 }
499 return 'public';
500 }
501
502 public function getAllowedParams() {
503 return array(
504 'start' => array(
505 ApiBase::PARAM_TYPE => 'timestamp'
506 ),
507 'end' => array(
508 ApiBase::PARAM_TYPE => 'timestamp'
509 ),
510 'dir' => array(
511 ApiBase::PARAM_DFLT => 'older',
512 ApiBase::PARAM_TYPE => array(
513 'newer',
514 'older'
515 )
516 ),
517 'namespace' => array(
518 ApiBase::PARAM_ISMULTI => true,
519 ApiBase::PARAM_TYPE => 'namespace'
520 ),
521 'user' => array(
522 ApiBase::PARAM_TYPE => 'user'
523 ),
524 'excludeuser' => array(
525 ApiBase::PARAM_TYPE => 'user'
526 ),
527 'tag' => null,
528 'prop' => array(
529 ApiBase::PARAM_ISMULTI => true,
530 ApiBase::PARAM_DFLT => 'title|timestamp|ids',
531 ApiBase::PARAM_TYPE => array(
532 'user',
533 'userid',
534 'comment',
535 'parsedcomment',
536 'flags',
537 'timestamp',
538 'title',
539 'ids',
540 'sizes',
541 'redirect',
542 'patrolled',
543 'loginfo',
544 'tags'
545 )
546 ),
547 'token' => array(
548 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
549 ApiBase::PARAM_ISMULTI => true
550 ),
551 'show' => array(
552 ApiBase::PARAM_ISMULTI => true,
553 ApiBase::PARAM_TYPE => array(
554 'minor',
555 '!minor',
556 'bot',
557 '!bot',
558 'anon',
559 '!anon',
560 'redirect',
561 '!redirect',
562 'patrolled',
563 '!patrolled'
564 )
565 ),
566 'limit' => array(
567 ApiBase::PARAM_DFLT => 10,
568 ApiBase::PARAM_TYPE => 'limit',
569 ApiBase::PARAM_MIN => 1,
570 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
571 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
572 ),
573 'type' => array(
574 ApiBase::PARAM_ISMULTI => true,
575 ApiBase::PARAM_TYPE => array(
576 'edit',
577 'new',
578 'log'
579 )
580 )
581 );
582 }
583
584 public function getParamDescription() {
585 $p = $this->getModulePrefix();
586 return array(
587 'start' => 'The timestamp to start enumerating from',
588 'end' => 'The timestamp to end enumerating',
589 'dir' => $this->getDirectionDescription( $p ),
590 'namespace' => 'Filter log entries to only this namespace(s)',
591 'user' => 'Only list changes by this user',
592 'excludeuser' => 'Don\'t list changes by this user',
593 'prop' => array(
594 'Include additional pieces of information',
595 ' user - Adds the user responsible for the edit and tags if they are an IP',
596 ' userid - Adds the user id responsible for the edit',
597 ' comment - Adds the comment for the edit',
598 ' parsedcomment - Adds the parsed comment for the edit',
599 ' flags - Adds flags for the edit',
600 ' timestamp - Adds timestamp of the edit',
601 ' title - Adds the page title of the edit',
602 ' ids - Adds the page ID, recent changes ID and the new and old revision ID',
603 ' sizes - Adds the new and old page length in bytes',
604 ' redirect - Tags edit if page is a redirect',
605 ' patrolled - Tags edits that have been patrolled',
606 ' loginfo - Adds log information (logid, logtype, etc) to log entries',
607 ' tags - Lists tags for the entry',
608 ),
609 'token' => 'Which tokens to obtain for each change',
610 'show' => array(
611 'Show only items that meet this criteria.',
612 "For example, to see only minor edits done by logged-in users, set {$p}show=minor|!anon"
613 ),
614 'type' => 'Which types of changes to show',
615 'limit' => 'How many total changes to return',
616 'tag' => 'Only list changes tagged with this tag',
617 );
618 }
619
620 public function getDescription() {
621 return 'Enumerate recent changes';
622 }
623
624 public function getPossibleErrors() {
625 return array_merge( parent::getPossibleErrors(), array(
626 array( 'show' ),
627 array( 'code' => 'permissiondenied', 'info' => 'You need the patrol right to request the patrolled flag' ),
628 array( 'code' => 'user-excludeuser', 'info' => 'user and excludeuser cannot be used together' ),
629 ) );
630 }
631
632 protected function getExamples() {
633 return array(
634 'api.php?action=query&list=recentchanges'
635 );
636 }
637
638 public function getVersion() {
639 return __CLASS__ . ': $Id$';
640 }
641 }