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