3 * Implements Special:Recentchanges
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
24 use MediaWiki\MediaWikiServices
;
27 * A special page that lists last changes made to the wiki
29 * @ingroup SpecialPage
31 class SpecialRecentChanges
extends ChangesListSpecialPage
{
32 // @codingStandardsIgnoreStart Needed "useless" override to change parameters.
33 public function __construct( $name = 'Recentchanges', $restriction = '' ) {
34 parent
::__construct( $name, $restriction );
36 // @codingStandardsIgnoreEnd
39 * Main execution point
41 * @param string $subpage
43 public function execute( $subpage ) {
44 // Backwards-compatibility: redirect to new feed URLs
45 $feedFormat = $this->getRequest()->getVal( 'feed' );
46 if ( !$this->including() && $feedFormat ) {
47 $query = $this->getFeedQuery();
48 $query['feedformat'] = $feedFormat === 'atom' ?
'atom' : 'rss';
49 $this->getOutput()->redirect( wfAppendQuery( wfScript( 'api' ), $query ) );
54 // 10 seconds server-side caching max
55 $this->getOutput()->setCdnMaxage( 10 );
56 // Check if the client has a cached version
57 $lastmod = $this->checkLastModified();
58 if ( $lastmod === false ) {
63 '//meta.wikimedia.org/wiki/Special:MyLanguage/Help:Recent_changes',
66 parent
::execute( $subpage );
70 * Get a FormOptions object containing the default options
74 public function getDefaultOptions() {
75 $opts = parent
::getDefaultOptions();
76 $user = $this->getUser();
78 $opts->add( 'days', $user->getIntOption( 'rcdays' ) );
79 $opts->add( 'limit', $user->getIntOption( 'rclimit' ) );
80 $opts->add( 'from', '' );
82 $opts->add( 'hideminor', $user->getBoolOption( 'hideminor' ) );
83 $opts->add( 'hidebots', true );
84 $opts->add( 'hideanons', false );
85 $opts->add( 'hideliu', false );
86 $opts->add( 'hidepatrolled', $user->getBoolOption( 'hidepatrolled' ) );
87 $opts->add( 'hidemyself', false );
88 $opts->add( 'hidecategorization', $user->getBoolOption( 'hidecategorization' ) );
90 $opts->add( 'categories', '' );
91 $opts->add( 'categories_any', false );
92 $opts->add( 'tagfilter', '' );
98 * Get custom show/hide filters
100 * @return array Map of filter URL param names to properties (msg/default)
102 protected function getCustomFilters() {
103 if ( $this->customFilters
=== null ) {
104 $this->customFilters
= parent
::getCustomFilters();
105 Hooks
::run( 'SpecialRecentChangesFilters', [ $this, &$this->customFilters
], '1.23' );
108 return $this->customFilters
;
112 * Process $par and put options found in $opts. Used when including the page.
115 * @param FormOptions $opts
117 public function parseParameters( $par, FormOptions
$opts ) {
118 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
119 foreach ( $bits as $bit ) {
120 if ( 'hidebots' === $bit ) {
121 $opts['hidebots'] = true;
123 if ( 'bots' === $bit ) {
124 $opts['hidebots'] = false;
126 if ( 'hideminor' === $bit ) {
127 $opts['hideminor'] = true;
129 if ( 'minor' === $bit ) {
130 $opts['hideminor'] = false;
132 if ( 'hideliu' === $bit ) {
133 $opts['hideliu'] = true;
135 if ( 'hidepatrolled' === $bit ) {
136 $opts['hidepatrolled'] = true;
138 if ( 'hideanons' === $bit ) {
139 $opts['hideanons'] = true;
141 if ( 'hidemyself' === $bit ) {
142 $opts['hidemyself'] = true;
144 if ( 'hidecategorization' === $bit ) {
145 $opts['hidecategorization'] = true;
148 if ( is_numeric( $bit ) ) {
149 $opts['limit'] = $bit;
153 if ( preg_match( '/^limit=(\d+)$/', $bit, $m ) ) {
154 $opts['limit'] = $m[1];
156 if ( preg_match( '/^days=(\d+)$/', $bit, $m ) ) {
157 $opts['days'] = $m[1];
159 if ( preg_match( '/^namespace=(\d+)$/', $bit, $m ) ) {
160 $opts['namespace'] = $m[1];
162 if ( preg_match( '/^tagfilter=(.*)$/', $bit, $m ) ) {
163 $opts['tagfilter'] = $m[1];
168 public function validateOptions( FormOptions
$opts ) {
169 $opts->validateIntBounds( 'limit', 0, 5000 );
170 parent
::validateOptions( $opts );
174 * Return an array of conditions depending of options set in $opts
176 * @param FormOptions $opts
179 public function buildMainQueryConds( FormOptions
$opts ) {
180 $dbr = $this->getDB();
181 $conds = parent
::buildMainQueryConds( $opts );
184 $cutoff_unixtime = time() - ( $opts['days'] * 86400 );
185 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
186 $cutoff = $dbr->timestamp( $cutoff_unixtime );
188 $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
189 if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW
, $cutoff ) ) {
190 $cutoff = $dbr->timestamp( $opts['from'] );
192 $opts->reset( 'from' );
195 $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
203 * @param array $conds
204 * @param FormOptions $opts
205 * @return bool|ResultWrapper Result or false (for Recentchangeslinked only)
207 public function doMainQuery( $conds, $opts ) {
208 $dbr = $this->getDB();
209 $user = $this->getUser();
211 $tables = [ 'recentchanges' ];
212 $fields = RecentChange
::selectFields();
216 // JOIN on watchlist for users
217 if ( $user->getId() && $user->isAllowed( 'viewmywatchlist' ) ) {
218 $tables[] = 'watchlist';
219 $fields[] = 'wl_user';
220 $fields[] = 'wl_notificationtimestamp';
221 $join_conds['watchlist'] = [ 'LEFT JOIN', [
222 'wl_user' => $user->getId(),
224 'wl_namespace=rc_namespace'
228 if ( $user->isAllowed( 'rollback' ) ) {
230 $fields[] = 'page_latest';
231 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
234 ChangeTags
::modifyDisplayQuery(
243 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
249 // array_merge() is used intentionally here so that hooks can, should
250 // they so desire, override the ORDER BY / LIMIT condition(s); prior to
251 // MediaWiki 1.26 this used to use the plus operator instead, which meant
252 // that extensions weren't able to change these conditions
253 $query_options = array_merge( [
254 'ORDER BY' => 'rc_timestamp DESC',
255 'LIMIT' => $opts['limit'] ], $query_options );
256 $rows = $dbr->select(
259 // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
260 // knowledge to use an index merge if it wants (it may use some other index though).
261 $conds +
[ 'rc_new' => [ 0, 1 ] ],
267 // Build the final data
268 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
269 $this->filterByCategories( $rows, $opts );
275 protected function runMainQueryHook( &$tables, &$fields, &$conds,
276 &$query_options, &$join_conds, $opts
278 return parent
::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
280 'SpecialRecentChangesQuery',
281 [ &$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields ],
286 protected function getDB() {
287 return wfGetDB( DB_REPLICA
, 'recentchanges' );
290 public function outputFeedLinks() {
291 $this->addFeedLinks( $this->getFeedQuery() );
295 * Get URL query parameters for action=feedrecentchanges API feed of current recent changes view.
299 protected function getFeedQuery() {
300 $query = array_filter( $this->getOptions()->getAllValues(), function ( $value ) {
301 // API handles empty parameters in a different way
302 return $value !== '';
304 $query['action'] = 'feedrecentchanges';
305 $feedLimit = $this->getConfig()->get( 'FeedLimit' );
306 if ( $query['limit'] > $feedLimit ) {
307 $query['limit'] = $feedLimit;
314 * Build and output the actual changes list.
316 * @param ResultWrapper $rows Database rows
317 * @param FormOptions $opts
319 public function outputChangesList( $rows, $opts ) {
320 $limit = $opts['limit'];
322 $showWatcherCount = $this->getConfig()->get( 'RCShowWatchingUsers' )
323 && $this->getUser()->getOption( 'shownumberswatching' );
326 $dbr = $this->getDB();
329 $list = ChangesList
::newFromContext( $this->getContext() );
330 $list->initChangesListRows( $rows );
332 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
333 $rclistOutput = $list->beginRecentChangesList();
334 foreach ( $rows as $obj ) {
338 $rc = RecentChange
::newFromRow( $obj );
340 # Skip CatWatch entries for hidden cats based on user preference
342 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE
&&
343 !$userShowHiddenCats &&
344 $rc->getParam( 'hidden-cat' )
349 $rc->counter
= $counter++
;
350 # Check if the page has been updated since the last visit
351 if ( $this->getConfig()->get( 'ShowUpdatedMarker' )
352 && !empty( $obj->wl_notificationtimestamp
)
354 $rc->notificationtimestamp
= ( $obj->rc_timestamp
>= $obj->wl_notificationtimestamp
);
356 $rc->notificationtimestamp
= false; // Default
358 # Check the number of users watching the page
359 $rc->numberofWatchingusers
= 0; // Default
360 if ( $showWatcherCount && $obj->rc_namespace
>= 0 ) {
361 if ( !isset( $watcherCache[$obj->rc_namespace
][$obj->rc_title
] ) ) {
362 $watcherCache[$obj->rc_namespace
][$obj->rc_title
] =
363 MediaWikiServices
::getInstance()->getWatchedItemStore()->countWatchers(
364 new TitleValue( (int)$obj->rc_namespace
, $obj->rc_title
)
367 $rc->numberofWatchingusers
= $watcherCache[$obj->rc_namespace
][$obj->rc_title
];
370 $changeLine = $list->recentChangesLine( $rc, !empty( $obj->wl_user
), $counter );
371 if ( $changeLine !== false ) {
372 $rclistOutput .= $changeLine;
376 $rclistOutput .= $list->endRecentChangesList();
378 if ( $rows->numRows() === 0 ) {
379 $this->getOutput()->addHTML(
380 '<div class="mw-changeslist-empty">' .
381 $this->msg( 'recentchanges-noresult' )->parse() .
384 if ( !$this->including() ) {
385 $this->getOutput()->setStatusCode( 404 );
388 $this->getOutput()->addHTML( $rclistOutput );
393 * Set the text to be displayed above the changes
395 * @param FormOptions $opts
396 * @param int $numRows Number of rows in the result to show after this header
398 public function doHeader( $opts, $numRows ) {
399 $this->setTopText( $opts );
401 $defaults = $opts->getAllValues();
402 $nondefaults = $opts->getChangedValues();
405 $panel[] = $this->makeLegend();
406 $panel[] = $this->optionsPanel( $defaults, $nondefaults, $numRows );
409 $extraOpts = $this->getExtraOptions( $opts );
410 $extraOptsCount = count( $extraOpts );
412 $submit = ' ' . Xml
::submitButton( $this->msg( 'recentchanges-submit' )->text() );
414 $out = Xml
::openElement( 'table', [ 'class' => 'mw-recentchanges-table' ] );
415 foreach ( $extraOpts as $name => $optionRow ) {
416 # Add submit button to the last row only
418 $addSubmit = ( $count === $extraOptsCount ) ?
$submit : '';
420 $out .= Xml
::openElement( 'tr' );
421 if ( is_array( $optionRow ) ) {
424 [ 'class' => 'mw-label mw-' . $name . '-label' ],
429 [ 'class' => 'mw-input' ],
430 $optionRow[1] . $addSubmit
435 [ 'class' => 'mw-input', 'colspan' => 2 ],
436 $optionRow . $addSubmit
439 $out .= Xml
::closeElement( 'tr' );
441 $out .= Xml
::closeElement( 'table' );
443 $unconsumed = $opts->getUnconsumedValues();
444 foreach ( $unconsumed as $key => $value ) {
445 $out .= Html
::hidden( $key, $value );
448 $t = $this->getPageTitle();
449 $out .= Html
::hidden( 'title', $t->getPrefixedText() );
450 $form = Xml
::tags( 'form', [ 'action' => wfScript() ], $out );
452 $panelString = implode( "\n", $panel );
454 $this->getOutput()->addHTML(
456 $this->msg( 'recentchanges-legend' )->text(),
458 [ 'class' => 'rcoptions' ]
462 $this->setBottomText( $opts );
466 * Send the text to be displayed above the options
468 * @param FormOptions $opts Unused
470 function setTopText( FormOptions
$opts ) {
473 $message = $this->msg( 'recentchangestext' )->inContentLanguage();
474 if ( !$message->isDisabled() ) {
475 $this->getOutput()->addWikiText(
476 Html
::rawElement( 'div',
477 [ 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ],
478 "\n" . $message->plain() . "\n"
480 /* $lineStart */ true,
481 /* $interface */ false
487 * Get options to be displayed in a form
489 * @param FormOptions $opts
492 function getExtraOptions( $opts ) {
493 $opts->consumeValues( [
494 'namespace', 'invert', 'associated', 'tagfilter', 'categories', 'categories_any'
498 $extraOpts['namespace'] = $this->namespaceFilterForm( $opts );
500 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
501 $extraOpts['category'] = $this->categoryFilterForm( $opts );
504 $tagFilter = ChangeTags
::buildTagFilterSelector( $opts['tagfilter'] );
505 if ( count( $tagFilter ) ) {
506 $extraOpts['tagfilter'] = $tagFilter;
509 // Don't fire the hook for subclasses. (Or should we?)
510 if ( $this->getName() === 'Recentchanges' ) {
511 Hooks
::run( 'SpecialRecentChangesPanel', [ &$extraOpts, $opts ] );
518 * Add page-specific modules.
520 protected function addModules() {
521 parent
::addModules();
522 $out = $this->getOutput();
523 $out->addModules( 'mediawiki.special.recentchanges' );
527 * Get last modified date, for client caching
528 * Don't use this if we are using the patrol feature, patrol changes don't
529 * update the timestamp
531 * @return string|bool
533 public function checkLastModified() {
534 $dbr = $this->getDB();
535 $lastmod = $dbr->selectField( 'recentchanges', 'MAX(rc_timestamp)', false, __METHOD__
);
541 * Creates the choose namespace selection
543 * @param FormOptions $opts
546 protected function namespaceFilterForm( FormOptions
$opts ) {
547 $nsSelect = Html
::namespaceSelector(
548 [ 'selected' => $opts['namespace'], 'all' => '' ],
549 [ 'name' => 'namespace', 'id' => 'namespace' ]
551 $nsLabel = Xml
::label( $this->msg( 'namespace' )->text(), 'namespace' );
552 $invert = Xml
::checkLabel(
553 $this->msg( 'invert' )->text(), 'invert', 'nsinvert',
555 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
557 $associated = Xml
::checkLabel(
558 $this->msg( 'namespace_association' )->text(), 'associated', 'nsassociated',
560 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
563 return [ $nsLabel, "$nsSelect $invert $associated" ];
567 * Create an input to filter changes by categories
569 * @param FormOptions $opts
572 protected function categoryFilterForm( FormOptions
$opts ) {
573 list( $label, $input ) = Xml
::inputLabelSep( $this->msg( 'rc_categories' )->text(),
574 'categories', 'mw-categories', false, $opts['categories'] );
576 $input .= ' ' . Xml
::checkLabel( $this->msg( 'rc_categories_any' )->text(),
577 'categories_any', 'mw-categories_any', $opts['categories_any'] );
579 return [ $label, $input ];
583 * Filter $rows by categories set in $opts
585 * @param ResultWrapper $rows Database rows
586 * @param FormOptions $opts
588 function filterByCategories( &$rows, FormOptions
$opts ) {
589 $categories = array_map( 'trim', explode( '|', $opts['categories'] ) );
591 if ( !count( $categories ) ) {
597 foreach ( $categories as $cat ) {
609 foreach ( $rows as $k => $r ) {
610 $nt = Title
::makeTitle( $r->rc_namespace
, $r->rc_title
);
611 $id = $nt->getArticleID();
613 continue; # Page might have been deleted...
615 if ( !in_array( $id, $articles ) ) {
618 if ( !isset( $a2r[$id] ) ) {
626 if ( !count( $articles ) ||
!count( $cats ) ) {
631 $catFind = new CategoryFinder
;
632 $catFind->seed( $articles, $cats, $opts['categories_any'] ?
'OR' : 'AND' );
633 $match = $catFind->run();
637 foreach ( $match as $id ) {
638 foreach ( $a2r[$id] as $rev ) {
640 $newrows[$k] = $rowsarr[$k];
647 * Makes change an option link which carries all the other options
649 * @param string $title Title
650 * @param array $override Options to override
651 * @param array $options Current options
652 * @param bool $active Whether to show the link in bold
655 function makeOptionsLink( $title, $override, $options, $active = false ) {
656 $params = $override +
$options;
658 // Bug 36524: false values have be converted to "0" otherwise
659 // wfArrayToCgi() will omit it them.
660 foreach ( $params as &$value ) {
661 if ( $value === false ) {
667 $text = htmlspecialchars( $title );
669 $text = '<strong>' . $text . '</strong>';
672 return Linker
::linkKnown( $this->getPageTitle(), $text, [], $params );
676 * Creates the options panel.
678 * @param array $defaults
679 * @param array $nondefaults
680 * @param int $numRows Number of rows in the result to show after this header
683 function optionsPanel( $defaults, $nondefaults, $numRows ) {
684 $options = $nondefaults +
$defaults;
687 $msg = $this->msg( 'rclegend' );
688 if ( !$msg->isDisabled() ) {
689 $note .= '<div class="mw-rclegend">' . $msg->parse() . "</div>\n";
692 $lang = $this->getLanguage();
693 $user = $this->getUser();
694 $config = $this->getConfig();
695 if ( $options['from'] ) {
696 $note .= $this->msg( 'rcnotefrom' )
697 ->numParams( $options['limit'] )
699 $lang->userTimeAndDate( $options['from'], $user ),
700 $lang->userDate( $options['from'], $user ),
701 $lang->userTime( $options['from'], $user )
703 ->numParams( $numRows )
704 ->parse() . '<br />';
707 # Sort data for display and make sure it's unique after we've added user data.
708 $linkLimits = $config->get( 'RCLinkLimits' );
709 $linkLimits[] = $options['limit'];
711 $linkLimits = array_unique( $linkLimits );
713 $linkDays = $config->get( 'RCLinkDays' );
714 $linkDays[] = $options['days'];
716 $linkDays = array_unique( $linkDays );
720 foreach ( $linkLimits as $value ) {
721 $cl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
722 [ 'limit' => $value ], $nondefaults, $value == $options['limit'] );
724 $cl = $lang->pipeList( $cl );
726 // day links, reset 'from' to none
728 foreach ( $linkDays as $value ) {
729 $dl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
730 [ 'days' => $value, 'from' => '' ], $nondefaults, $value == $options['days'] );
732 $dl = $lang->pipeList( $dl );
736 'hideminor' => 'rcshowhideminor',
737 'hidebots' => 'rcshowhidebots',
738 'hideanons' => 'rcshowhideanons',
739 'hideliu' => 'rcshowhideliu',
740 'hidepatrolled' => 'rcshowhidepatr',
741 'hidemyself' => 'rcshowhidemine'
744 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
745 $filters['hidecategorization'] = 'rcshowhidecategorization';
748 $showhide = [ 'show', 'hide' ];
750 foreach ( $this->getCustomFilters() as $key => $params ) {
751 $filters[$key] = $params['msg'];
753 // Disable some if needed
754 if ( !$user->useRCPatrol() ) {
755 unset( $filters['hidepatrolled'] );
759 foreach ( $filters as $key => $msg ) {
760 // The following messages are used here:
761 // rcshowhideminor-show, rcshowhideminor-hide, rcshowhidebots-show, rcshowhidebots-hide,
762 // rcshowhideanons-show, rcshowhideanons-hide, rcshowhideliu-show, rcshowhideliu-hide,
763 // rcshowhidepatr-show, rcshowhidepatr-hide, rcshowhidemine-show, rcshowhidemine-hide,
764 // rcshowhidecategorization-show, rcshowhidecategorization-hide.
765 $linkMessage = $this->msg( $msg . '-' . $showhide[1 - $options[$key]] );
766 // Extensions can define additional filters, but don't need to define the corresponding
767 // messages. If they don't exist, just fall back to 'show' and 'hide'.
768 if ( !$linkMessage->exists() ) {
769 $linkMessage = $this->msg( $showhide[1 - $options[$key]] );
772 $link = $this->makeOptionsLink( $linkMessage->text(),
773 [ $key => 1 - $options[$key] ], $nondefaults );
774 $links[] = "<span class=\"$msg rcshowhideoption\">"
775 . $this->msg( $msg )->rawParams( $link )->escaped() . '</span>';
778 // show from this onward link
779 $timestamp = wfTimestampNow();
780 $now = $lang->userTimeAndDate( $timestamp, $user );
781 $timenow = $lang->userTime( $timestamp, $user );
782 $datenow = $lang->userDate( $timestamp, $user );
783 $pipedLinks = '<span class="rcshowhide">' . $lang->pipeList( $links ) . '</span>';
785 $rclinks = '<span class="rclinks">' . $this->msg( 'rclinks' )->rawParams( $cl, $dl, $pipedLinks )
786 ->parse() . '</span>';
788 $rclistfrom = '<span class="rclistfrom">' . $this->makeOptionsLink(
789 $this->msg( 'rclistfrom' )->rawParams( $now, $timenow, $datenow )->parse(),
790 [ 'from' => $timestamp ],
794 return "{$note}$rclinks<br />$rclistfrom";
797 public function isIncludable() {
801 protected function getCacheTTL() {