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