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