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