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
;
26 use Wikimedia\Rdbms\FakeResultWrapper
;
29 * A special page that lists last changes made to the wiki
31 * @ingroup SpecialPage
33 class SpecialRecentChanges
extends ChangesListSpecialPage
{
34 // @codingStandardsIgnoreStart Needed "useless" override to change parameters.
35 public function __construct( $name = 'Recentchanges', $restriction = '' ) {
36 parent
::__construct( $name, $restriction );
38 // @codingStandardsIgnoreEnd
41 * Main execution point
43 * @param string $subpage
45 public function execute( $subpage ) {
46 // Backwards-compatibility: redirect to new feed URLs
47 $feedFormat = $this->getRequest()->getVal( 'feed' );
48 if ( !$this->including() && $feedFormat ) {
49 $query = $this->getFeedQuery();
50 $query['feedformat'] = $feedFormat === 'atom' ?
'atom' : 'rss';
51 $this->getOutput()->redirect( wfAppendQuery( wfScript( 'api' ), $query ) );
56 // 10 seconds server-side caching max
57 $out = $this->getOutput();
58 $out->setCdnMaxage( 10 );
59 // Check if the client has a cached version
60 $lastmod = $this->checkLastModified();
61 if ( $lastmod === false ) {
66 '//meta.wikimedia.org/wiki/Special:MyLanguage/Help:Recent_changes',
69 parent
::execute( $subpage );
71 if ( $this->isStructuredFilterUiEnabled() ) {
72 $jsData = $this->getStructuredFilterJsData();
75 foreach ( $jsData['messageKeys'] as $key ){
76 $messages[$key] = $this->msg( $key )->plain();
80 ResourceLoader
::makeInlineScript(
81 Xml
::encodeJsCall( 'mw.messages.set', [
87 $out->addJsConfigVars( 'wgStructuredChangeFilters', $jsData['groups'] );
94 protected function transformFilterDefinition( array $filterDefinition ) {
95 if ( isset( $filterDefinition['showHideSuffix'] ) ) {
96 $filterDefinition['showHide'] = 'rc' . $filterDefinition['showHideSuffix'];
99 return $filterDefinition;
105 protected function registerFilters() {
106 parent
::registerFilters();
108 $user = $this->getUser();
110 $significance = $this->getFilterGroup( 'significance' );
111 $hideMinor = $significance->getFilter( 'hideminor' );
112 $hideMinor->setDefault( $user->getBoolOption( 'hideminor' ) );
114 $automated = $this->getFilterGroup( 'automated' );
115 $hideBots = $automated->getFilter( 'hidebots' );
116 $hideBots->setDefault( true );
118 $reviewStatus = $this->getFilterGroup( 'reviewStatus' );
119 if ( $reviewStatus !== null ) {
120 // Conditional on feature being available and rights
121 $hidePatrolled = $reviewStatus->getFilter( 'hidepatrolled' );
122 $hidePatrolled->setDefault( $user->getBoolOption( 'hidepatrolled' ) );
125 $changeType = $this->getFilterGroup( 'changeType' );
126 $hideCategorization = $changeType->getFilter( 'hidecategorization' );
127 if ( $hideCategorization !== null ) {
128 // Conditional on feature being available
129 $hideCategorization->setDefault( $user->getBoolOption( 'hidecategorization' ) );
134 * Get a FormOptions object containing the default options
136 * @return FormOptions
138 public function getDefaultOptions() {
139 $opts = parent
::getDefaultOptions();
140 $user = $this->getUser();
142 $opts->add( 'days', $user->getIntOption( 'rcdays' ) );
143 $opts->add( 'limit', $user->getIntOption( 'rclimit' ) );
144 $opts->add( 'from', '' );
146 $opts->add( 'categories', '' );
147 $opts->add( 'categories_any', false );
148 $opts->add( 'tagfilter', '' );
154 * Get all custom filters
156 * @return array Map of filter URL param names to properties (msg/default)
158 protected function getCustomFilters() {
159 if ( $this->customFilters
=== null ) {
160 $this->customFilters
= parent
::getCustomFilters();
161 Hooks
::run( 'SpecialRecentChangesFilters', [ $this, &$this->customFilters
], '1.23' );
164 return $this->customFilters
;
168 * Process $par and put options found in $opts. Used when including the page.
171 * @param FormOptions $opts
173 public function parseParameters( $par, FormOptions
$opts ) {
174 parent
::parseParameters( $par, $opts );
176 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
177 foreach ( $bits as $bit ) {
178 if ( is_numeric( $bit ) ) {
179 $opts['limit'] = $bit;
183 if ( preg_match( '/^limit=(\d+)$/', $bit, $m ) ) {
184 $opts['limit'] = $m[1];
186 if ( preg_match( '/^days=(\d+)$/', $bit, $m ) ) {
187 $opts['days'] = $m[1];
189 if ( preg_match( '/^namespace=(\d+)$/', $bit, $m ) ) {
190 $opts['namespace'] = $m[1];
192 if ( preg_match( '/^tagfilter=(.*)$/', $bit, $m ) ) {
193 $opts['tagfilter'] = $m[1];
198 public function validateOptions( FormOptions
$opts ) {
199 $opts->validateIntBounds( 'limit', 0, 5000 );
200 parent
::validateOptions( $opts );
206 protected function buildQuery( &$tables, &$fields, &$conds,
207 &$query_options, &$join_conds, FormOptions
$opts ) {
209 $dbr = $this->getDB();
210 parent
::buildQuery( $tables, $fields, $conds,
211 $query_options, $join_conds, $opts );
214 $cutoff_unixtime = time() - ( $opts['days'] * 86400 );
215 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
216 $cutoff = $dbr->timestamp( $cutoff_unixtime );
218 $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
219 if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW
, $cutoff ) ) {
220 $cutoff = $dbr->timestamp( $opts['from'] );
222 $opts->reset( 'from' );
225 $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
231 protected function doMainQuery( $tables, $fields, $conds, $query_options,
232 $join_conds, FormOptions
$opts ) {
234 $dbr = $this->getDB();
235 $user = $this->getUser();
237 $tables[] = 'recentchanges';
238 $fields = array_merge( RecentChange
::selectFields(), $fields );
240 // JOIN on watchlist for users
241 if ( $user->getId() && $user->isAllowed( 'viewmywatchlist' ) ) {
242 $tables[] = 'watchlist';
243 $fields[] = 'wl_user';
244 $fields[] = 'wl_notificationtimestamp';
245 $join_conds['watchlist'] = [ 'LEFT JOIN', [
246 'wl_user' => $user->getId(),
248 'wl_namespace=rc_namespace'
252 if ( $user->isAllowed( 'rollback' ) ) {
254 $fields[] = 'page_latest';
255 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
258 ChangeTags
::modifyDisplayQuery(
267 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
273 // array_merge() is used intentionally here so that hooks can, should
274 // they so desire, override the ORDER BY / LIMIT condition(s); prior to
275 // MediaWiki 1.26 this used to use the plus operator instead, which meant
276 // that extensions weren't able to change these conditions
277 $query_options = array_merge( [
278 'ORDER BY' => 'rc_timestamp DESC',
279 'LIMIT' => $opts['limit'] ], $query_options );
280 $rows = $dbr->select(
283 // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
284 // knowledge to use an index merge if it wants (it may use some other index though).
285 $conds +
[ 'rc_new' => [ 0, 1 ] ],
291 // Build the final data
292 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
293 $this->filterByCategories( $rows, $opts );
299 protected function runMainQueryHook( &$tables, &$fields, &$conds,
300 &$query_options, &$join_conds, $opts
302 return parent
::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
304 'SpecialRecentChangesQuery',
305 [ &$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields ],
310 protected function getDB() {
311 return wfGetDB( DB_REPLICA
, 'recentchanges' );
314 public function outputFeedLinks() {
315 $this->addFeedLinks( $this->getFeedQuery() );
319 * Get URL query parameters for action=feedrecentchanges API feed of current recent changes view.
323 protected function getFeedQuery() {
324 $query = array_filter( $this->getOptions()->getAllValues(), function ( $value ) {
325 // API handles empty parameters in a different way
326 return $value !== '';
328 $query['action'] = 'feedrecentchanges';
329 $feedLimit = $this->getConfig()->get( 'FeedLimit' );
330 if ( $query['limit'] > $feedLimit ) {
331 $query['limit'] = $feedLimit;
338 * Build and output the actual changes list.
340 * @param ResultWrapper $rows Database rows
341 * @param FormOptions $opts
343 public function outputChangesList( $rows, $opts ) {
344 $limit = $opts['limit'];
346 $showWatcherCount = $this->getConfig()->get( 'RCShowWatchingUsers' )
347 && $this->getUser()->getOption( 'shownumberswatching' );
350 $dbr = $this->getDB();
353 $list = ChangesList
::newFromContext( $this->getContext(), $this->filterGroups
);
354 $list->initChangesListRows( $rows );
356 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
357 $rclistOutput = $list->beginRecentChangesList();
358 foreach ( $rows as $obj ) {
362 $rc = RecentChange
::newFromRow( $obj );
364 # Skip CatWatch entries for hidden cats based on user preference
366 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE
&&
367 !$userShowHiddenCats &&
368 $rc->getParam( 'hidden-cat' )
373 $rc->counter
= $counter++
;
374 # Check if the page has been updated since the last visit
375 if ( $this->getConfig()->get( 'ShowUpdatedMarker' )
376 && !empty( $obj->wl_notificationtimestamp
)
378 $rc->notificationtimestamp
= ( $obj->rc_timestamp
>= $obj->wl_notificationtimestamp
);
380 $rc->notificationtimestamp
= false; // Default
382 # Check the number of users watching the page
383 $rc->numberofWatchingusers
= 0; // Default
384 if ( $showWatcherCount && $obj->rc_namespace
>= 0 ) {
385 if ( !isset( $watcherCache[$obj->rc_namespace
][$obj->rc_title
] ) ) {
386 $watcherCache[$obj->rc_namespace
][$obj->rc_title
] =
387 MediaWikiServices
::getInstance()->getWatchedItemStore()->countWatchers(
388 new TitleValue( (int)$obj->rc_namespace
, $obj->rc_title
)
391 $rc->numberofWatchingusers
= $watcherCache[$obj->rc_namespace
][$obj->rc_title
];
394 $changeLine = $list->recentChangesLine( $rc, !empty( $obj->wl_user
), $counter );
395 if ( $changeLine !== false ) {
396 $rclistOutput .= $changeLine;
400 $rclistOutput .= $list->endRecentChangesList();
402 if ( $rows->numRows() === 0 ) {
403 $this->outputNoResults();
404 if ( !$this->including() ) {
405 $this->getOutput()->setStatusCode( 404 );
408 $this->getOutput()->addHTML( $rclistOutput );
413 * Set the text to be displayed above the changes
415 * @param FormOptions $opts
416 * @param int $numRows Number of rows in the result to show after this header
418 public function doHeader( $opts, $numRows ) {
419 $this->setTopText( $opts );
421 $defaults = $opts->getAllValues();
422 $nondefaults = $opts->getChangedValues();
425 $panel[] = $this->makeLegend();
426 $panel[] = $this->optionsPanel( $defaults, $nondefaults, $numRows );
429 $extraOpts = $this->getExtraOptions( $opts );
430 $extraOptsCount = count( $extraOpts );
432 $submit = ' ' . Xml
::submitButton( $this->msg( 'recentchanges-submit' )->text() );
434 $out = Xml
::openElement( 'table', [ 'class' => 'mw-recentchanges-table' ] );
435 foreach ( $extraOpts as $name => $optionRow ) {
436 # Add submit button to the last row only
438 $addSubmit = ( $count === $extraOptsCount ) ?
$submit : '';
440 $out .= Xml
::openElement( 'tr' );
441 if ( is_array( $optionRow ) ) {
444 [ 'class' => 'mw-label mw-' . $name . '-label' ],
449 [ 'class' => 'mw-input' ],
450 $optionRow[1] . $addSubmit
455 [ 'class' => 'mw-input', 'colspan' => 2 ],
456 $optionRow . $addSubmit
459 $out .= Xml
::closeElement( 'tr' );
461 $out .= Xml
::closeElement( 'table' );
463 $unconsumed = $opts->getUnconsumedValues();
464 foreach ( $unconsumed as $key => $value ) {
465 $out .= Html
::hidden( $key, $value );
468 $t = $this->getPageTitle();
469 $out .= Html
::hidden( 'title', $t->getPrefixedText() );
470 $form = Xml
::tags( 'form', [ 'action' => wfScript() ], $out );
472 $panelString = implode( "\n", $panel );
474 $rcoptions = Xml
::fieldset(
475 $this->msg( 'recentchanges-legend' )->text(),
477 [ 'class' => 'rcoptions' ]
480 // Insert a placeholder for RCFilters
481 if ( $this->getUser()->getOption( 'rcenhancedfilters' ) ) {
482 $rcfilterContainer = Html
::element(
484 [ 'class' => 'rcfilters-container' ]
487 // Wrap both with rcfilters-head
488 $this->getOutput()->addHTML(
491 [ 'class' => 'rcfilters-head' ],
492 $rcfilterContainer . $rcoptions
496 $this->getOutput()->addHTML( $rcoptions );
499 $this->setBottomText( $opts );
503 * Send the text to be displayed above the options
505 * @param FormOptions $opts Unused
507 function setTopText( FormOptions
$opts ) {
510 $message = $this->msg( 'recentchangestext' )->inContentLanguage();
511 if ( !$message->isDisabled() ) {
512 $this->getOutput()->addWikiText(
513 Html
::rawElement( 'div',
514 [ 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ],
515 "\n" . $message->plain() . "\n"
517 /* $lineStart */ true,
518 /* $interface */ false
524 * Get options to be displayed in a form
526 * @param FormOptions $opts
529 function getExtraOptions( $opts ) {
530 $opts->consumeValues( [
531 'namespace', 'invert', 'associated', 'tagfilter', 'categories', 'categories_any'
535 $extraOpts['namespace'] = $this->namespaceFilterForm( $opts );
537 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
538 $extraOpts['category'] = $this->categoryFilterForm( $opts );
541 $tagFilter = ChangeTags
::buildTagFilterSelector(
542 $opts['tagfilter'], false, $this->getContext() );
543 if ( count( $tagFilter ) ) {
544 $extraOpts['tagfilter'] = $tagFilter;
547 // Don't fire the hook for subclasses. (Or should we?)
548 if ( $this->getName() === 'Recentchanges' ) {
549 Hooks
::run( 'SpecialRecentChangesPanel', [ &$extraOpts, $opts ] );
556 * Check whether the structured filter UI is enabled
560 protected function isStructuredFilterUiEnabled() {
561 return $this->getUser()->getOption(
567 * Add page-specific modules.
569 protected function addModules() {
570 parent
::addModules();
571 $out = $this->getOutput();
572 $out->addModules( 'mediawiki.special.recentchanges' );
573 if ( $this->isStructuredFilterUiEnabled() ) {
574 $out->addModules( 'mediawiki.rcfilters.filters.ui' );
575 $out->addModuleStyles( 'mediawiki.rcfilters.filters.base.styles' );
580 * Get last modified date, for client caching
581 * Don't use this if we are using the patrol feature, patrol changes don't
582 * update the timestamp
584 * @return string|bool
586 public function checkLastModified() {
587 $dbr = $this->getDB();
588 $lastmod = $dbr->selectField( 'recentchanges', 'MAX(rc_timestamp)', false, __METHOD__
);
594 * Creates the choose namespace selection
596 * @param FormOptions $opts
599 protected function namespaceFilterForm( FormOptions
$opts ) {
600 $nsSelect = Html
::namespaceSelector(
601 [ 'selected' => $opts['namespace'], 'all' => '' ],
602 [ 'name' => 'namespace', 'id' => 'namespace' ]
604 $nsLabel = Xml
::label( $this->msg( 'namespace' )->text(), 'namespace' );
605 $invert = Xml
::checkLabel(
606 $this->msg( 'invert' )->text(), 'invert', 'nsinvert',
608 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
610 $associated = Xml
::checkLabel(
611 $this->msg( 'namespace_association' )->text(), 'associated', 'nsassociated',
613 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
616 return [ $nsLabel, "$nsSelect $invert $associated" ];
620 * Create an input to filter changes by categories
622 * @param FormOptions $opts
625 protected function categoryFilterForm( FormOptions
$opts ) {
626 list( $label, $input ) = Xml
::inputLabelSep( $this->msg( 'rc_categories' )->text(),
627 'categories', 'mw-categories', false, $opts['categories'] );
629 $input .= ' ' . Xml
::checkLabel( $this->msg( 'rc_categories_any' )->text(),
630 'categories_any', 'mw-categories_any', $opts['categories_any'] );
632 return [ $label, $input ];
636 * Filter $rows by categories set in $opts
638 * @param ResultWrapper $rows Database rows
639 * @param FormOptions $opts
641 function filterByCategories( &$rows, FormOptions
$opts ) {
642 $categories = array_map( 'trim', explode( '|', $opts['categories'] ) );
644 if ( !count( $categories ) ) {
650 foreach ( $categories as $cat ) {
662 foreach ( $rows as $k => $r ) {
663 $nt = Title
::makeTitle( $r->rc_namespace
, $r->rc_title
);
664 $id = $nt->getArticleID();
666 continue; # Page might have been deleted...
668 if ( !in_array( $id, $articles ) ) {
671 if ( !isset( $a2r[$id] ) ) {
679 if ( !count( $articles ) ||
!count( $cats ) ) {
684 $catFind = new CategoryFinder
;
685 $catFind->seed( $articles, $cats, $opts['categories_any'] ?
'OR' : 'AND' );
686 $match = $catFind->run();
690 foreach ( $match as $id ) {
691 foreach ( $a2r[$id] as $rev ) {
693 $newrows[$k] = $rowsarr[$k];
696 $rows = new FakeResultWrapper( array_values( $newrows ) );
700 * Makes change an option link which carries all the other options
702 * @param string $title Title
703 * @param array $override Options to override
704 * @param array $options Current options
705 * @param bool $active Whether to show the link in bold
708 function makeOptionsLink( $title, $override, $options, $active = false ) {
709 $params = $override +
$options;
711 // T38524: false values have be converted to "0" otherwise
712 // wfArrayToCgi() will omit it them.
713 foreach ( $params as &$value ) {
714 if ( $value === false ) {
721 $title = new HtmlArmor( '<strong>' . htmlspecialchars( $title ) . '</strong>' );
724 return $this->getLinkRenderer()->makeKnownLink( $this->getPageTitle(), $title, [
725 'data-params' => json_encode( $override ),
726 'data-keys' => implode( ',', array_keys( $override ) ),
731 * Creates the options panel.
733 * @param array $defaults
734 * @param array $nondefaults
735 * @param int $numRows Number of rows in the result to show after this header
738 function optionsPanel( $defaults, $nondefaults, $numRows ) {
739 $options = $nondefaults +
$defaults;
742 $msg = $this->msg( 'rclegend' );
743 if ( !$msg->isDisabled() ) {
744 $note .= '<div class="mw-rclegend">' . $msg->parse() . "</div>\n";
747 $lang = $this->getLanguage();
748 $user = $this->getUser();
749 $config = $this->getConfig();
750 if ( $options['from'] ) {
751 $note .= $this->msg( 'rcnotefrom' )
752 ->numParams( $options['limit'] )
754 $lang->userTimeAndDate( $options['from'], $user ),
755 $lang->userDate( $options['from'], $user ),
756 $lang->userTime( $options['from'], $user )
758 ->numParams( $numRows )
759 ->parse() . '<br />';
762 # Sort data for display and make sure it's unique after we've added user data.
763 $linkLimits = $config->get( 'RCLinkLimits' );
764 $linkLimits[] = $options['limit'];
766 $linkLimits = array_unique( $linkLimits );
768 $linkDays = $config->get( 'RCLinkDays' );
769 $linkDays[] = $options['days'];
771 $linkDays = array_unique( $linkDays );
775 foreach ( $linkLimits as $value ) {
776 $cl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
777 [ 'limit' => $value ], $nondefaults, $value == $options['limit'] );
779 $cl = $lang->pipeList( $cl );
781 // day links, reset 'from' to none
783 foreach ( $linkDays as $value ) {
784 $dl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
785 [ 'days' => $value, 'from' => '' ], $nondefaults, $value == $options['days'] );
787 $dl = $lang->pipeList( $dl );
789 $showhide = [ 'show', 'hide' ];
793 $filterGroups = $this->getFilterGroups();
795 $context = $this->getContext();
796 foreach ( $filterGroups as $groupName => $group ) {
797 if ( !$group->isPerGroupRequestParameter() ) {
798 foreach ( $group->getFilters() as $key => $filter ) {
799 if ( $filter->displaysOnUnstructuredUi( $this ) ) {
800 $msg = $filter->getShowHide();
801 $linkMessage = $this->msg( $msg . '-' . $showhide[1 - $options[$key]] );
802 // Extensions can define additional filters, but don't need to define the corresponding
803 // messages. If they don't exist, just fall back to 'show' and 'hide'.
804 if ( !$linkMessage->exists() ) {
805 $linkMessage = $this->msg( $showhide[1 - $options[$key]] );
808 $link = $this->makeOptionsLink( $linkMessage->text(),
809 [ $key => 1 - $options[$key] ], $nondefaults );
812 'class' => "$msg rcshowhideoption",
813 'data-filter-name' => $filter->getName(),
816 if ( $filter->isFeatureAvailableOnStructuredUi( $this ) ) {
817 $attribs['data-feature-in-structured-ui'] = true;
820 $links[] = Html
::rawElement(
823 $this->msg( $msg )->rawParams( $link )->escaped()
830 // show from this onward link
831 $timestamp = wfTimestampNow();
832 $now = $lang->userTimeAndDate( $timestamp, $user );
833 $timenow = $lang->userTime( $timestamp, $user );
834 $datenow = $lang->userDate( $timestamp, $user );
835 $pipedLinks = '<span class="rcshowhide">' . $lang->pipeList( $links ) . '</span>';
837 $rclinks = '<span class="rclinks">' . $this->msg( 'rclinks' )->rawParams( $cl, $dl, $pipedLinks )
838 ->parse() . '</span>';
840 $rclistfrom = '<span class="rclistfrom">' . $this->makeOptionsLink(
841 $this->msg( 'rclistfrom' )->rawParams( $now, $timenow, $datenow )->parse(),
842 [ 'from' => $timestamp ],
846 return "{$note}$rclinks<br />$rclistfrom";
849 public function isIncludable() {
853 protected function getCacheTTL() {