0bfe1855df0f4fff612b02daa290d3c922b480af
[lhc/web/wiklou.git] / includes / specials / SpecialRecentChanges.php
1 <?php
2 /**
3 * Implements Special:Recentchanges
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\Rdbms\IResultWrapper;
26 use Wikimedia\Rdbms\FakeResultWrapper;
27
28 /**
29 * A special page that lists last changes made to the wiki
30 *
31 * @ingroup SpecialPage
32 */
33 class SpecialRecentChanges extends ChangesListSpecialPage {
34
35 protected static $savedQueriesPreferenceName = 'rcfilters-saved-queries';
36 protected static $daysPreferenceName = 'rcdays'; // Use general RecentChanges preference
37 protected static $limitPreferenceName = 'rcfilters-limit'; // Use RCFilters-specific preference
38 protected static $collapsedPreferenceName = 'rcfilters-rc-collapsed';
39
40 private $watchlistFilterGroupDefinition;
41
42 public function __construct( $name = 'Recentchanges', $restriction = '' ) {
43 parent::__construct( $name, $restriction );
44
45 $this->watchlistFilterGroupDefinition = [
46 'name' => 'watchlist',
47 'title' => 'rcfilters-filtergroup-watchlist',
48 'class' => ChangesListStringOptionsFilterGroup::class,
49 'priority' => -9,
50 'isFullCoverage' => true,
51 'filters' => [
52 [
53 'name' => 'watched',
54 'label' => 'rcfilters-filter-watchlist-watched-label',
55 'description' => 'rcfilters-filter-watchlist-watched-description',
56 'cssClassSuffix' => 'watched',
57 'isRowApplicableCallable' => function ( $ctx, $rc ) {
58 return $rc->getAttribute( 'wl_user' );
59 }
60 ],
61 [
62 'name' => 'watchednew',
63 'label' => 'rcfilters-filter-watchlist-watchednew-label',
64 'description' => 'rcfilters-filter-watchlist-watchednew-description',
65 'cssClassSuffix' => 'watchednew',
66 'isRowApplicableCallable' => function ( $ctx, $rc ) {
67 return $rc->getAttribute( 'wl_user' ) &&
68 $rc->getAttribute( 'rc_timestamp' ) &&
69 $rc->getAttribute( 'wl_notificationtimestamp' ) &&
70 $rc->getAttribute( 'rc_timestamp' ) >= $rc->getAttribute( 'wl_notificationtimestamp' );
71 },
72 ],
73 [
74 'name' => 'notwatched',
75 'label' => 'rcfilters-filter-watchlist-notwatched-label',
76 'description' => 'rcfilters-filter-watchlist-notwatched-description',
77 'cssClassSuffix' => 'notwatched',
78 'isRowApplicableCallable' => function ( $ctx, $rc ) {
79 return $rc->getAttribute( 'wl_user' ) === null;
80 },
81 ]
82 ],
83 'default' => ChangesListStringOptionsFilterGroup::NONE,
84 'queryCallable' => function ( $specialPageClassName, $context, $dbr,
85 &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selectedValues ) {
86 sort( $selectedValues );
87 $notwatchedCond = 'wl_user IS NULL';
88 $watchedCond = 'wl_user IS NOT NULL';
89 $newCond = 'rc_timestamp >= wl_notificationtimestamp';
90
91 if ( $selectedValues === [ 'notwatched' ] ) {
92 $conds[] = $notwatchedCond;
93 return;
94 }
95
96 if ( $selectedValues === [ 'watched' ] ) {
97 $conds[] = $watchedCond;
98 return;
99 }
100
101 if ( $selectedValues === [ 'watchednew' ] ) {
102 $conds[] = $dbr->makeList( [
103 $watchedCond,
104 $newCond
105 ], LIST_AND );
106 return;
107 }
108
109 if ( $selectedValues === [ 'notwatched', 'watched' ] ) {
110 // no filters
111 return;
112 }
113
114 if ( $selectedValues === [ 'notwatched', 'watchednew' ] ) {
115 $conds[] = $dbr->makeList( [
116 $notwatchedCond,
117 $dbr->makeList( [
118 $watchedCond,
119 $newCond
120 ], LIST_AND )
121 ], LIST_OR );
122 return;
123 }
124
125 if ( $selectedValues === [ 'watched', 'watchednew' ] ) {
126 $conds[] = $watchedCond;
127 return;
128 }
129
130 if ( $selectedValues === [ 'notwatched', 'watched', 'watchednew' ] ) {
131 // no filters
132 return;
133 }
134 }
135 ];
136 }
137
138 /**
139 * @param string|null $subpage
140 */
141 public function execute( $subpage ) {
142 // Backwards-compatibility: redirect to new feed URLs
143 $feedFormat = $this->getRequest()->getVal( 'feed' );
144 if ( !$this->including() && $feedFormat ) {
145 $query = $this->getFeedQuery();
146 $query['feedformat'] = $feedFormat === 'atom' ? 'atom' : 'rss';
147 $this->getOutput()->redirect( wfAppendQuery( wfScript( 'api' ), $query ) );
148
149 return;
150 }
151
152 // 10 seconds server-side caching max
153 $out = $this->getOutput();
154 $out->setCdnMaxage( 10 );
155 // Check if the client has a cached version
156 $lastmod = $this->checkLastModified();
157 if ( $lastmod === false ) {
158 return;
159 }
160
161 $this->addHelpLink(
162 'https://meta.wikimedia.org/wiki/Special:MyLanguage/Help:Recent_changes',
163 true
164 );
165 parent::execute( $subpage );
166 }
167
168 /**
169 * @inheritDoc
170 */
171 protected function transformFilterDefinition( array $filterDefinition ) {
172 if ( isset( $filterDefinition['showHideSuffix'] ) ) {
173 $filterDefinition['showHide'] = 'rc' . $filterDefinition['showHideSuffix'];
174 }
175
176 return $filterDefinition;
177 }
178
179 /**
180 * @inheritDoc
181 */
182 protected function registerFilters() {
183 parent::registerFilters();
184
185 if (
186 !$this->including() &&
187 $this->getUser()->isLoggedIn() &&
188 $this->getUser()->isAllowed( 'viewmywatchlist' )
189 ) {
190 $this->registerFiltersFromDefinitions( [ $this->watchlistFilterGroupDefinition ] );
191 $watchlistGroup = $this->getFilterGroup( 'watchlist' );
192 $watchlistGroup->getFilter( 'watched' )->setAsSupersetOf(
193 $watchlistGroup->getFilter( 'watchednew' )
194 );
195 }
196
197 $user = $this->getUser();
198
199 $significance = $this->getFilterGroup( 'significance' );
200 /** @var ChangesListBooleanFilter $hideMinor */
201 $hideMinor = $significance->getFilter( 'hideminor' );
202 '@phan-var ChangesListBooleanFilter $hideMinor';
203 $hideMinor->setDefault( $user->getBoolOption( 'hideminor' ) );
204
205 $automated = $this->getFilterGroup( 'automated' );
206 /** @var ChangesListBooleanFilter $hideBots */
207 $hideBots = $automated->getFilter( 'hidebots' );
208 '@phan-var ChangesListBooleanFilter $hideBots';
209 $hideBots->setDefault( true );
210
211 /** @var ChangesListStringOptionsFilterGroup|null $reviewStatus */
212 $reviewStatus = $this->getFilterGroup( 'reviewStatus' );
213 '@phan-var ChangesListStringOptionsFilterGroup|null $reviewStatus';
214 if ( $reviewStatus !== null ) {
215 // Conditional on feature being available and rights
216 if ( $user->getBoolOption( 'hidepatrolled' ) ) {
217 $reviewStatus->setDefault( 'unpatrolled' );
218 $legacyReviewStatus = $this->getFilterGroup( 'legacyReviewStatus' );
219 /** @var ChangesListBooleanFilter $legacyHidePatrolled */
220 $legacyHidePatrolled = $legacyReviewStatus->getFilter( 'hidepatrolled' );
221 '@phan-var ChangesListBooleanFilter $legacyHidePatrolled';
222 $legacyHidePatrolled->setDefault( true );
223 }
224 }
225
226 $changeType = $this->getFilterGroup( 'changeType' );
227 /** @var ChangesListBooleanFilter $hideCategorization */
228 $hideCategorization = $changeType->getFilter( 'hidecategorization' );
229 '@phan-var ChangesListBooleanFilter $hideCategorization';
230 if ( $hideCategorization !== null ) {
231 // Conditional on feature being available
232 $hideCategorization->setDefault( $user->getBoolOption( 'hidecategorization' ) );
233 }
234 }
235
236 /**
237 * Process $par and put options found in $opts. Used when including the page.
238 *
239 * @param string $par
240 * @param FormOptions $opts
241 */
242 public function parseParameters( $par, FormOptions $opts ) {
243 parent::parseParameters( $par, $opts );
244
245 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
246 foreach ( $bits as $bit ) {
247 if ( is_numeric( $bit ) ) {
248 $opts['limit'] = $bit;
249 }
250
251 $m = [];
252 if ( preg_match( '/^limit=(\d+)$/', $bit, $m ) ) {
253 $opts['limit'] = $m[1];
254 }
255 if ( preg_match( '/^days=(\d+(?:\.\d+)?)$/', $bit, $m ) ) {
256 $opts['days'] = $m[1];
257 }
258 if ( preg_match( '/^namespace=(.*)$/', $bit, $m ) ) {
259 $opts['namespace'] = $m[1];
260 }
261 if ( preg_match( '/^tagfilter=(.*)$/', $bit, $m ) ) {
262 $opts['tagfilter'] = $m[1];
263 }
264 }
265 }
266
267 /**
268 * @inheritDoc
269 */
270 protected function doMainQuery( $tables, $fields, $conds, $query_options,
271 $join_conds, FormOptions $opts
272 ) {
273 $dbr = $this->getDB();
274 $user = $this->getUser();
275
276 $rcQuery = RecentChange::getQueryInfo();
277 $tables = array_merge( $tables, $rcQuery['tables'] );
278 $fields = array_merge( $rcQuery['fields'], $fields );
279 $join_conds = array_merge( $join_conds, $rcQuery['joins'] );
280
281 // JOIN on watchlist for users
282 if ( $user->isLoggedIn() && $user->isAllowed( 'viewmywatchlist' ) ) {
283 $tables[] = 'watchlist';
284 $fields[] = 'wl_user';
285 $fields[] = 'wl_notificationtimestamp';
286 $join_conds['watchlist'] = [ 'LEFT JOIN', [
287 'wl_user' => $user->getId(),
288 'wl_title=rc_title',
289 'wl_namespace=rc_namespace'
290 ] ];
291 }
292
293 // JOIN on page, used for 'last revision' filter highlight
294 $tables[] = 'page';
295 $fields[] = 'page_latest';
296 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
297
298 $tagFilter = $opts['tagfilter'] ? explode( '|', $opts['tagfilter'] ) : [];
299 ChangeTags::modifyDisplayQuery(
300 $tables,
301 $fields,
302 $conds,
303 $join_conds,
304 $query_options,
305 $tagFilter
306 );
307
308 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
309 $opts )
310 ) {
311 return false;
312 }
313
314 if ( $this->areFiltersInConflict() ) {
315 return false;
316 }
317
318 $orderByAndLimit = [
319 'ORDER BY' => 'rc_timestamp DESC',
320 'LIMIT' => $opts['limit']
321 ];
322 if ( in_array( 'DISTINCT', $query_options ) ) {
323 // ChangeTags::modifyDisplayQuery() adds DISTINCT when filtering on multiple tags.
324 // In order to prevent DISTINCT from causing query performance problems,
325 // we have to GROUP BY the primary key. This in turn requires us to add
326 // the primary key to the end of the ORDER BY, and the old ORDER BY to the
327 // start of the GROUP BY
328 $orderByAndLimit['ORDER BY'] = 'rc_timestamp DESC, rc_id DESC';
329 $orderByAndLimit['GROUP BY'] = 'rc_timestamp, rc_id';
330 }
331 // array_merge() is used intentionally here so that hooks can, should
332 // they so desire, override the ORDER BY / LIMIT condition(s); prior to
333 // MediaWiki 1.26 this used to use the plus operator instead, which meant
334 // that extensions weren't able to change these conditions
335 $query_options = array_merge( $orderByAndLimit, $query_options );
336 $rows = $dbr->select(
337 $tables,
338 $fields,
339 // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
340 // knowledge to use an index merge if it wants (it may use some other index though).
341 $conds + [ 'rc_new' => [ 0, 1 ] ],
342 __METHOD__,
343 $query_options,
344 $join_conds
345 );
346
347 return $rows;
348 }
349
350 protected function getDB() {
351 return wfGetDB( DB_REPLICA, 'recentchanges' );
352 }
353
354 public function outputFeedLinks() {
355 $this->addFeedLinks( $this->getFeedQuery() );
356 }
357
358 /**
359 * Get URL query parameters for action=feedrecentchanges API feed of current recent changes view.
360 *
361 * @return array
362 */
363 protected function getFeedQuery() {
364 $query = array_filter( $this->getOptions()->getAllValues(), function ( $value ) {
365 // API handles empty parameters in a different way
366 return $value !== '';
367 } );
368 $query['action'] = 'feedrecentchanges';
369 $feedLimit = $this->getConfig()->get( 'FeedLimit' );
370 if ( $query['limit'] > $feedLimit ) {
371 $query['limit'] = $feedLimit;
372 }
373
374 return $query;
375 }
376
377 /**
378 * Build and output the actual changes list.
379 *
380 * @param IResultWrapper $rows Database rows
381 * @param FormOptions $opts
382 */
383 public function outputChangesList( $rows, $opts ) {
384 $limit = $opts['limit'];
385
386 $showWatcherCount = $this->getConfig()->get( 'RCShowWatchingUsers' )
387 && $this->getUser()->getOption( 'shownumberswatching' );
388 $watcherCache = [];
389
390 $counter = 1;
391 $list = ChangesList::newFromContext( $this->getContext(), $this->filterGroups );
392 $list->initChangesListRows( $rows );
393
394 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
395 $rclistOutput = $list->beginRecentChangesList();
396 if ( $this->isStructuredFilterUiEnabled() ) {
397 $rclistOutput .= $this->makeLegend();
398 }
399
400 foreach ( $rows as $obj ) {
401 if ( $limit == 0 ) {
402 break;
403 }
404 $rc = RecentChange::newFromRow( $obj );
405
406 # Skip CatWatch entries for hidden cats based on user preference
407 if (
408 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE &&
409 !$userShowHiddenCats &&
410 $rc->getParam( 'hidden-cat' )
411 ) {
412 continue;
413 }
414
415 $rc->counter = $counter++;
416 # Check if the page has been updated since the last visit
417 if ( $this->getConfig()->get( 'ShowUpdatedMarker' )
418 && !empty( $obj->wl_notificationtimestamp )
419 ) {
420 $rc->notificationtimestamp = ( $obj->rc_timestamp >= $obj->wl_notificationtimestamp );
421 } else {
422 $rc->notificationtimestamp = false; // Default
423 }
424 # Check the number of users watching the page
425 $rc->numberofWatchingusers = 0; // Default
426 if ( $showWatcherCount && $obj->rc_namespace >= 0 ) {
427 if ( !isset( $watcherCache[$obj->rc_namespace][$obj->rc_title] ) ) {
428 $watcherCache[$obj->rc_namespace][$obj->rc_title] =
429 MediaWikiServices::getInstance()->getWatchedItemStore()->countWatchers(
430 new TitleValue( (int)$obj->rc_namespace, $obj->rc_title )
431 );
432 }
433 $rc->numberofWatchingusers = $watcherCache[$obj->rc_namespace][$obj->rc_title];
434 }
435
436 $changeLine = $list->recentChangesLine( $rc, !empty( $obj->wl_user ), $counter );
437 if ( $changeLine !== false ) {
438 $rclistOutput .= $changeLine;
439 --$limit;
440 }
441 }
442 $rclistOutput .= $list->endRecentChangesList();
443
444 if ( $rows->numRows() === 0 ) {
445 $this->outputNoResults();
446 if ( !$this->including() ) {
447 $this->getOutput()->setStatusCode( 404 );
448 }
449 } else {
450 $this->getOutput()->addHTML( $rclistOutput );
451 }
452 }
453
454 /**
455 * Set the text to be displayed above the changes
456 *
457 * @param FormOptions $opts
458 * @param int $numRows Number of rows in the result to show after this header
459 */
460 public function doHeader( $opts, $numRows ) {
461 $this->setTopText( $opts );
462
463 $defaults = $opts->getAllValues();
464 $nondefaults = $opts->getChangedValues();
465
466 $panel = [];
467 if ( !$this->isStructuredFilterUiEnabled() ) {
468 $panel[] = $this->makeLegend();
469 }
470 $panel[] = $this->optionsPanel( $defaults, $nondefaults, $numRows );
471 $panel[] = '<hr />';
472
473 $extraOpts = $this->getExtraOptions( $opts );
474 $extraOptsCount = count( $extraOpts );
475 $count = 0;
476 $submit = ' ' . Xml::submitButton( $this->msg( 'recentchanges-submit' )->text() );
477
478 $out = Xml::openElement( 'table', [ 'class' => 'mw-recentchanges-table' ] );
479 foreach ( $extraOpts as $name => $optionRow ) {
480 # Add submit button to the last row only
481 ++$count;
482 $addSubmit = ( $count === $extraOptsCount ) ? $submit : '';
483
484 $out .= Xml::openElement( 'tr', [ 'class' => $name . 'Form' ] );
485 if ( is_array( $optionRow ) ) {
486 $out .= Xml::tags(
487 'td',
488 [ 'class' => 'mw-label mw-' . $name . '-label' ],
489 $optionRow[0]
490 );
491 $out .= Xml::tags(
492 'td',
493 [ 'class' => 'mw-input' ],
494 $optionRow[1] . $addSubmit
495 );
496 } else {
497 $out .= Xml::tags(
498 'td',
499 [ 'class' => 'mw-input', 'colspan' => 2 ],
500 $optionRow . $addSubmit
501 );
502 }
503 $out .= Xml::closeElement( 'tr' );
504 }
505 $out .= Xml::closeElement( 'table' );
506
507 $unconsumed = $opts->getUnconsumedValues();
508 foreach ( $unconsumed as $key => $value ) {
509 $out .= Html::hidden( $key, $value );
510 }
511
512 $t = $this->getPageTitle();
513 $out .= Html::hidden( 'title', $t->getPrefixedText() );
514 $form = Xml::tags( 'form', [ 'action' => wfScript() ], $out );
515 $panel[] = $form;
516 $panelString = implode( "\n", $panel );
517
518 $rcoptions = Xml::fieldset(
519 $this->msg( 'recentchanges-legend' )->text(),
520 $panelString,
521 [ 'class' => 'rcoptions cloptions' ]
522 );
523
524 // Insert a placeholder for RCFilters
525 if ( $this->isStructuredFilterUiEnabled() ) {
526 $rcfilterContainer = Html::element(
527 'div',
528 // TODO: Remove deprecated rcfilters-container class
529 [ 'class' => 'rcfilters-container mw-rcfilters-container' ]
530 );
531
532 $loadingContainer = Html::rawElement(
533 'div',
534 [ 'class' => 'mw-rcfilters-spinner' ],
535 Html::element(
536 'div',
537 [ 'class' => 'mw-rcfilters-spinner-bounce' ]
538 )
539 );
540
541 // Wrap both with rcfilters-head
542 $this->getOutput()->addHTML(
543 Html::rawElement(
544 'div',
545 // TODO: Remove deprecated rcfilters-head class
546 [ 'class' => 'rcfilters-head mw-rcfilters-head' ],
547 $rcfilterContainer . $rcoptions
548 )
549 );
550
551 // Add spinner
552 $this->getOutput()->addHTML( $loadingContainer );
553 } else {
554 $this->getOutput()->addHTML( $rcoptions );
555 }
556
557 $this->setBottomText( $opts );
558 }
559
560 /**
561 * Send the text to be displayed above the options
562 *
563 * @param FormOptions $opts Unused
564 */
565 function setTopText( FormOptions $opts ) {
566 $message = $this->msg( 'recentchangestext' )->inContentLanguage();
567 if ( !$message->isDisabled() ) {
568 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
569 // Parse the message in this weird ugly way to preserve the ability to include interlanguage
570 // links in it (T172461). In the future when T66969 is resolved, perhaps we can just use
571 // $message->parse() instead. This code is copied from Message::parseText().
572 $parserOutput = MessageCache::singleton()->parse(
573 $message->plain(),
574 $this->getPageTitle(),
575 /*linestart*/true,
576 // Message class sets the interface flag to false when parsing in a language different than
577 // user language, and this is wiki content language
578 /*interface*/false,
579 $contLang
580 );
581 $content = $parserOutput->getText( [
582 'enableSectionEditLinks' => false,
583 ] );
584 // Add only metadata here (including the language links), text is added below
585 $this->getOutput()->addParserOutputMetadata( $parserOutput );
586
587 $langAttributes = [
588 'lang' => $contLang->getHtmlCode(),
589 'dir' => $contLang->getDir(),
590 ];
591
592 $topLinksAttributes = [ 'class' => 'mw-recentchanges-toplinks' ];
593
594 if ( $this->isStructuredFilterUiEnabled() ) {
595 // Check whether the widget is already collapsed or expanded
596 $collapsedState = $this->getRequest()->getCookie( 'rcfilters-toplinks-collapsed-state' );
597 // Note that an empty/unset cookie means collapsed, so check for !== 'expanded'
598 $topLinksAttributes[ 'class' ] .= $collapsedState !== 'expanded' ?
599 ' mw-recentchanges-toplinks-collapsed' : '';
600
601 $this->getOutput()->enableOOUI();
602 $contentTitle = new OOUI\ButtonWidget( [
603 'classes' => [ 'mw-recentchanges-toplinks-title' ],
604 'label' => new OOUI\HtmlSnippet( $this->msg( 'rcfilters-other-review-tools' )->parse() ),
605 'framed' => false,
606 'indicator' => $collapsedState !== 'expanded' ? 'down' : 'up',
607 'flags' => [ 'progressive' ],
608 ] );
609
610 $contentWrapper = Html::rawElement( 'div',
611 array_merge(
612 [ 'class' => 'mw-recentchanges-toplinks-content mw-collapsible-content' ],
613 $langAttributes
614 ),
615 $content
616 );
617 $content = $contentTitle . $contentWrapper;
618 } else {
619 // Language direction should be on the top div only
620 // if the title is not there. If it is there, it's
621 // interface direction, and the language/dir attributes
622 // should be on the content itself
623 $topLinksAttributes = array_merge( $topLinksAttributes, $langAttributes );
624 }
625
626 $this->getOutput()->addHTML(
627 Html::rawElement( 'div', $topLinksAttributes, $content )
628 );
629 }
630 }
631
632 /**
633 * Get options to be displayed in a form
634 *
635 * @param FormOptions $opts
636 * @return array
637 */
638 function getExtraOptions( $opts ) {
639 $opts->consumeValues( [
640 'namespace', 'invert', 'associated', 'tagfilter'
641 ] );
642
643 $extraOpts = [];
644 $extraOpts['namespace'] = $this->namespaceFilterForm( $opts );
645
646 $tagFilter = ChangeTags::buildTagFilterSelector(
647 $opts['tagfilter'], false, $this->getContext() );
648 if ( count( $tagFilter ) ) {
649 $extraOpts['tagfilter'] = $tagFilter;
650 }
651
652 // Don't fire the hook for subclasses. (Or should we?)
653 if ( $this->getName() === 'Recentchanges' ) {
654 Hooks::run( 'SpecialRecentChangesPanel', [ &$extraOpts, $opts ] );
655 }
656
657 return $extraOpts;
658 }
659
660 /**
661 * Add page-specific modules.
662 */
663 protected function addModules() {
664 parent::addModules();
665 $out = $this->getOutput();
666 $out->addModules( 'mediawiki.special.recentchanges' );
667 }
668
669 /**
670 * Get last modified date, for client caching
671 * Don't use this if we are using the patrol feature, patrol changes don't
672 * update the timestamp
673 *
674 * @return string|bool
675 */
676 public function checkLastModified() {
677 $dbr = $this->getDB();
678 $lastmod = $dbr->selectField( 'recentchanges', 'MAX(rc_timestamp)', '', __METHOD__ );
679
680 return $lastmod;
681 }
682
683 /**
684 * Creates the choose namespace selection
685 *
686 * @param FormOptions $opts
687 * @return string[]
688 */
689 protected function namespaceFilterForm( FormOptions $opts ) {
690 $nsSelect = Html::namespaceSelector(
691 [ 'selected' => $opts['namespace'], 'all' => '', 'in-user-lang' => true ],
692 [ 'name' => 'namespace', 'id' => 'namespace' ]
693 );
694 $nsLabel = Xml::label( $this->msg( 'namespace' )->text(), 'namespace' );
695 $attribs = [ 'class' => [ 'mw-input-with-label' ] ];
696 // Hide the checkboxes when the namespace filter is set to 'all'.
697 if ( $opts['namespace'] === '' ) {
698 $attribs['class'][] = 'mw-input-hidden';
699 }
700 $invert = Html::rawElement( 'span', $attribs, Xml::checkLabel(
701 $this->msg( 'invert' )->text(), 'invert', 'nsinvert',
702 $opts['invert'],
703 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
704 ) );
705 $associated = Html::rawElement( 'span', $attribs, Xml::checkLabel(
706 $this->msg( 'namespace_association' )->text(), 'associated', 'nsassociated',
707 $opts['associated'],
708 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
709 ) );
710
711 return [ $nsLabel, "$nsSelect $invert $associated" ];
712 }
713
714 /**
715 * Filter $rows by categories set in $opts
716 *
717 * @deprecated since 1.31
718 *
719 * @param IResultWrapper &$rows Database rows
720 * @param FormOptions $opts
721 */
722 function filterByCategories( &$rows, FormOptions $opts ) {
723 wfDeprecated( __METHOD__, '1.31' );
724
725 $categories = array_map( 'trim', explode( '|', $opts['categories'] ) );
726
727 if ( $categories === [] ) {
728 return;
729 }
730
731 # Filter categories
732 $cats = [];
733 foreach ( $categories as $cat ) {
734 $cat = trim( $cat );
735 if ( $cat == '' ) {
736 continue;
737 }
738 $cats[] = $cat;
739 }
740
741 # Filter articles
742 $articles = [];
743 $a2r = [];
744 $rowsarr = [];
745 foreach ( $rows as $k => $r ) {
746 $nt = Title::makeTitle( $r->rc_namespace, $r->rc_title );
747 $id = $nt->getArticleID();
748 if ( $id == 0 ) {
749 continue; # Page might have been deleted...
750 }
751 if ( !in_array( $id, $articles ) ) {
752 $articles[] = $id;
753 }
754 if ( !isset( $a2r[$id] ) ) {
755 $a2r[$id] = [];
756 }
757 $a2r[$id][] = $k;
758 $rowsarr[$k] = $r;
759 }
760
761 # Shortcut?
762 if ( $articles === [] || $cats === [] ) {
763 return;
764 }
765
766 # Look up
767 $catFind = new CategoryFinder;
768 $catFind->seed( $articles, $cats, $opts['categories_any'] ? 'OR' : 'AND' );
769 $match = $catFind->run();
770
771 # Filter
772 $newrows = [];
773 foreach ( $match as $id ) {
774 foreach ( $a2r[$id] as $rev ) {
775 $k = $rev;
776 $newrows[$k] = $rowsarr[$k];
777 }
778 }
779 $rows = new FakeResultWrapper( array_values( $newrows ) );
780 }
781
782 /**
783 * Makes change an option link which carries all the other options
784 *
785 * @param string $title
786 * @param array $override Options to override
787 * @param array $options Current options
788 * @param bool $active Whether to show the link in bold
789 * @return string
790 */
791 function makeOptionsLink( $title, $override, $options, $active = false ) {
792 $params = $this->convertParamsForLink( $override + $options );
793
794 if ( $active ) {
795 $title = new HtmlArmor( '<strong>' . htmlspecialchars( $title ) . '</strong>' );
796 }
797
798 return $this->getLinkRenderer()->makeKnownLink( $this->getPageTitle(), $title, [
799 'data-params' => json_encode( $override ),
800 'data-keys' => implode( ',', array_keys( $override ) ),
801 ], $params );
802 }
803
804 /**
805 * Creates the options panel.
806 *
807 * @param array $defaults
808 * @param array $nondefaults
809 * @param int $numRows Number of rows in the result to show after this header
810 * @return string
811 */
812 function optionsPanel( $defaults, $nondefaults, $numRows ) {
813 $options = $nondefaults + $defaults;
814
815 $note = '';
816 $msg = $this->msg( 'rclegend' );
817 if ( !$msg->isDisabled() ) {
818 $note .= Html::rawElement(
819 'div',
820 [ 'class' => 'mw-rclegend' ],
821 $msg->parse()
822 );
823 }
824
825 $lang = $this->getLanguage();
826 $user = $this->getUser();
827 $config = $this->getConfig();
828 if ( $options['from'] ) {
829 $resetLink = $this->makeOptionsLink( $this->msg( 'rclistfromreset' ),
830 [ 'from' => '' ], $nondefaults );
831
832 $noteFromMsg = $this->msg( 'rcnotefrom' )
833 ->numParams( $options['limit'] )
834 ->params(
835 $lang->userTimeAndDate( $options['from'], $user ),
836 $lang->userDate( $options['from'], $user ),
837 $lang->userTime( $options['from'], $user )
838 )
839 ->numParams( $numRows );
840 $note .= Html::rawElement(
841 'span',
842 [ 'class' => 'rcnotefrom' ],
843 $noteFromMsg->parse()
844 ) .
845 ' ' .
846 Html::rawElement(
847 'span',
848 [ 'class' => 'rcoptions-listfromreset' ],
849 $this->msg( 'parentheses' )->rawParams( $resetLink )->parse()
850 ) .
851 '<br />';
852 }
853
854 # Sort data for display and make sure it's unique after we've added user data.
855 $linkLimits = $config->get( 'RCLinkLimits' );
856 $linkLimits[] = $options['limit'];
857 sort( $linkLimits );
858 $linkLimits = array_unique( $linkLimits );
859
860 $linkDays = $this->getLinkDays();
861 $linkDays[] = $options['days'];
862 sort( $linkDays );
863 $linkDays = array_unique( $linkDays );
864
865 // limit links
866 $cl = [];
867 foreach ( $linkLimits as $value ) {
868 $cl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
869 [ 'limit' => $value ], $nondefaults, $value == $options['limit'] );
870 }
871 $cl = $lang->pipeList( $cl );
872
873 // day links, reset 'from' to none
874 $dl = [];
875 foreach ( $linkDays as $value ) {
876 $dl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
877 [ 'days' => $value, 'from' => '' ], $nondefaults, $value == $options['days'] );
878 }
879 $dl = $lang->pipeList( $dl );
880
881 $showhide = [ 'show', 'hide' ];
882
883 $links = [];
884
885 foreach ( $this->getLegacyShowHideFilters() as $key => $filter ) {
886 $msg = $filter->getShowHide();
887 $linkMessage = $this->msg( $msg . '-' . $showhide[1 - $options[$key]] );
888 // Extensions can define additional filters, but don't need to define the corresponding
889 // messages. If they don't exist, just fall back to 'show' and 'hide'.
890 if ( !$linkMessage->exists() ) {
891 $linkMessage = $this->msg( $showhide[1 - $options[$key]] );
892 }
893
894 $link = $this->makeOptionsLink( $linkMessage->text(),
895 [ $key => 1 - $options[$key] ], $nondefaults );
896
897 $attribs = [
898 'class' => "$msg rcshowhideoption clshowhideoption",
899 'data-filter-name' => $filter->getName(),
900 ];
901
902 if ( $filter->isFeatureAvailableOnStructuredUi( $this ) ) {
903 $attribs['data-feature-in-structured-ui'] = true;
904 }
905
906 $links[] = Html::rawElement(
907 'span',
908 $attribs,
909 $this->msg( $msg )->rawParams( $link )->parse()
910 );
911 }
912
913 // show from this onward link
914 $timestamp = wfTimestampNow();
915 $now = $lang->userTimeAndDate( $timestamp, $user );
916 $timenow = $lang->userTime( $timestamp, $user );
917 $datenow = $lang->userDate( $timestamp, $user );
918 $pipedLinks = '<span class="rcshowhide">' . $lang->pipeList( $links ) . '</span>';
919
920 $rclinks = Html::rawElement(
921 'span',
922 [ 'class' => 'rclinks' ],
923 $this->msg( 'rclinks' )->rawParams( $cl, $dl, '' )->parse()
924 );
925
926 $rclistfrom = Html::rawElement(
927 'span',
928 [ 'class' => 'rclistfrom' ],
929 $this->makeOptionsLink(
930 $this->msg( 'rclistfrom' )->plaintextParams( $now, $timenow, $datenow )->parse(),
931 [ 'from' => $timestamp, 'fromFormatted' => $now ],
932 $nondefaults
933 )
934 );
935
936 return "{$note}$rclinks<br />$pipedLinks<br />$rclistfrom";
937 }
938
939 public function isIncludable() {
940 return true;
941 }
942
943 protected function getCacheTTL() {
944 return 60 * 5;
945 }
946
947 public function getDefaultLimit() {
948 $systemPrefValue = $this->getUser()->getIntOption( 'rclimit' );
949 // Prefer the RCFilters-specific preference if RCFilters is enabled
950 if ( $this->isStructuredFilterUiEnabled() ) {
951 return $this->getUser()->getIntOption( static::$limitPreferenceName, $systemPrefValue );
952 }
953
954 // Otherwise, use the system rclimit preference value
955 return $systemPrefValue;
956 }
957 }