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
;
25 use Wikimedia\Rdbms\ResultWrapper
;
28 * A special page that lists last changes made to the wiki
30 * @ingroup SpecialPage
32 class SpecialRecentChanges
extends ChangesListSpecialPage
{
33 // @codingStandardsIgnoreStart Needed "useless" override to change parameters.
34 public function __construct( $name = 'Recentchanges', $restriction = '' ) {
35 parent
::__construct( $name, $restriction );
37 // @codingStandardsIgnoreEnd
40 * Main execution point
42 * @param string $subpage
44 public function execute( $subpage ) {
45 // Backwards-compatibility: redirect to new feed URLs
46 $feedFormat = $this->getRequest()->getVal( 'feed' );
47 if ( !$this->including() && $feedFormat ) {
48 $query = $this->getFeedQuery();
49 $query['feedformat'] = $feedFormat === 'atom' ?
'atom' : 'rss';
50 $this->getOutput()->redirect( wfAppendQuery( wfScript( 'api' ), $query ) );
55 // 10 seconds server-side caching max
56 $out = $this->getOutput();
57 $out->setCdnMaxage( 10 );
58 // Check if the client has a cached version
59 $lastmod = $this->checkLastModified();
60 if ( $lastmod === false ) {
65 '//meta.wikimedia.org/wiki/Special:MyLanguage/Help:Recent_changes',
68 parent
::execute( $subpage );
70 if ( $this->isStructuredFilterUiEnabled() ) {
71 $jsData = $this->getStructuredFilterJsData();
74 foreach ( $jsData['messageKeys'] as $key ){
75 $messages[$key] = $this->msg( $key )->plain();
79 ResourceLoader
::makeInlineScript(
80 Xml
::encodeJsCall( 'mw.messages.set', [
86 $out->addJsConfigVars( 'wgStructuredChangeFilters', $jsData['groups'] );
93 protected function registerFiltersFromDefinitions( array $definition ) {
94 foreach ( $definition as $groupName => &$groupDefinition ) {
95 foreach ( $groupDefinition['filters'] as &$filterDefinition ) {
96 if ( isset( $filterDefinition['showHideSuffix'] ) ) {
97 $filterDefinition['showHide'] = 'rc' . $filterDefinition['showHideSuffix'];
102 parent
::registerFiltersFromDefinitions( $definition );
108 protected function registerFilters() {
109 parent
::registerFilters();
111 $user = $this->getUser();
113 $significance = $this->getFilterGroup( 'significance' );
114 $hideMinor = $significance->getFilter( 'hideminor' );
115 $hideMinor->setDefault( $user->getBoolOption( 'hideminor' ) );
117 $automated = $this->getFilterGroup( 'automated' );
118 $hideBots = $automated->getFilter( 'hidebots' );
119 $hideBots->setDefault( true );
121 $reviewStatus = $this->getFilterGroup( 'reviewStatus' );
122 $hidePatrolled = $reviewStatus->getFilter( 'hidepatrolled' );
123 $hidePatrolled->setDefault( $user->getBoolOption( 'hidepatrolled' ) );
125 $changeType = $this->getFilterGroup( 'changeType' );
126 $hideCategorization = $changeType->getFilter( 'hidecategorization' );
127 $hideCategorization->setDefault( $user->getBoolOption( 'hidecategorization' ) );
131 * Get a FormOptions object containing the default options
133 * @return FormOptions
135 public function getDefaultOptions() {
136 $opts = parent
::getDefaultOptions();
137 $user = $this->getUser();
139 $opts->add( 'days', $user->getIntOption( 'rcdays' ) );
140 $opts->add( 'limit', $user->getIntOption( 'rclimit' ) );
141 $opts->add( 'from', '' );
143 $opts->add( 'categories', '' );
144 $opts->add( 'categories_any', false );
145 $opts->add( 'tagfilter', '' );
151 * Get all custom filters
153 * @return array Map of filter URL param names to properties (msg/default)
155 protected function getCustomFilters() {
156 if ( $this->customFilters
=== null ) {
157 $this->customFilters
= parent
::getCustomFilters();
158 Hooks
::run( 'SpecialRecentChangesFilters', [ $this, &$this->customFilters
], '1.23' );
161 return $this->customFilters
;
165 * Process $par and put options found in $opts. Used when including the page.
168 * @param FormOptions $opts
170 public function parseParameters( $par, FormOptions
$opts ) {
171 parent
::parseParameters( $par, $opts );
173 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
174 foreach ( $bits as $bit ) {
175 if ( is_numeric( $bit ) ) {
176 $opts['limit'] = $bit;
180 if ( preg_match( '/^limit=(\d+)$/', $bit, $m ) ) {
181 $opts['limit'] = $m[1];
183 if ( preg_match( '/^days=(\d+)$/', $bit, $m ) ) {
184 $opts['days'] = $m[1];
186 if ( preg_match( '/^namespace=(\d+)$/', $bit, $m ) ) {
187 $opts['namespace'] = $m[1];
189 if ( preg_match( '/^tagfilter=(.*)$/', $bit, $m ) ) {
190 $opts['tagfilter'] = $m[1];
195 public function validateOptions( FormOptions
$opts ) {
196 $opts->validateIntBounds( 'limit', 0, 5000 );
197 parent
::validateOptions( $opts );
203 protected function buildQuery( &$tables, &$fields, &$conds,
204 &$query_options, &$join_conds, FormOptions
$opts ) {
206 $dbr = $this->getDB();
207 parent
::buildQuery( $tables, $fields, $conds,
208 $query_options, $join_conds, $opts );
211 $cutoff_unixtime = time() - ( $opts['days'] * 86400 );
212 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
213 $cutoff = $dbr->timestamp( $cutoff_unixtime );
215 $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
216 if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW
, $cutoff ) ) {
217 $cutoff = $dbr->timestamp( $opts['from'] );
219 $opts->reset( 'from' );
222 $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
228 protected function doMainQuery( $tables, $fields, $conds, $query_options,
229 $join_conds, FormOptions
$opts ) {
231 $dbr = $this->getDB();
232 $user = $this->getUser();
234 $tables[] = 'recentchanges';
235 $fields = array_merge( RecentChange
::selectFields(), $fields );
237 // JOIN on watchlist for users
238 if ( $user->getId() && $user->isAllowed( 'viewmywatchlist' ) ) {
239 $tables[] = 'watchlist';
240 $fields[] = 'wl_user';
241 $fields[] = 'wl_notificationtimestamp';
242 $join_conds['watchlist'] = [ 'LEFT JOIN', [
243 'wl_user' => $user->getId(),
245 'wl_namespace=rc_namespace'
249 if ( $user->isAllowed( 'rollback' ) ) {
251 $fields[] = 'page_latest';
252 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
255 ChangeTags
::modifyDisplayQuery(
264 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
270 // array_merge() is used intentionally here so that hooks can, should
271 // they so desire, override the ORDER BY / LIMIT condition(s); prior to
272 // MediaWiki 1.26 this used to use the plus operator instead, which meant
273 // that extensions weren't able to change these conditions
274 $query_options = array_merge( [
275 'ORDER BY' => 'rc_timestamp DESC',
276 'LIMIT' => $opts['limit'] ], $query_options );
277 $rows = $dbr->select(
280 // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
281 // knowledge to use an index merge if it wants (it may use some other index though).
282 $conds +
[ 'rc_new' => [ 0, 1 ] ],
288 // Build the final data
289 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
290 $this->filterByCategories( $rows, $opts );
296 protected function runMainQueryHook( &$tables, &$fields, &$conds,
297 &$query_options, &$join_conds, $opts
299 return parent
::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
301 'SpecialRecentChangesQuery',
302 [ &$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields ],
307 protected function getDB() {
308 return wfGetDB( DB_REPLICA
, 'recentchanges' );
311 public function outputFeedLinks() {
312 $this->addFeedLinks( $this->getFeedQuery() );
316 * Get URL query parameters for action=feedrecentchanges API feed of current recent changes view.
320 protected function getFeedQuery() {
321 $query = array_filter( $this->getOptions()->getAllValues(), function ( $value ) {
322 // API handles empty parameters in a different way
323 return $value !== '';
325 $query['action'] = 'feedrecentchanges';
326 $feedLimit = $this->getConfig()->get( 'FeedLimit' );
327 if ( $query['limit'] > $feedLimit ) {
328 $query['limit'] = $feedLimit;
335 * Build and output the actual changes list.
337 * @param ResultWrapper $rows Database rows
338 * @param FormOptions $opts
340 public function outputChangesList( $rows, $opts ) {
341 $limit = $opts['limit'];
343 $showWatcherCount = $this->getConfig()->get( 'RCShowWatchingUsers' )
344 && $this->getUser()->getOption( 'shownumberswatching' );
347 $dbr = $this->getDB();
350 $list = ChangesList
::newFromContext( $this->getContext(), $this->filterGroups
);
351 $list->initChangesListRows( $rows );
353 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
354 $rclistOutput = $list->beginRecentChangesList();
355 foreach ( $rows as $obj ) {
359 $rc = RecentChange
::newFromRow( $obj );
361 # Skip CatWatch entries for hidden cats based on user preference
363 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE
&&
364 !$userShowHiddenCats &&
365 $rc->getParam( 'hidden-cat' )
370 $rc->counter
= $counter++
;
371 # Check if the page has been updated since the last visit
372 if ( $this->getConfig()->get( 'ShowUpdatedMarker' )
373 && !empty( $obj->wl_notificationtimestamp
)
375 $rc->notificationtimestamp
= ( $obj->rc_timestamp
>= $obj->wl_notificationtimestamp
);
377 $rc->notificationtimestamp
= false; // Default
379 # Check the number of users watching the page
380 $rc->numberofWatchingusers
= 0; // Default
381 if ( $showWatcherCount && $obj->rc_namespace
>= 0 ) {
382 if ( !isset( $watcherCache[$obj->rc_namespace
][$obj->rc_title
] ) ) {
383 $watcherCache[$obj->rc_namespace
][$obj->rc_title
] =
384 MediaWikiServices
::getInstance()->getWatchedItemStore()->countWatchers(
385 new TitleValue( (int)$obj->rc_namespace
, $obj->rc_title
)
388 $rc->numberofWatchingusers
= $watcherCache[$obj->rc_namespace
][$obj->rc_title
];
391 $changeLine = $list->recentChangesLine( $rc, !empty( $obj->wl_user
), $counter );
392 if ( $changeLine !== false ) {
393 $rclistOutput .= $changeLine;
397 $rclistOutput .= $list->endRecentChangesList();
399 if ( $rows->numRows() === 0 ) {
400 $this->getOutput()->addHTML(
401 '<div class="mw-changeslist-empty">' .
402 $this->msg( 'recentchanges-noresult' )->parse() .
405 if ( !$this->including() ) {
406 $this->getOutput()->setStatusCode( 404 );
409 $this->getOutput()->addHTML( $rclistOutput );
414 * Set the text to be displayed above the changes
416 * @param FormOptions $opts
417 * @param int $numRows Number of rows in the result to show after this header
419 public function doHeader( $opts, $numRows ) {
420 $this->setTopText( $opts );
422 $defaults = $opts->getAllValues();
423 $nondefaults = $opts->getChangedValues();
426 $panel[] = $this->makeLegend();
427 $panel[] = $this->optionsPanel( $defaults, $nondefaults, $numRows );
430 $extraOpts = $this->getExtraOptions( $opts );
431 $extraOptsCount = count( $extraOpts );
433 $submit = ' ' . Xml
::submitButton( $this->msg( 'recentchanges-submit' )->text() );
435 $out = Xml
::openElement( 'table', [ 'class' => 'mw-recentchanges-table' ] );
436 foreach ( $extraOpts as $name => $optionRow ) {
437 # Add submit button to the last row only
439 $addSubmit = ( $count === $extraOptsCount ) ?
$submit : '';
441 $out .= Xml
::openElement( 'tr' );
442 if ( is_array( $optionRow ) ) {
445 [ 'class' => 'mw-label mw-' . $name . '-label' ],
450 [ 'class' => 'mw-input' ],
451 $optionRow[1] . $addSubmit
456 [ 'class' => 'mw-input', 'colspan' => 2 ],
457 $optionRow . $addSubmit
460 $out .= Xml
::closeElement( 'tr' );
462 $out .= Xml
::closeElement( 'table' );
464 $unconsumed = $opts->getUnconsumedValues();
465 foreach ( $unconsumed as $key => $value ) {
466 $out .= Html
::hidden( $key, $value );
469 $t = $this->getPageTitle();
470 $out .= Html
::hidden( 'title', $t->getPrefixedText() );
471 $form = Xml
::tags( 'form', [ 'action' => wfScript() ], $out );
473 $panelString = implode( "\n", $panel );
475 $rcoptions = Xml
::fieldset(
476 $this->msg( 'recentchanges-legend' )->text(),
478 [ 'class' => 'rcoptions' ]
481 // Insert a placeholder for RCFilters
482 if ( $this->getUser()->getOption( 'rcenhancedfilters' ) ) {
483 $rcfilterContainer = Html
::element(
485 [ 'class' => 'rcfilters-container' ]
488 // Wrap both with rcfilters-head
489 $this->getOutput()->addHTML(
492 [ 'class' => 'rcfilters-head' ],
493 $rcfilterContainer . $rcoptions
497 $this->getOutput()->addHTML( $rcoptions );
500 $this->setBottomText( $opts );
504 * Send the text to be displayed above the options
506 * @param FormOptions $opts Unused
508 function setTopText( FormOptions
$opts ) {
511 $message = $this->msg( 'recentchangestext' )->inContentLanguage();
512 if ( !$message->isDisabled() ) {
513 $this->getOutput()->addWikiText(
514 Html
::rawElement( 'div',
515 [ 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ],
516 "\n" . $message->plain() . "\n"
518 /* $lineStart */ true,
519 /* $interface */ false
525 * Get options to be displayed in a form
527 * @param FormOptions $opts
530 function getExtraOptions( $opts ) {
531 $opts->consumeValues( [
532 'namespace', 'invert', 'associated', 'tagfilter', 'categories', 'categories_any'
536 $extraOpts['namespace'] = $this->namespaceFilterForm( $opts );
538 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
539 $extraOpts['category'] = $this->categoryFilterForm( $opts );
542 $tagFilter = ChangeTags
::buildTagFilterSelector(
543 $opts['tagfilter'], false, $this->getContext() );
544 if ( count( $tagFilter ) ) {
545 $extraOpts['tagfilter'] = $tagFilter;
548 // Don't fire the hook for subclasses. (Or should we?)
549 if ( $this->getName() === 'Recentchanges' ) {
550 Hooks
::run( 'SpecialRecentChangesPanel', [ &$extraOpts, $opts ] );
557 * Check whether the structured filter UI is enabled
561 protected function isStructuredFilterUiEnabled() {
562 return $this->getUser()->getOption(
568 * Add page-specific modules.
570 protected function addModules() {
571 parent
::addModules();
572 $out = $this->getOutput();
573 $out->addModules( 'mediawiki.special.recentchanges' );
574 if ( $this->isStructuredFilterUiEnabled() ) {
575 $out->addModules( 'mediawiki.rcfilters.filters.ui' );
576 $out->addModuleStyles( 'mediawiki.rcfilters.filters.base.styles' );
581 * Get last modified date, for client caching
582 * Don't use this if we are using the patrol feature, patrol changes don't
583 * update the timestamp
585 * @return string|bool
587 public function checkLastModified() {
588 $dbr = $this->getDB();
589 $lastmod = $dbr->selectField( 'recentchanges', 'MAX(rc_timestamp)', false, __METHOD__
);
595 * Creates the choose namespace selection
597 * @param FormOptions $opts
600 protected function namespaceFilterForm( FormOptions
$opts ) {
601 $nsSelect = Html
::namespaceSelector(
602 [ 'selected' => $opts['namespace'], 'all' => '' ],
603 [ 'name' => 'namespace', 'id' => 'namespace' ]
605 $nsLabel = Xml
::label( $this->msg( 'namespace' )->text(), 'namespace' );
606 $invert = Xml
::checkLabel(
607 $this->msg( 'invert' )->text(), 'invert', 'nsinvert',
609 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
611 $associated = Xml
::checkLabel(
612 $this->msg( 'namespace_association' )->text(), 'associated', 'nsassociated',
614 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
617 return [ $nsLabel, "$nsSelect $invert $associated" ];
621 * Create an input to filter changes by categories
623 * @param FormOptions $opts
626 protected function categoryFilterForm( FormOptions
$opts ) {
627 list( $label, $input ) = Xml
::inputLabelSep( $this->msg( 'rc_categories' )->text(),
628 'categories', 'mw-categories', false, $opts['categories'] );
630 $input .= ' ' . Xml
::checkLabel( $this->msg( 'rc_categories_any' )->text(),
631 'categories_any', 'mw-categories_any', $opts['categories_any'] );
633 return [ $label, $input ];
637 * Filter $rows by categories set in $opts
639 * @param ResultWrapper $rows Database rows
640 * @param FormOptions $opts
642 function filterByCategories( &$rows, FormOptions
$opts ) {
643 $categories = array_map( 'trim', explode( '|', $opts['categories'] ) );
645 if ( !count( $categories ) ) {
651 foreach ( $categories as $cat ) {
663 foreach ( $rows as $k => $r ) {
664 $nt = Title
::makeTitle( $r->rc_namespace
, $r->rc_title
);
665 $id = $nt->getArticleID();
667 continue; # Page might have been deleted...
669 if ( !in_array( $id, $articles ) ) {
672 if ( !isset( $a2r[$id] ) ) {
680 if ( !count( $articles ) ||
!count( $cats ) ) {
685 $catFind = new CategoryFinder
;
686 $catFind->seed( $articles, $cats, $opts['categories_any'] ?
'OR' : 'AND' );
687 $match = $catFind->run();
691 foreach ( $match as $id ) {
692 foreach ( $a2r[$id] as $rev ) {
694 $newrows[$k] = $rowsarr[$k];
701 * Makes change an option link which carries all the other options
703 * @param string $title Title
704 * @param array $override Options to override
705 * @param array $options Current options
706 * @param bool $active Whether to show the link in bold
709 function makeOptionsLink( $title, $override, $options, $active = false ) {
710 $params = $override +
$options;
712 // T38524: false values have be converted to "0" otherwise
713 // wfArrayToCgi() will omit it them.
714 foreach ( $params as &$value ) {
715 if ( $value === false ) {
722 $title = new HtmlArmor( '<strong>' . htmlspecialchars( $title ) . '</strong>' );
725 return $this->getLinkRenderer()->makeKnownLink( $this->getPageTitle(), $title, [
726 'data-params' => json_encode( $override ),
727 'data-keys' => implode( ',', array_keys( $override ) ),
732 * Creates the options panel.
734 * @param array $defaults
735 * @param array $nondefaults
736 * @param int $numRows Number of rows in the result to show after this header
739 function optionsPanel( $defaults, $nondefaults, $numRows ) {
740 $options = $nondefaults +
$defaults;
743 $msg = $this->msg( 'rclegend' );
744 if ( !$msg->isDisabled() ) {
745 $note .= '<div class="mw-rclegend">' . $msg->parse() . "</div>\n";
748 $lang = $this->getLanguage();
749 $user = $this->getUser();
750 $config = $this->getConfig();
751 if ( $options['from'] ) {
752 $note .= $this->msg( 'rcnotefrom' )
753 ->numParams( $options['limit'] )
755 $lang->userTimeAndDate( $options['from'], $user ),
756 $lang->userDate( $options['from'], $user ),
757 $lang->userTime( $options['from'], $user )
759 ->numParams( $numRows )
760 ->parse() . '<br />';
763 # Sort data for display and make sure it's unique after we've added user data.
764 $linkLimits = $config->get( 'RCLinkLimits' );
765 $linkLimits[] = $options['limit'];
767 $linkLimits = array_unique( $linkLimits );
769 $linkDays = $config->get( 'RCLinkDays' );
770 $linkDays[] = $options['days'];
772 $linkDays = array_unique( $linkDays );
776 foreach ( $linkLimits as $value ) {
777 $cl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
778 [ 'limit' => $value ], $nondefaults, $value == $options['limit'] );
780 $cl = $lang->pipeList( $cl );
782 // day links, reset 'from' to none
784 foreach ( $linkDays as $value ) {
785 $dl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
786 [ 'days' => $value, 'from' => '' ], $nondefaults, $value == $options['days'] );
788 $dl = $lang->pipeList( $dl );
790 $showhide = [ 'show', 'hide' ];
794 $filterGroups = $this->getFilterGroups();
796 $context = $this->getContext();
797 foreach ( $filterGroups as $groupName => $group ) {
798 if ( !$group->isPerGroupRequestParameter() ) {
799 foreach ( $group->getFilters() as $key => $filter ) {
800 if ( $filter->displaysOnUnstructuredUi( $this ) ) {
801 $msg = $filter->getShowHide();
802 $linkMessage = $this->msg( $msg . '-' . $showhide[1 - $options[$key]] );
803 // Extensions can define additional filters, but don't need to define the corresponding
804 // messages. If they don't exist, just fall back to 'show' and 'hide'.
805 if ( !$linkMessage->exists() ) {
806 $linkMessage = $this->msg( $showhide[1 - $options[$key]] );
809 $link = $this->makeOptionsLink( $linkMessage->text(),
810 [ $key => 1 - $options[$key] ], $nondefaults );
813 'class' => "$msg rcshowhideoption",
814 'data-filter-name' => $filter->getName(),
817 if ( $filter->isFeatureAvailableOnStructuredUi( $this ) ) {
818 $attribs['data-feature-in-structured-ui'] = true;
821 $links[] = Html
::rawElement(
824 $this->msg( $msg )->rawParams( $link )->escaped()
831 // show from this onward link
832 $timestamp = wfTimestampNow();
833 $now = $lang->userTimeAndDate( $timestamp, $user );
834 $timenow = $lang->userTime( $timestamp, $user );
835 $datenow = $lang->userDate( $timestamp, $user );
836 $pipedLinks = '<span class="rcshowhide">' . $lang->pipeList( $links ) . '</span>';
838 $rclinks = '<span class="rclinks">' . $this->msg( 'rclinks' )->rawParams( $cl, $dl, $pipedLinks )
839 ->parse() . '</span>';
841 $rclistfrom = '<span class="rclistfrom">' . $this->makeOptionsLink(
842 $this->msg( 'rclistfrom' )->rawParams( $now, $timenow, $datenow )->parse(),
843 [ 'from' => $timestamp ],
847 return "{$note}$rclinks<br />$rclistfrom";
850 public function isIncludable() {
854 protected function getCacheTTL() {