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