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
25 * A special page that lists last changes made to the wiki
27 * @ingroup SpecialPage
29 class SpecialRecentChanges
extends ChangesListSpecialPage
{
30 // @codingStandardsIgnoreStart Needed "useless" override to change parameters.
31 public function __construct( $name = 'Recentchanges', $restriction = '' ) {
32 parent
::__construct( $name, $restriction );
34 // @codingStandardsIgnoreEnd
37 * Main execution point
39 * @param string $subpage
41 public function execute( $subpage ) {
42 // Backwards-compatibility: redirect to new feed URLs
43 $feedFormat = $this->getRequest()->getVal( 'feed' );
44 if ( !$this->including() && $feedFormat ) {
45 $query = $this->getFeedQuery();
46 $query['feedformat'] = $feedFormat === 'atom' ?
'atom' : 'rss';
47 $this->getOutput()->redirect( wfAppendQuery( wfScript( 'api' ), $query ) );
52 // 10 seconds server-side caching max
53 $this->getOutput()->setCdnMaxage( 10 );
54 // Check if the client has a cached version
55 $lastmod = $this->checkLastModified();
56 if ( $lastmod === false ) {
61 '//meta.wikimedia.org/wiki/Special:MyLanguage/Help:Recent_changes',
64 parent
::execute( $subpage );
68 * Get a FormOptions object containing the default options
72 public function getDefaultOptions() {
73 $opts = parent
::getDefaultOptions();
74 $user = $this->getUser();
76 $opts->add( 'days', $user->getIntOption( 'rcdays' ) );
77 $opts->add( 'limit', $user->getIntOption( 'rclimit' ) );
78 $opts->add( 'from', '' );
80 $opts->add( 'hideminor', $user->getBoolOption( 'hideminor' ) );
81 $opts->add( 'hidebots', true );
82 $opts->add( 'hideanons', false );
83 $opts->add( 'hideliu', false );
84 $opts->add( 'hidepatrolled', $user->getBoolOption( 'hidepatrolled' ) );
85 $opts->add( 'hidemyself', false );
86 $opts->add( 'hidecategorization', $user->getBoolOption( 'hidecategorization' ) );
88 $opts->add( 'categories', '' );
89 $opts->add( 'categories_any', false );
90 $opts->add( 'tagfilter', '' );
96 * Get custom show/hide filters
98 * @return array Map of filter URL param names to properties (msg/default)
100 protected function getCustomFilters() {
101 if ( $this->customFilters
=== null ) {
102 $this->customFilters
= parent
::getCustomFilters();
103 Hooks
::run( 'SpecialRecentChangesFilters', [ $this, &$this->customFilters
], '1.23' );
106 return $this->customFilters
;
110 * Process $par and put options found in $opts. Used when including the page.
113 * @param FormOptions $opts
115 public function parseParameters( $par, FormOptions
$opts ) {
116 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
117 foreach ( $bits as $bit ) {
118 if ( 'hidebots' === $bit ) {
119 $opts['hidebots'] = true;
121 if ( 'bots' === $bit ) {
122 $opts['hidebots'] = false;
124 if ( 'hideminor' === $bit ) {
125 $opts['hideminor'] = true;
127 if ( 'minor' === $bit ) {
128 $opts['hideminor'] = false;
130 if ( 'hideliu' === $bit ) {
131 $opts['hideliu'] = true;
133 if ( 'hidepatrolled' === $bit ) {
134 $opts['hidepatrolled'] = true;
136 if ( 'hideanons' === $bit ) {
137 $opts['hideanons'] = true;
139 if ( 'hidemyself' === $bit ) {
140 $opts['hidemyself'] = true;
142 if ( 'hidecategorization' === $bit ) {
143 $opts['hidecategorization'] = true;
146 if ( is_numeric( $bit ) ) {
147 $opts['limit'] = $bit;
151 if ( preg_match( '/^limit=(\d+)$/', $bit, $m ) ) {
152 $opts['limit'] = $m[1];
154 if ( preg_match( '/^days=(\d+)$/', $bit, $m ) ) {
155 $opts['days'] = $m[1];
157 if ( preg_match( '/^namespace=(\d+)$/', $bit, $m ) ) {
158 $opts['namespace'] = $m[1];
163 public function validateOptions( FormOptions
$opts ) {
164 $opts->validateIntBounds( 'limit', 0, 5000 );
165 parent
::validateOptions( $opts );
169 * Return an array of conditions depending of options set in $opts
171 * @param FormOptions $opts
174 public function buildMainQueryConds( FormOptions
$opts ) {
175 $dbr = $this->getDB();
176 $conds = parent
::buildMainQueryConds( $opts );
179 $cutoff_unixtime = time() - ( $opts['days'] * 86400 );
180 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
181 $cutoff = $dbr->timestamp( $cutoff_unixtime );
183 $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
184 if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW
, $cutoff ) ) {
185 $cutoff = $dbr->timestamp( $opts['from'] );
187 $opts->reset( 'from' );
190 $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
198 * @param array $conds
199 * @param FormOptions $opts
200 * @return bool|ResultWrapper Result or false (for Recentchangeslinked only)
202 public function doMainQuery( $conds, $opts ) {
203 $dbr = $this->getDB();
204 $user = $this->getUser();
206 $tables = [ 'recentchanges' ];
207 $fields = RecentChange
::selectFields();
211 // JOIN on watchlist for users
212 if ( $user->getId() && $user->isAllowed( 'viewmywatchlist' ) ) {
213 $tables[] = 'watchlist';
214 $fields[] = 'wl_user';
215 $fields[] = 'wl_notificationtimestamp';
216 $join_conds['watchlist'] = [ 'LEFT JOIN', [
217 'wl_user' => $user->getId(),
219 'wl_namespace=rc_namespace'
223 if ( $user->isAllowed( 'rollback' ) ) {
225 $fields[] = 'page_latest';
226 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
229 ChangeTags
::modifyDisplayQuery(
238 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
244 // array_merge() is used intentionally here so that hooks can, should
245 // they so desire, override the ORDER BY / LIMIT condition(s); prior to
246 // MediaWiki 1.26 this used to use the plus operator instead, which meant
247 // that extensions weren't able to change these conditions
248 $query_options = array_merge( [
249 'ORDER BY' => 'rc_timestamp DESC',
250 'LIMIT' => $opts['limit'] ], $query_options );
251 $rows = $dbr->select(
254 // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
255 // knowledge to use an index merge if it wants (it may use some other index though).
256 $conds +
[ 'rc_new' => [ 0, 1 ] ],
262 // Build the final data
263 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
264 $this->filterByCategories( $rows, $opts );
270 protected function runMainQueryHook( &$tables, &$fields, &$conds,
271 &$query_options, &$join_conds, $opts
273 return parent
::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
275 'SpecialRecentChangesQuery',
276 [ &$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields ],
281 protected function getDB() {
282 return wfGetDB( DB_SLAVE
, 'recentchanges' );
285 public function outputFeedLinks() {
286 $this->addFeedLinks( $this->getFeedQuery() );
290 * Get URL query parameters for action=feedrecentchanges API feed of current recent changes view.
294 protected function getFeedQuery() {
295 $query = array_filter( $this->getOptions()->getAllValues(), function ( $value ) {
296 // API handles empty parameters in a different way
297 return $value !== '';
299 $query['action'] = 'feedrecentchanges';
300 $feedLimit = $this->getConfig()->get( 'FeedLimit' );
301 if ( $query['limit'] > $feedLimit ) {
302 $query['limit'] = $feedLimit;
309 * Build and output the actual changes list.
311 * @param array $rows Database rows
312 * @param FormOptions $opts
314 public function outputChangesList( $rows, $opts ) {
315 $limit = $opts['limit'];
317 $showWatcherCount = $this->getConfig()->get( 'RCShowWatchingUsers' )
318 && $this->getUser()->getOption( 'shownumberswatching' );
321 $dbr = $this->getDB();
324 $list = ChangesList
::newFromContext( $this->getContext() );
325 $list->initChangesListRows( $rows );
327 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
328 $rclistOutput = $list->beginRecentChangesList();
329 foreach ( $rows as $obj ) {
333 $rc = RecentChange
::newFromRow( $obj );
335 # Skip CatWatch entries for hidden cats based on user preference
337 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE
&&
338 !$userShowHiddenCats &&
339 $rc->getParam( 'hidden-cat' )
344 $rc->counter
= $counter++
;
345 # Check if the page has been updated since the last visit
346 if ( $this->getConfig()->get( 'ShowUpdatedMarker' )
347 && !empty( $obj->wl_notificationtimestamp
)
349 $rc->notificationtimestamp
= ( $obj->rc_timestamp
>= $obj->wl_notificationtimestamp
);
351 $rc->notificationtimestamp
= false; // Default
353 # Check the number of users watching the page
354 $rc->numberofWatchingusers
= 0; // Default
355 if ( $showWatcherCount && $obj->rc_namespace
>= 0 ) {
356 if ( !isset( $watcherCache[$obj->rc_namespace
][$obj->rc_title
] ) ) {
357 $watcherCache[$obj->rc_namespace
][$obj->rc_title
] =
362 'wl_namespace' => $obj->rc_namespace
,
363 'wl_title' => $obj->rc_title
,
365 __METHOD__
. '-watchers'
368 $rc->numberofWatchingusers
= $watcherCache[$obj->rc_namespace
][$obj->rc_title
];
371 $changeLine = $list->recentChangesLine( $rc, !empty( $obj->wl_user
), $counter );
372 if ( $changeLine !== false ) {
373 $rclistOutput .= $changeLine;
377 $rclistOutput .= $list->endRecentChangesList();
379 if ( $rows->numRows() === 0 ) {
380 $this->getOutput()->addHTML(
381 '<div class="mw-changeslist-empty">' .
382 $this->msg( 'recentchanges-noresult' )->parse() .
385 if ( !$this->including() ) {
386 $this->getOutput()->setStatusCode( 404 );
389 $this->getOutput()->addHTML( $rclistOutput );
394 * Set the text to be displayed above the changes
396 * @param FormOptions $opts
397 * @param int $numRows Number of rows in the result to show after this header
399 public function doHeader( $opts, $numRows ) {
400 $this->setTopText( $opts );
402 $defaults = $opts->getAllValues();
403 $nondefaults = $opts->getChangedValues();
406 $panel[] = $this->makeLegend();
407 $panel[] = $this->optionsPanel( $defaults, $nondefaults, $numRows );
410 $extraOpts = $this->getExtraOptions( $opts );
411 $extraOptsCount = count( $extraOpts );
413 $submit = ' ' . Xml
::submitButton( $this->msg( 'recentchanges-submit' )->text() );
415 $out = Xml
::openElement( 'table', [ 'class' => 'mw-recentchanges-table' ] );
416 foreach ( $extraOpts as $name => $optionRow ) {
417 # Add submit button to the last row only
419 $addSubmit = ( $count === $extraOptsCount ) ?
$submit : '';
421 $out .= Xml
::openElement( 'tr' );
422 if ( is_array( $optionRow ) ) {
425 [ 'class' => 'mw-label mw-' . $name . '-label' ],
430 [ 'class' => 'mw-input' ],
431 $optionRow[1] . $addSubmit
436 [ 'class' => 'mw-input', 'colspan' => 2 ],
437 $optionRow . $addSubmit
440 $out .= Xml
::closeElement( 'tr' );
442 $out .= Xml
::closeElement( 'table' );
444 $unconsumed = $opts->getUnconsumedValues();
445 foreach ( $unconsumed as $key => $value ) {
446 $out .= Html
::hidden( $key, $value );
449 $t = $this->getPageTitle();
450 $out .= Html
::hidden( 'title', $t->getPrefixedText() );
451 $form = Xml
::tags( 'form', [ 'action' => wfScript() ], $out );
453 $panelString = implode( "\n", $panel );
455 $this->getOutput()->addHTML(
457 $this->msg( 'recentchanges-legend' )->text(),
459 [ 'class' => 'rcoptions' ]
463 $this->setBottomText( $opts );
467 * Send the text to be displayed above the options
469 * @param FormOptions $opts Unused
471 function setTopText( FormOptions
$opts ) {
474 $message = $this->msg( 'recentchangestext' )->inContentLanguage();
475 if ( !$message->isDisabled() ) {
476 $this->getOutput()->addWikiText(
477 Html
::rawElement( 'div',
478 [ 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ],
479 "\n" . $message->plain() . "\n"
481 /* $lineStart */ true,
482 /* $interface */ false
488 * Get options to be displayed in a form
490 * @param FormOptions $opts
493 function getExtraOptions( $opts ) {
494 $opts->consumeValues( [
495 'namespace', 'invert', 'associated', 'tagfilter', 'categories', 'categories_any'
499 $extraOpts['namespace'] = $this->namespaceFilterForm( $opts );
501 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
502 $extraOpts['category'] = $this->categoryFilterForm( $opts );
505 $tagFilter = ChangeTags
::buildTagFilterSelector( $opts['tagfilter'] );
506 if ( count( $tagFilter ) ) {
507 $extraOpts['tagfilter'] = $tagFilter;
510 // Don't fire the hook for subclasses. (Or should we?)
511 if ( $this->getName() === 'Recentchanges' ) {
512 Hooks
::run( 'SpecialRecentChangesPanel', [ &$extraOpts, $opts ] );
519 * Add page-specific modules.
521 protected function addModules() {
522 parent
::addModules();
523 $out = $this->getOutput();
524 $out->addModules( 'mediawiki.special.recentchanges' );
528 * Get last modified date, for client caching
529 * Don't use this if we are using the patrol feature, patrol changes don't
530 * update the timestamp
532 * @return string|bool
534 public function checkLastModified() {
535 $dbr = $this->getDB();
536 $lastmod = $dbr->selectField( 'recentchanges', 'MAX(rc_timestamp)', false, __METHOD__
);
542 * Creates the choose namespace selection
544 * @param FormOptions $opts
547 protected function namespaceFilterForm( FormOptions
$opts ) {
548 $nsSelect = Html
::namespaceSelector(
549 [ 'selected' => $opts['namespace'], 'all' => '' ],
550 [ 'name' => 'namespace', 'id' => 'namespace' ]
552 $nsLabel = Xml
::label( $this->msg( 'namespace' )->text(), 'namespace' );
553 $invert = Xml
::checkLabel(
554 $this->msg( 'invert' )->text(), 'invert', 'nsinvert',
556 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
558 $associated = Xml
::checkLabel(
559 $this->msg( 'namespace_association' )->text(), 'associated', 'nsassociated',
561 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
564 return [ $nsLabel, "$nsSelect $invert $associated" ];
568 * Create an input to filter changes by categories
570 * @param FormOptions $opts
573 protected function categoryFilterForm( FormOptions
$opts ) {
574 list( $label, $input ) = Xml
::inputLabelSep( $this->msg( 'rc_categories' )->text(),
575 'categories', 'mw-categories', false, $opts['categories'] );
577 $input .= ' ' . Xml
::checkLabel( $this->msg( 'rc_categories_any' )->text(),
578 'categories_any', 'mw-categories_any', $opts['categories_any'] );
580 return [ $label, $input ];
584 * Filter $rows by categories set in $opts
586 * @param ResultWrapper $rows Database rows
587 * @param FormOptions $opts
589 function filterByCategories( &$rows, FormOptions
$opts ) {
590 $categories = array_map( 'trim', explode( '|', $opts['categories'] ) );
592 if ( !count( $categories ) ) {
598 foreach ( $categories as $cat ) {
610 foreach ( $rows as $k => $r ) {
611 $nt = Title
::makeTitle( $r->rc_namespace
, $r->rc_title
);
612 $id = $nt->getArticleID();
614 continue; # Page might have been deleted...
616 if ( !in_array( $id, $articles ) ) {
619 if ( !isset( $a2r[$id] ) ) {
627 if ( !count( $articles ) ||
!count( $cats ) ) {
632 $catFind = new CategoryFinder
;
633 $catFind->seed( $articles, $cats, $opts['categories_any'] ?
'OR' : 'AND' );
634 $match = $catFind->run();
638 foreach ( $match as $id ) {
639 foreach ( $a2r[$id] as $rev ) {
641 $newrows[$k] = $rowsarr[$k];
648 * Makes change an option link which carries all the other options
650 * @param string $title Title
651 * @param array $override Options to override
652 * @param array $options Current options
653 * @param bool $active Whether to show the link in bold
656 function makeOptionsLink( $title, $override, $options, $active = false ) {
657 $params = $override +
$options;
659 // Bug 36524: false values have be converted to "0" otherwise
660 // wfArrayToCgi() will omit it them.
661 foreach ( $params as &$value ) {
662 if ( $value === false ) {
668 $text = htmlspecialchars( $title );
670 $text = '<strong>' . $text . '</strong>';
673 return Linker
::linkKnown( $this->getPageTitle(), $text, [], $params );
677 * Creates the options panel.
679 * @param array $defaults
680 * @param array $nondefaults
681 * @param int $numRows Number of rows in the result to show after this header
684 function optionsPanel( $defaults, $nondefaults, $numRows ) {
685 $options = $nondefaults +
$defaults;
688 $msg = $this->msg( 'rclegend' );
689 if ( !$msg->isDisabled() ) {
690 $note .= '<div class="mw-rclegend">' . $msg->parse() . "</div>\n";
693 $lang = $this->getLanguage();
694 $user = $this->getUser();
695 $config = $this->getConfig();
696 if ( $options['from'] ) {
697 $note .= $this->msg( 'rcnotefrom' )
698 ->numParams( $options['limit'] )
700 $lang->userTimeAndDate( $options['from'], $user ),
701 $lang->userDate( $options['from'], $user ),
702 $lang->userTime( $options['from'], $user )
704 ->numParams( $numRows )
705 ->parse() . '<br />';
708 # Sort data for display and make sure it's unique after we've added user data.
709 $linkLimits = $config->get( 'RCLinkLimits' );
710 $linkLimits[] = $options['limit'];
712 $linkLimits = array_unique( $linkLimits );
714 $linkDays = $config->get( 'RCLinkDays' );
715 $linkDays[] = $options['days'];
717 $linkDays = array_unique( $linkDays );
721 foreach ( $linkLimits as $value ) {
722 $cl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
723 [ 'limit' => $value ], $nondefaults, $value == $options['limit'] );
725 $cl = $lang->pipeList( $cl );
727 // day links, reset 'from' to none
729 foreach ( $linkDays as $value ) {
730 $dl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
731 [ 'days' => $value, 'from' => '' ], $nondefaults, $value == $options['days'] );
733 $dl = $lang->pipeList( $dl );
737 'hideminor' => 'rcshowhideminor',
738 'hidebots' => 'rcshowhidebots',
739 'hideanons' => 'rcshowhideanons',
740 'hideliu' => 'rcshowhideliu',
741 'hidepatrolled' => 'rcshowhidepatr',
742 'hidemyself' => 'rcshowhidemine'
745 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
746 $filters['hidecategorization'] = 'rcshowhidecategorization';
749 $showhide = [ 'show', 'hide' ];
751 foreach ( $this->getCustomFilters() as $key => $params ) {
752 $filters[$key] = $params['msg'];
754 // Disable some if needed
755 if ( !$user->useRCPatrol() ) {
756 unset( $filters['hidepatrolled'] );
760 foreach ( $filters as $key => $msg ) {
761 // The following messages are used here:
762 // rcshowhideminor-show, rcshowhideminor-hide, rcshowhidebots-show, rcshowhidebots-hide,
763 // rcshowhideanons-show, rcshowhideanons-hide, rcshowhideliu-show, rcshowhideliu-hide,
764 // rcshowhidepatr-show, rcshowhidepatr-hide, rcshowhidemine-show, rcshowhidemine-hide,
765 // rcshowhidecategorization-show, rcshowhidecategorization-hide.
766 $linkMessage = $this->msg( $msg . '-' . $showhide[1 - $options[$key]] );
767 // Extensions can define additional filters, but don't need to define the corresponding
768 // messages. If they don't exist, just fall back to 'show' and 'hide'.
769 if ( !$linkMessage->exists() ) {
770 $linkMessage = $this->msg( $showhide[1 - $options[$key]] );
773 $link = $this->makeOptionsLink( $linkMessage->text(),
774 [ $key => 1 - $options[$key] ], $nondefaults );
775 $links[] = "<span class=\"$msg rcshowhideoption\">"
776 . $this->msg( $msg )->rawParams( $link )->escaped() . '</span>';
779 // show from this onward link
780 $timestamp = wfTimestampNow();
781 $now = $lang->userTimeAndDate( $timestamp, $user );
782 $timenow = $lang->userTime( $timestamp, $user );
783 $datenow = $lang->userDate( $timestamp, $user );
784 $pipedLinks = '<span class="rcshowhide">' . $lang->pipeList( $links ) . '</span>';
786 $rclinks = '<span class="rclinks">' . $this->msg( 'rclinks' )->rawParams( $cl, $dl, $pipedLinks )
787 ->parse() . '</span>';
789 $rclistfrom = '<span class="rclistfrom">' . $this->makeOptionsLink(
790 $this->msg( 'rclistfrom' )->rawParams( $now, $timenow, $datenow )->parse(),
791 [ 'from' => $timestamp ],
795 return "{$note}$rclinks<br />$rclistfrom";
798 public function isIncludable() {