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