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();
75 $config = $this->getConfig();
77 $opts->add( 'days', $user->getIntOption( 'rcdays' ) );
78 $opts->add( 'limit', $user->getIntOption( 'rclimit' ) );
79 $opts->add( 'from', '' );
81 $opts->add( 'hideminor', $user->getBoolOption( 'hideminor' ) );
82 $opts->add( 'hidebots', true );
83 $opts->add( 'hideanons', false );
84 $opts->add( 'hideliu', false );
85 $opts->add( 'hidepatrolled', $user->getBoolOption( 'hidepatrolled' ) );
86 $opts->add( 'hidemyself', false );
87 $opts->add( 'hidecategorization', $user->getBoolOption( 'hidecategorization' ) );
89 $opts->add( 'categories', '' );
90 $opts->add( 'categories_any', false );
91 $opts->add( 'tagfilter', '' );
97 * Get custom show/hide filters
99 * @return array Map of filter URL param names to properties (msg/default)
101 protected function getCustomFilters() {
102 if ( $this->customFilters
=== null ) {
103 $this->customFilters
= parent
::getCustomFilters();
104 Hooks
::run( 'SpecialRecentChangesFilters', [ $this, &$this->customFilters
], '1.23' );
107 return $this->customFilters
;
111 * Process $par and put options found in $opts. Used when including the page.
114 * @param FormOptions $opts
116 public function parseParameters( $par, FormOptions
$opts ) {
117 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
118 foreach ( $bits as $bit ) {
119 if ( 'hidebots' === $bit ) {
120 $opts['hidebots'] = true;
122 if ( 'bots' === $bit ) {
123 $opts['hidebots'] = false;
125 if ( 'hideminor' === $bit ) {
126 $opts['hideminor'] = true;
128 if ( 'minor' === $bit ) {
129 $opts['hideminor'] = false;
131 if ( 'hideliu' === $bit ) {
132 $opts['hideliu'] = true;
134 if ( 'hidepatrolled' === $bit ) {
135 $opts['hidepatrolled'] = true;
137 if ( 'hideanons' === $bit ) {
138 $opts['hideanons'] = true;
140 if ( 'hidemyself' === $bit ) {
141 $opts['hidemyself'] = true;
143 if ( 'hidecategorization' === $bit ) {
144 $opts['hidecategorization'] = true;
147 if ( is_numeric( $bit ) ) {
148 $opts['limit'] = $bit;
152 if ( preg_match( '/^limit=(\d+)$/', $bit, $m ) ) {
153 $opts['limit'] = $m[1];
155 if ( preg_match( '/^days=(\d+)$/', $bit, $m ) ) {
156 $opts['days'] = $m[1];
158 if ( preg_match( '/^namespace=(\d+)$/', $bit, $m ) ) {
159 $opts['namespace'] = $m[1];
164 public function validateOptions( FormOptions
$opts ) {
165 $opts->validateIntBounds( 'limit', 0, 5000 );
166 parent
::validateOptions( $opts );
170 * Return an array of conditions depending of options set in $opts
172 * @param FormOptions $opts
175 public function buildMainQueryConds( FormOptions
$opts ) {
176 $dbr = $this->getDB();
177 $conds = parent
::buildMainQueryConds( $opts );
180 $cutoff_unixtime = time() - ( $opts['days'] * 86400 );
181 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
182 $cutoff = $dbr->timestamp( $cutoff_unixtime );
184 $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
185 if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW
, $cutoff ) ) {
186 $cutoff = $dbr->timestamp( $opts['from'] );
188 $opts->reset( 'from' );
191 $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
199 * @param array $conds
200 * @param FormOptions $opts
201 * @return bool|ResultWrapper Result or false (for Recentchangeslinked only)
203 public function doMainQuery( $conds, $opts ) {
204 $dbr = $this->getDB();
205 $user = $this->getUser();
207 $tables = [ 'recentchanges' ];
208 $fields = RecentChange
::selectFields();
212 // JOIN on watchlist for users
213 if ( $user->getId() && $user->isAllowed( 'viewmywatchlist' ) ) {
214 $tables[] = 'watchlist';
215 $fields[] = 'wl_user';
216 $fields[] = 'wl_notificationtimestamp';
217 $join_conds['watchlist'] = [ 'LEFT JOIN', [
218 'wl_user' => $user->getId(),
220 'wl_namespace=rc_namespace'
224 if ( $user->isAllowed( 'rollback' ) ) {
226 $fields[] = 'page_latest';
227 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
230 ChangeTags
::modifyDisplayQuery(
239 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
245 // array_merge() is used intentionally here so that hooks can, should
246 // they so desire, override the ORDER BY / LIMIT condition(s); prior to
247 // MediaWiki 1.26 this used to use the plus operator instead, which meant
248 // that extensions weren't able to change these conditions
249 $query_options = array_merge( [
250 'ORDER BY' => 'rc_timestamp DESC',
251 'LIMIT' => $opts['limit'] ], $query_options );
252 $rows = $dbr->select(
255 // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
256 // knowledge to use an index merge if it wants (it may use some other index though).
257 $conds +
[ 'rc_new' => [ 0, 1 ] ],
263 // Build the final data
264 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
265 $this->filterByCategories( $rows, $opts );
271 protected function runMainQueryHook( &$tables, &$fields, &$conds,
272 &$query_options, &$join_conds, $opts
274 return parent
::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
276 'SpecialRecentChangesQuery',
277 [ &$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields ],
282 protected function getDB() {
283 return wfGetDB( DB_SLAVE
, 'recentchanges' );
286 public function outputFeedLinks() {
287 $this->addFeedLinks( $this->getFeedQuery() );
291 * Get URL query parameters for action=feedrecentchanges API feed of current recent changes view.
295 protected function getFeedQuery() {
296 $query = array_filter( $this->getOptions()->getAllValues(), function ( $value ) {
297 // API handles empty parameters in a different way
298 return $value !== '';
300 $query['action'] = 'feedrecentchanges';
301 $feedLimit = $this->getConfig()->get( 'FeedLimit' );
302 if ( $query['limit'] > $feedLimit ) {
303 $query['limit'] = $feedLimit;
310 * Build and output the actual changes list.
312 * @param array $rows Database rows
313 * @param FormOptions $opts
315 public function outputChangesList( $rows, $opts ) {
316 $limit = $opts['limit'];
318 $showWatcherCount = $this->getConfig()->get( 'RCShowWatchingUsers' )
319 && $this->getUser()->getOption( 'shownumberswatching' );
322 $dbr = $this->getDB();
325 $list = ChangesList
::newFromContext( $this->getContext() );
326 $list->initChangesListRows( $rows );
328 $rclistOutput = $list->beginRecentChangesList();
329 foreach ( $rows as $obj ) {
333 $rc = RecentChange
::newFromRow( $obj );
334 $rc->counter
= $counter++
;
335 # Check if the page has been updated since the last visit
336 if ( $this->getConfig()->get( 'ShowUpdatedMarker' )
337 && !empty( $obj->wl_notificationtimestamp
)
339 $rc->notificationtimestamp
= ( $obj->rc_timestamp
>= $obj->wl_notificationtimestamp
);
341 $rc->notificationtimestamp
= false; // Default
343 # Check the number of users watching the page
344 $rc->numberofWatchingusers
= 0; // Default
345 if ( $showWatcherCount && $obj->rc_namespace
>= 0 ) {
346 if ( !isset( $watcherCache[$obj->rc_namespace
][$obj->rc_title
] ) ) {
347 $watcherCache[$obj->rc_namespace
][$obj->rc_title
] =
352 'wl_namespace' => $obj->rc_namespace
,
353 'wl_title' => $obj->rc_title
,
355 __METHOD__
. '-watchers'
358 $rc->numberofWatchingusers
= $watcherCache[$obj->rc_namespace
][$obj->rc_title
];
361 $changeLine = $list->recentChangesLine( $rc, !empty( $obj->wl_user
), $counter );
362 if ( $changeLine !== false ) {
363 $rclistOutput .= $changeLine;
367 $rclistOutput .= $list->endRecentChangesList();
369 if ( $rows->numRows() === 0 ) {
370 $this->getOutput()->addHtml(
371 '<div class="mw-changeslist-empty">' .
372 $this->msg( 'recentchanges-noresult' )->parse() .
375 if ( !$this->including() ) {
376 $this->getOutput()->setStatusCode( 404 );
379 $this->getOutput()->addHTML( $rclistOutput );
384 * Set the text to be displayed above the changes
386 * @param FormOptions $opts
387 * @param int $numRows Number of rows in the result to show after this header
389 public function doHeader( $opts, $numRows ) {
390 $this->setTopText( $opts );
392 $defaults = $opts->getAllValues();
393 $nondefaults = $opts->getChangedValues();
396 $panel[] = $this->makeLegend();
397 $panel[] = $this->optionsPanel( $defaults, $nondefaults, $numRows );
400 $extraOpts = $this->getExtraOptions( $opts );
401 $extraOptsCount = count( $extraOpts );
403 $submit = ' ' . Xml
::submitbutton( $this->msg( 'recentchanges-submit' )->text() );
405 $out = Xml
::openElement( 'table', [ 'class' => 'mw-recentchanges-table' ] );
406 foreach ( $extraOpts as $name => $optionRow ) {
407 # Add submit button to the last row only
409 $addSubmit = ( $count === $extraOptsCount ) ?
$submit : '';
411 $out .= Xml
::openElement( 'tr' );
412 if ( is_array( $optionRow ) ) {
415 [ 'class' => 'mw-label mw-' . $name . '-label' ],
420 [ 'class' => 'mw-input' ],
421 $optionRow[1] . $addSubmit
426 [ 'class' => 'mw-input', 'colspan' => 2 ],
427 $optionRow . $addSubmit
430 $out .= Xml
::closeElement( 'tr' );
432 $out .= Xml
::closeElement( 'table' );
434 $unconsumed = $opts->getUnconsumedValues();
435 foreach ( $unconsumed as $key => $value ) {
436 $out .= Html
::hidden( $key, $value );
439 $t = $this->getPageTitle();
440 $out .= Html
::hidden( 'title', $t->getPrefixedText() );
441 $form = Xml
::tags( 'form', [ 'action' => wfScript() ], $out );
443 $panelString = implode( "\n", $panel );
445 $this->getOutput()->addHTML(
447 $this->msg( 'recentchanges-legend' )->text(),
449 [ 'class' => 'rcoptions' ]
453 $this->setBottomText( $opts );
457 * Send the text to be displayed above the options
459 * @param FormOptions $opts Unused
461 function setTopText( FormOptions
$opts ) {
464 $message = $this->msg( 'recentchangestext' )->inContentLanguage();
465 if ( !$message->isDisabled() ) {
466 $this->getOutput()->addWikiText(
467 Html
::rawElement( 'div',
468 [ 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ],
469 "\n" . $message->plain() . "\n"
471 /* $lineStart */ true,
472 /* $interface */ false
478 * Get options to be displayed in a form
480 * @param FormOptions $opts
483 function getExtraOptions( $opts ) {
484 $opts->consumeValues( [
485 'namespace', 'invert', 'associated', 'tagfilter', 'categories', 'categories_any'
489 $extraOpts['namespace'] = $this->namespaceFilterForm( $opts );
491 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
492 $extraOpts['category'] = $this->categoryFilterForm( $opts );
495 $tagFilter = ChangeTags
::buildTagFilterSelector( $opts['tagfilter'] );
496 if ( count( $tagFilter ) ) {
497 $extraOpts['tagfilter'] = $tagFilter;
500 // Don't fire the hook for subclasses. (Or should we?)
501 if ( $this->getName() === 'Recentchanges' ) {
502 Hooks
::run( 'SpecialRecentChangesPanel', [ &$extraOpts, $opts ] );
509 * Add page-specific modules.
511 protected function addModules() {
512 parent
::addModules();
513 $out = $this->getOutput();
514 $out->addModules( 'mediawiki.special.recentchanges' );
518 * Get last modified date, for client caching
519 * Don't use this if we are using the patrol feature, patrol changes don't
520 * update the timestamp
522 * @return string|bool
524 public function checkLastModified() {
525 $dbr = $this->getDB();
526 $lastmod = $dbr->selectField( 'recentchanges', 'MAX(rc_timestamp)', false, __METHOD__
);
532 * Creates the choose namespace selection
534 * @param FormOptions $opts
537 protected function namespaceFilterForm( FormOptions
$opts ) {
538 $nsSelect = Html
::namespaceSelector(
539 [ 'selected' => $opts['namespace'], 'all' => '' ],
540 [ 'name' => 'namespace', 'id' => 'namespace' ]
542 $nsLabel = Xml
::label( $this->msg( 'namespace' )->text(), 'namespace' );
543 $invert = Xml
::checkLabel(
544 $this->msg( 'invert' )->text(), 'invert', 'nsinvert',
546 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
548 $associated = Xml
::checkLabel(
549 $this->msg( 'namespace_association' )->text(), 'associated', 'nsassociated',
551 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
554 return [ $nsLabel, "$nsSelect $invert $associated" ];
558 * Create an input to filter changes by categories
560 * @param FormOptions $opts
563 protected function categoryFilterForm( FormOptions
$opts ) {
564 list( $label, $input ) = Xml
::inputLabelSep( $this->msg( 'rc_categories' )->text(),
565 'categories', 'mw-categories', false, $opts['categories'] );
567 $input .= ' ' . Xml
::checkLabel( $this->msg( 'rc_categories_any' )->text(),
568 'categories_any', 'mw-categories_any', $opts['categories_any'] );
570 return [ $label, $input ];
574 * Filter $rows by categories set in $opts
576 * @param ResultWrapper $rows Database rows
577 * @param FormOptions $opts
579 function filterByCategories( &$rows, FormOptions
$opts ) {
580 $categories = array_map( 'trim', explode( '|', $opts['categories'] ) );
582 if ( !count( $categories ) ) {
588 foreach ( $categories as $cat ) {
600 foreach ( $rows as $k => $r ) {
601 $nt = Title
::makeTitle( $r->rc_namespace
, $r->rc_title
);
602 $id = $nt->getArticleID();
604 continue; # Page might have been deleted...
606 if ( !in_array( $id, $articles ) ) {
609 if ( !isset( $a2r[$id] ) ) {
617 if ( !count( $articles ) ||
!count( $cats ) ) {
622 $catFind = new CategoryFinder
;
623 $catFind->seed( $articles, $cats, $opts['categories_any'] ?
'OR' : 'AND' );
624 $match = $catFind->run();
628 foreach ( $match as $id ) {
629 foreach ( $a2r[$id] as $rev ) {
631 $newrows[$k] = $rowsarr[$k];
638 * Makes change an option link which carries all the other options
640 * @param string $title Title
641 * @param array $override Options to override
642 * @param array $options Current options
643 * @param bool $active Whether to show the link in bold
646 function makeOptionsLink( $title, $override, $options, $active = false ) {
647 $params = $override +
$options;
649 // Bug 36524: false values have be converted to "0" otherwise
650 // wfArrayToCgi() will omit it them.
651 foreach ( $params as &$value ) {
652 if ( $value === false ) {
658 $text = htmlspecialchars( $title );
660 $text = '<strong>' . $text . '</strong>';
663 return Linker
::linkKnown( $this->getPageTitle(), $text, [], $params );
667 * Creates the options panel.
669 * @param array $defaults
670 * @param array $nondefaults
671 * @param int $numRows Number of rows in the result to show after this header
674 function optionsPanel( $defaults, $nondefaults, $numRows ) {
675 $options = $nondefaults +
$defaults;
678 $msg = $this->msg( 'rclegend' );
679 if ( !$msg->isDisabled() ) {
680 $note .= '<div class="mw-rclegend">' . $msg->parse() . "</div>\n";
683 $lang = $this->getLanguage();
684 $user = $this->getUser();
685 $config = $this->getConfig();
686 if ( $options['from'] ) {
687 $note .= $this->msg( 'rcnotefrom' )
688 ->numParams( $options['limit'] )
690 $lang->userTimeAndDate( $options['from'], $user ),
691 $lang->userDate( $options['from'], $user ),
692 $lang->userTime( $options['from'], $user )
694 ->numParams( $numRows )
695 ->parse() . '<br />';
698 # Sort data for display and make sure it's unique after we've added user data.
699 $linkLimits = $config->get( 'RCLinkLimits' );
700 $linkLimits[] = $options['limit'];
702 $linkLimits = array_unique( $linkLimits );
704 $linkDays = $config->get( 'RCLinkDays' );
705 $linkDays[] = $options['days'];
707 $linkDays = array_unique( $linkDays );
711 foreach ( $linkLimits as $value ) {
712 $cl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
713 [ 'limit' => $value ], $nondefaults, $value == $options['limit'] );
715 $cl = $lang->pipeList( $cl );
717 // day links, reset 'from' to none
719 foreach ( $linkDays as $value ) {
720 $dl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
721 [ 'days' => $value, 'from' => '' ], $nondefaults, $value == $options['days'] );
723 $dl = $lang->pipeList( $dl );
727 'hideminor' => 'rcshowhideminor',
728 'hidebots' => 'rcshowhidebots',
729 'hideanons' => 'rcshowhideanons',
730 'hideliu' => 'rcshowhideliu',
731 'hidepatrolled' => 'rcshowhidepatr',
732 'hidemyself' => 'rcshowhidemine'
735 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
736 $filters['hidecategorization'] = 'rcshowhidecategorization';
739 $showhide = [ 'show', 'hide' ];
741 foreach ( $this->getCustomFilters() as $key => $params ) {
742 $filters[$key] = $params['msg'];
744 // Disable some if needed
745 if ( !$user->useRCPatrol() ) {
746 unset( $filters['hidepatrolled'] );
750 foreach ( $filters as $key => $msg ) {
751 // The following messages are used here:
752 // rcshowhideminor-show, rcshowhideminor-hide, rcshowhidebots-show, rcshowhidebots-hide,
753 // rcshowhideanons-show, rcshowhideanons-hide, rcshowhideliu-show, rcshowhideliu-hide,
754 // rcshowhidepatr-show, rcshowhidepatr-hide, rcshowhidemine-show, rcshowhidemine-hide,
755 // rcshowhidecategorization-show, rcshowhidecategorization-hide.
756 $linkMessage = $this->msg( $msg . '-' . $showhide[1 - $options[$key]] );
757 // Extensions can define additional filters, but don't need to define the corresponding
758 // messages. If they don't exist, just fall back to 'show' and 'hide'.
759 if ( !$linkMessage->exists() ) {
760 $linkMessage = $this->msg( $showhide[1 - $options[$key]] );
763 $link = $this->makeOptionsLink( $linkMessage->text(),
764 [ $key => 1 - $options[$key] ], $nondefaults );
765 $links[] = "<span class=\"$msg rcshowhideoption\">"
766 . $this->msg( $msg )->rawParams( $link )->escaped() . '</span>';
769 // show from this onward link
770 $timestamp = wfTimestampNow();
771 $now = $lang->userTimeAndDate( $timestamp, $user );
772 $timenow = $lang->userTime( $timestamp, $user );
773 $datenow = $lang->userDate( $timestamp, $user );
774 $pipedLinks = '<span class="rcshowhide">' . $lang->pipeList( $links ) . '</span>';
776 $rclinks = '<span class="rclinks">' . $this->msg( 'rclinks' )->rawParams( $cl, $dl, $pipedLinks )
777 ->parse() . '</span>';
779 $rclistfrom = '<span class="rclistfrom">' . $this->makeOptionsLink(
780 $this->msg( 'rclistfrom' )->rawParams( $now, $timenow, $datenow )->parse(),
781 [ 'from' => $timestamp ],
785 return "{$note}$rclinks<br />$rclistfrom";
788 public function isIncludable() {