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