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