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