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