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