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