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