Merge "Hide "hideuser" on Special:Block for non-infinite blocks"
[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 $opts->validateBounds( 'days', 0, $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
377 parent::validateOptions( $opts );
378 }
379
380 /**
381 * @inheritdoc
382 */
383 protected function buildQuery( &$tables, &$fields, &$conds,
384 &$query_options, &$join_conds, FormOptions $opts
385 ) {
386 $dbr = $this->getDB();
387 parent::buildQuery( $tables, $fields, $conds,
388 $query_options, $join_conds, $opts );
389
390 // Calculate cutoff
391 $cutoff_unixtime = time() - $opts['days'] * 3600 * 24;
392 $cutoff = $dbr->timestamp( $cutoff_unixtime );
393
394 $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
395 if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW, $cutoff ) ) {
396 $cutoff = $dbr->timestamp( $opts['from'] );
397 } else {
398 $opts->reset( 'from' );
399 }
400
401 $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
402 }
403
404 /**
405 * @inheritdoc
406 */
407 protected function doMainQuery( $tables, $fields, $conds, $query_options,
408 $join_conds, FormOptions $opts
409 ) {
410 $dbr = $this->getDB();
411 $user = $this->getUser();
412
413 $tables[] = 'recentchanges';
414 $fields = array_merge( RecentChange::selectFields(), $fields );
415
416 // JOIN on watchlist for users
417 if ( $user->isLoggedIn() && $user->isAllowed( 'viewmywatchlist' ) ) {
418 $tables[] = 'watchlist';
419 $fields[] = 'wl_user';
420 $fields[] = 'wl_notificationtimestamp';
421 $join_conds['watchlist'] = [ 'LEFT JOIN', [
422 'wl_user' => $user->getId(),
423 'wl_title=rc_title',
424 'wl_namespace=rc_namespace'
425 ] ];
426 }
427
428 // JOIN on page, used for 'last revision' filter highlight
429 $tables[] = 'page';
430 $fields[] = 'page_latest';
431 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
432
433 $tagFilter = $opts['tagfilter'] ? explode( '|', $opts['tagfilter'] ) : [];
434 ChangeTags::modifyDisplayQuery(
435 $tables,
436 $fields,
437 $conds,
438 $join_conds,
439 $query_options,
440 $tagFilter
441 );
442
443 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
444 $opts )
445 ) {
446 return false;
447 }
448
449 if ( $this->areFiltersInConflict() ) {
450 return false;
451 }
452
453 $orderByAndLimit = [
454 'ORDER BY' => 'rc_timestamp DESC',
455 'LIMIT' => $opts['limit']
456 ];
457 if ( in_array( 'DISTINCT', $query_options ) ) {
458 // ChangeTags::modifyDisplayQuery() adds DISTINCT when filtering on multiple tags.
459 // In order to prevent DISTINCT from causing query performance problems,
460 // we have to GROUP BY the primary key. This in turn requires us to add
461 // the primary key to the end of the ORDER BY, and the old ORDER BY to the
462 // start of the GROUP BY
463 $orderByAndLimit['ORDER BY'] = 'rc_timestamp DESC, rc_id DESC';
464 $orderByAndLimit['GROUP BY'] = 'rc_timestamp, rc_id';
465 }
466 // array_merge() is used intentionally here so that hooks can, should
467 // they so desire, override the ORDER BY / LIMIT condition(s); prior to
468 // MediaWiki 1.26 this used to use the plus operator instead, which meant
469 // that extensions weren't able to change these conditions
470 $query_options = array_merge( $orderByAndLimit, $query_options );
471 $rows = $dbr->select(
472 $tables,
473 $fields,
474 // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
475 // knowledge to use an index merge if it wants (it may use some other index though).
476 $conds + [ 'rc_new' => [ 0, 1 ] ],
477 __METHOD__,
478 $query_options,
479 $join_conds
480 );
481
482 // Build the final data
483 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
484 $this->filterByCategories( $rows, $opts );
485 }
486
487 return $rows;
488 }
489
490 protected function runMainQueryHook( &$tables, &$fields, &$conds,
491 &$query_options, &$join_conds, $opts
492 ) {
493 return parent::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
494 && Hooks::run(
495 'SpecialRecentChangesQuery',
496 [ &$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields ],
497 '1.23'
498 );
499 }
500
501 protected function getDB() {
502 return wfGetDB( DB_REPLICA, 'recentchanges' );
503 }
504
505 public function outputFeedLinks() {
506 $this->addFeedLinks( $this->getFeedQuery() );
507 }
508
509 /**
510 * Get URL query parameters for action=feedrecentchanges API feed of current recent changes view.
511 *
512 * @return array
513 */
514 protected function getFeedQuery() {
515 $query = array_filter( $this->getOptions()->getAllValues(), function ( $value ) {
516 // API handles empty parameters in a different way
517 return $value !== '';
518 } );
519 $query['action'] = 'feedrecentchanges';
520 $feedLimit = $this->getConfig()->get( 'FeedLimit' );
521 if ( $query['limit'] > $feedLimit ) {
522 $query['limit'] = $feedLimit;
523 }
524
525 return $query;
526 }
527
528 /**
529 * Build and output the actual changes list.
530 *
531 * @param ResultWrapper $rows Database rows
532 * @param FormOptions $opts
533 */
534 public function outputChangesList( $rows, $opts ) {
535 $limit = $opts['limit'];
536
537 $showWatcherCount = $this->getConfig()->get( 'RCShowWatchingUsers' )
538 && $this->getUser()->getOption( 'shownumberswatching' );
539 $watcherCache = [];
540
541 $dbr = $this->getDB();
542
543 $counter = 1;
544 $list = ChangesList::newFromContext( $this->getContext(), $this->filterGroups );
545 $list->initChangesListRows( $rows );
546
547 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
548 $rclistOutput = $list->beginRecentChangesList();
549 if ( $this->isStructuredFilterUiEnabled() ) {
550 $rclistOutput .= $this->makeLegend();
551 }
552
553 foreach ( $rows as $obj ) {
554 if ( $limit == 0 ) {
555 break;
556 }
557 $rc = RecentChange::newFromRow( $obj );
558
559 # Skip CatWatch entries for hidden cats based on user preference
560 if (
561 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE &&
562 !$userShowHiddenCats &&
563 $rc->getParam( 'hidden-cat' )
564 ) {
565 continue;
566 }
567
568 $rc->counter = $counter++;
569 # Check if the page has been updated since the last visit
570 if ( $this->getConfig()->get( 'ShowUpdatedMarker' )
571 && !empty( $obj->wl_notificationtimestamp )
572 ) {
573 $rc->notificationtimestamp = ( $obj->rc_timestamp >= $obj->wl_notificationtimestamp );
574 } else {
575 $rc->notificationtimestamp = false; // Default
576 }
577 # Check the number of users watching the page
578 $rc->numberofWatchingusers = 0; // Default
579 if ( $showWatcherCount && $obj->rc_namespace >= 0 ) {
580 if ( !isset( $watcherCache[$obj->rc_namespace][$obj->rc_title] ) ) {
581 $watcherCache[$obj->rc_namespace][$obj->rc_title] =
582 MediaWikiServices::getInstance()->getWatchedItemStore()->countWatchers(
583 new TitleValue( (int)$obj->rc_namespace, $obj->rc_title )
584 );
585 }
586 $rc->numberofWatchingusers = $watcherCache[$obj->rc_namespace][$obj->rc_title];
587 }
588
589 $changeLine = $list->recentChangesLine( $rc, !empty( $obj->wl_user ), $counter );
590 if ( $changeLine !== false ) {
591 $rclistOutput .= $changeLine;
592 --$limit;
593 }
594 }
595 $rclistOutput .= $list->endRecentChangesList();
596
597 if ( $rows->numRows() === 0 ) {
598 $this->outputNoResults();
599 if ( !$this->including() ) {
600 $this->getOutput()->setStatusCode( 404 );
601 }
602 } else {
603 $this->getOutput()->addHTML( $rclistOutput );
604 }
605 }
606
607 /**
608 * Set the text to be displayed above the changes
609 *
610 * @param FormOptions $opts
611 * @param int $numRows Number of rows in the result to show after this header
612 */
613 public function doHeader( $opts, $numRows ) {
614 $this->setTopText( $opts );
615
616 $defaults = $opts->getAllValues();
617 $nondefaults = $opts->getChangedValues();
618
619 $panel = [];
620 if ( !$this->isStructuredFilterUiEnabled() ) {
621 $panel[] = $this->makeLegend();
622 }
623 $panel[] = $this->optionsPanel( $defaults, $nondefaults, $numRows );
624 $panel[] = '<hr />';
625
626 $extraOpts = $this->getExtraOptions( $opts );
627 $extraOptsCount = count( $extraOpts );
628 $count = 0;
629 $submit = ' ' . Xml::submitButton( $this->msg( 'recentchanges-submit' )->text() );
630
631 $out = Xml::openElement( 'table', [ 'class' => 'mw-recentchanges-table' ] );
632 foreach ( $extraOpts as $name => $optionRow ) {
633 # Add submit button to the last row only
634 ++$count;
635 $addSubmit = ( $count === $extraOptsCount ) ? $submit : '';
636
637 $out .= Xml::openElement( 'tr' );
638 if ( is_array( $optionRow ) ) {
639 $out .= Xml::tags(
640 'td',
641 [ 'class' => 'mw-label mw-' . $name . '-label' ],
642 $optionRow[0]
643 );
644 $out .= Xml::tags(
645 'td',
646 [ 'class' => 'mw-input' ],
647 $optionRow[1] . $addSubmit
648 );
649 } else {
650 $out .= Xml::tags(
651 'td',
652 [ 'class' => 'mw-input', 'colspan' => 2 ],
653 $optionRow . $addSubmit
654 );
655 }
656 $out .= Xml::closeElement( 'tr' );
657 }
658 $out .= Xml::closeElement( 'table' );
659
660 $unconsumed = $opts->getUnconsumedValues();
661 foreach ( $unconsumed as $key => $value ) {
662 $out .= Html::hidden( $key, $value );
663 }
664
665 $t = $this->getPageTitle();
666 $out .= Html::hidden( 'title', $t->getPrefixedText() );
667 $form = Xml::tags( 'form', [ 'action' => wfScript() ], $out );
668 $panel[] = $form;
669 $panelString = implode( "\n", $panel );
670
671 $rcoptions = Xml::fieldset(
672 $this->msg( 'recentchanges-legend' )->text(),
673 $panelString,
674 [ 'class' => 'rcoptions' ]
675 );
676
677 // Insert a placeholder for RCFilters
678 if ( $this->getUser()->getOption( 'rcenhancedfilters' ) ) {
679 $rcfilterContainer = Html::element(
680 'div',
681 [ 'class' => 'rcfilters-container' ]
682 );
683
684 $loadingContainer = Html::rawElement(
685 'div',
686 [ 'class' => 'rcfilters-spinner' ],
687 Html::element(
688 'div',
689 [ 'class' => 'rcfilters-spinner-bounce' ]
690 )
691 );
692
693 // Wrap both with rcfilters-head
694 $this->getOutput()->addHTML(
695 Html::rawElement(
696 'div',
697 [ 'class' => 'rcfilters-head' ],
698 $rcfilterContainer . $rcoptions
699 )
700 );
701
702 // Add spinner
703 $this->getOutput()->addHTML( $loadingContainer );
704 } else {
705 $this->getOutput()->addHTML( $rcoptions );
706 }
707
708 $this->setBottomText( $opts );
709 }
710
711 /**
712 * Send the text to be displayed above the options
713 *
714 * @param FormOptions $opts Unused
715 */
716 function setTopText( FormOptions $opts ) {
717 global $wgContLang;
718
719 $message = $this->msg( 'recentchangestext' )->inContentLanguage();
720 if ( !$message->isDisabled() ) {
721 $content = $message->parse();
722
723 $langAttributes = [
724 'lang' => $wgContLang->getHtmlCode(),
725 'dir' => $wgContLang->getDir(),
726 ];
727
728 $topLinksAttributes = [ 'class' => 'mw-recentchanges-toplinks' ];
729
730 if ( $this->getUser()->getOption( 'rcenhancedfilters' ) ) {
731 $contentTitle = Html::rawElement( 'div',
732 [ 'class' => 'mw-recentchanges-toplinks-title' ],
733 $this->msg( 'rcfilters-other-review-tools' )->parse()
734 );
735 $contentWrapper = Html::rawElement( 'div',
736 array_merge( [ 'class' => 'mw-collapsible-content' ], $langAttributes ),
737 $content
738 );
739 $content = $contentTitle . $contentWrapper;
740 } else {
741 // Language direction should be on the top div only
742 // if the title is not there. If it is there, it's
743 // interface direction, and the language/dir attributes
744 // should be on the content itself
745 $topLinksAttributes = array_merge( $topLinksAttributes, $langAttributes );
746 }
747
748 $this->getOutput()->addHTML(
749 Html::rawElement( 'div', $topLinksAttributes, $content )
750 );
751 }
752 }
753
754 /**
755 * Get options to be displayed in a form
756 *
757 * @param FormOptions $opts
758 * @return array
759 */
760 function getExtraOptions( $opts ) {
761 $opts->consumeValues( [
762 'namespace', 'invert', 'associated', 'tagfilter', 'categories', 'categories_any'
763 ] );
764
765 $extraOpts = [];
766 $extraOpts['namespace'] = $this->namespaceFilterForm( $opts );
767
768 if ( $this->getConfig()->get( 'AllowCategorizedRecentChanges' ) ) {
769 $extraOpts['category'] = $this->categoryFilterForm( $opts );
770 }
771
772 $tagFilter = ChangeTags::buildTagFilterSelector(
773 $opts['tagfilter'], false, $this->getContext() );
774 if ( count( $tagFilter ) ) {
775 $extraOpts['tagfilter'] = $tagFilter;
776 }
777
778 // Don't fire the hook for subclasses. (Or should we?)
779 if ( $this->getName() === 'Recentchanges' ) {
780 Hooks::run( 'SpecialRecentChangesPanel', [ &$extraOpts, $opts ] );
781 }
782
783 return $extraOpts;
784 }
785
786 /**
787 * Check whether the structured filter UI is enabled
788 *
789 * @return bool
790 */
791 protected function isStructuredFilterUiEnabled() {
792 return $this->getUser()->getOption(
793 'rcenhancedfilters'
794 );
795 }
796
797 /**
798 * Add page-specific modules.
799 */
800 protected function addModules() {
801 parent::addModules();
802 $out = $this->getOutput();
803 $out->addModules( 'mediawiki.special.recentchanges' );
804 if ( $this->isStructuredFilterUiEnabled() ) {
805 $out->addModules( 'mediawiki.rcfilters.filters.ui' );
806 $out->addModuleStyles( 'mediawiki.rcfilters.filters.base.styles' );
807 }
808 }
809
810 /**
811 * Get last modified date, for client caching
812 * Don't use this if we are using the patrol feature, patrol changes don't
813 * update the timestamp
814 *
815 * @return string|bool
816 */
817 public function checkLastModified() {
818 $dbr = $this->getDB();
819 $lastmod = $dbr->selectField( 'recentchanges', 'MAX(rc_timestamp)', false, __METHOD__ );
820
821 return $lastmod;
822 }
823
824 /**
825 * Creates the choose namespace selection
826 *
827 * @param FormOptions $opts
828 * @return string
829 */
830 protected function namespaceFilterForm( FormOptions $opts ) {
831 $nsSelect = Html::namespaceSelector(
832 [ 'selected' => $opts['namespace'], 'all' => '' ],
833 [ 'name' => 'namespace', 'id' => 'namespace' ]
834 );
835 $nsLabel = Xml::label( $this->msg( 'namespace' )->text(), 'namespace' );
836 $invert = Xml::checkLabel(
837 $this->msg( 'invert' )->text(), 'invert', 'nsinvert',
838 $opts['invert'],
839 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
840 );
841 $associated = Xml::checkLabel(
842 $this->msg( 'namespace_association' )->text(), 'associated', 'nsassociated',
843 $opts['associated'],
844 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
845 );
846
847 return [ $nsLabel, "$nsSelect $invert $associated" ];
848 }
849
850 /**
851 * Create an input to filter changes by categories
852 *
853 * @param FormOptions $opts
854 * @return array
855 */
856 protected function categoryFilterForm( FormOptions $opts ) {
857 list( $label, $input ) = Xml::inputLabelSep( $this->msg( 'rc_categories' )->text(),
858 'categories', 'mw-categories', false, $opts['categories'] );
859
860 $input .= ' ' . Xml::checkLabel( $this->msg( 'rc_categories_any' )->text(),
861 'categories_any', 'mw-categories_any', $opts['categories_any'] );
862
863 return [ $label, $input ];
864 }
865
866 /**
867 * Filter $rows by categories set in $opts
868 *
869 * @param ResultWrapper $rows Database rows
870 * @param FormOptions $opts
871 */
872 function filterByCategories( &$rows, FormOptions $opts ) {
873 $categories = array_map( 'trim', explode( '|', $opts['categories'] ) );
874
875 if ( !count( $categories ) ) {
876 return;
877 }
878
879 # Filter categories
880 $cats = [];
881 foreach ( $categories as $cat ) {
882 $cat = trim( $cat );
883 if ( $cat == '' ) {
884 continue;
885 }
886 $cats[] = $cat;
887 }
888
889 # Filter articles
890 $articles = [];
891 $a2r = [];
892 $rowsarr = [];
893 foreach ( $rows as $k => $r ) {
894 $nt = Title::makeTitle( $r->rc_namespace, $r->rc_title );
895 $id = $nt->getArticleID();
896 if ( $id == 0 ) {
897 continue; # Page might have been deleted...
898 }
899 if ( !in_array( $id, $articles ) ) {
900 $articles[] = $id;
901 }
902 if ( !isset( $a2r[$id] ) ) {
903 $a2r[$id] = [];
904 }
905 $a2r[$id][] = $k;
906 $rowsarr[$k] = $r;
907 }
908
909 # Shortcut?
910 if ( !count( $articles ) || !count( $cats ) ) {
911 return;
912 }
913
914 # Look up
915 $catFind = new CategoryFinder;
916 $catFind->seed( $articles, $cats, $opts['categories_any'] ? 'OR' : 'AND' );
917 $match = $catFind->run();
918
919 # Filter
920 $newrows = [];
921 foreach ( $match as $id ) {
922 foreach ( $a2r[$id] as $rev ) {
923 $k = $rev;
924 $newrows[$k] = $rowsarr[$k];
925 }
926 }
927 $rows = new FakeResultWrapper( array_values( $newrows ) );
928 }
929
930 /**
931 * Makes change an option link which carries all the other options
932 *
933 * @param string $title Title
934 * @param array $override Options to override
935 * @param array $options Current options
936 * @param bool $active Whether to show the link in bold
937 * @return string
938 */
939 function makeOptionsLink( $title, $override, $options, $active = false ) {
940 $params = $this->convertParamsForLink( $override + $options );
941
942 if ( $active ) {
943 $title = new HtmlArmor( '<strong>' . htmlspecialchars( $title ) . '</strong>' );
944 }
945
946 return $this->getLinkRenderer()->makeKnownLink( $this->getPageTitle(), $title, [
947 'data-params' => json_encode( $override ),
948 'data-keys' => implode( ',', array_keys( $override ) ),
949 ], $params );
950 }
951
952 /**
953 * Creates the options panel.
954 *
955 * @param array $defaults
956 * @param array $nondefaults
957 * @param int $numRows Number of rows in the result to show after this header
958 * @return string
959 */
960 function optionsPanel( $defaults, $nondefaults, $numRows ) {
961 $options = $nondefaults + $defaults;
962
963 $note = '';
964 $msg = $this->msg( 'rclegend' );
965 if ( !$msg->isDisabled() ) {
966 $note .= '<div class="mw-rclegend">' . $msg->parse() . "</div>\n";
967 }
968
969 $lang = $this->getLanguage();
970 $user = $this->getUser();
971 $config = $this->getConfig();
972 if ( $options['from'] ) {
973 $resetLink = $this->makeOptionsLink( $this->msg( 'rclistfromreset' ),
974 [ 'from' => '' ], $nondefaults );
975
976 $note .= $this->msg( 'rcnotefrom' )
977 ->numParams( $options['limit'] )
978 ->params(
979 $lang->userTimeAndDate( $options['from'], $user ),
980 $lang->userDate( $options['from'], $user ),
981 $lang->userTime( $options['from'], $user )
982 )
983 ->numParams( $numRows )
984 ->parse() . ' ' .
985 Html::rawElement(
986 'span',
987 [ 'class' => 'rcoptions-listfromreset' ],
988 $this->msg( 'parentheses' )->rawParams( $resetLink )->parse()
989 ) .
990 '<br />';
991 }
992
993 # Sort data for display and make sure it's unique after we've added user data.
994 $linkLimits = $config->get( 'RCLinkLimits' );
995 $linkLimits[] = $options['limit'];
996 sort( $linkLimits );
997 $linkLimits = array_unique( $linkLimits );
998
999 $linkDays = $config->get( 'RCLinkDays' );
1000 $linkDays[] = $options['days'];
1001 sort( $linkDays );
1002 $linkDays = array_unique( $linkDays );
1003
1004 // limit links
1005 $cl = [];
1006 foreach ( $linkLimits as $value ) {
1007 $cl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
1008 [ 'limit' => $value ], $nondefaults, $value == $options['limit'] );
1009 }
1010 $cl = $lang->pipeList( $cl );
1011
1012 // day links, reset 'from' to none
1013 $dl = [];
1014 foreach ( $linkDays as $value ) {
1015 $dl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
1016 [ 'days' => $value, 'from' => '' ], $nondefaults, $value == $options['days'] );
1017 }
1018 $dl = $lang->pipeList( $dl );
1019
1020 $showhide = [ 'show', 'hide' ];
1021
1022 $links = [];
1023
1024 $filterGroups = $this->getFilterGroups();
1025
1026 $context = $this->getContext();
1027 foreach ( $filterGroups as $groupName => $group ) {
1028 if ( !$group->isPerGroupRequestParameter() ) {
1029 foreach ( $group->getFilters() as $key => $filter ) {
1030 if ( $filter->displaysOnUnstructuredUi( $this ) ) {
1031 $msg = $filter->getShowHide();
1032 $linkMessage = $this->msg( $msg . '-' . $showhide[1 - $options[$key]] );
1033 // Extensions can define additional filters, but don't need to define the corresponding
1034 // messages. If they don't exist, just fall back to 'show' and 'hide'.
1035 if ( !$linkMessage->exists() ) {
1036 $linkMessage = $this->msg( $showhide[1 - $options[$key]] );
1037 }
1038
1039 $link = $this->makeOptionsLink( $linkMessage->text(),
1040 [ $key => 1 - $options[$key] ], $nondefaults );
1041
1042 $attribs = [
1043 'class' => "$msg rcshowhideoption",
1044 'data-filter-name' => $filter->getName(),
1045 ];
1046
1047 if ( $filter->isFeatureAvailableOnStructuredUi( $this ) ) {
1048 $attribs['data-feature-in-structured-ui'] = true;
1049 }
1050
1051 $links[] = Html::rawElement(
1052 'span',
1053 $attribs,
1054 $this->msg( $msg )->rawParams( $link )->escaped()
1055 );
1056 }
1057 }
1058 }
1059 }
1060
1061 // show from this onward link
1062 $timestamp = wfTimestampNow();
1063 $now = $lang->userTimeAndDate( $timestamp, $user );
1064 $timenow = $lang->userTime( $timestamp, $user );
1065 $datenow = $lang->userDate( $timestamp, $user );
1066 $pipedLinks = '<span class="rcshowhide">' . $lang->pipeList( $links ) . '</span>';
1067
1068 $rclinks = '<span class="rclinks">' . $this->msg( 'rclinks' )->rawParams( $cl, $dl, '' )
1069 ->parse() . '</span>';
1070
1071 $rclistfrom = '<span class="rclistfrom">' . $this->makeOptionsLink(
1072 $this->msg( 'rclistfrom' )->rawParams( $now, $timenow, $datenow )->parse(),
1073 [ 'from' => $timestamp ],
1074 $nondefaults
1075 ) . '</span>';
1076
1077 return "{$note}$rclinks<br />$pipedLinks<br />$rclistfrom";
1078 }
1079
1080 public function isIncludable() {
1081 return true;
1082 }
1083
1084 protected function getCacheTTL() {
1085 return 60 * 5;
1086 }
1087 }