Merge "Provide an opt-out preference for New Filters for RecentChanges"
[lhc/web/wiklou.git] / includes / specials / SpecialWatchlist.php
1 <?php
2 /**
3 * Implements Special:Watchlist
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\IDatabase;
27
28 /**
29 * A special page that lists last changes made to the wiki,
30 * limited to user-defined list of titles.
31 *
32 * @ingroup SpecialPage
33 */
34 class SpecialWatchlist extends ChangesListSpecialPage {
35 private $maxDays;
36
37 public function __construct( $page = 'Watchlist', $restriction = 'viewmywatchlist' ) {
38 parent::__construct( $page, $restriction );
39
40 $this->maxDays = $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 );
41 }
42
43 public function doesWrites() {
44 return true;
45 }
46
47 /**
48 * Main execution point
49 *
50 * @param string $subpage
51 */
52 function execute( $subpage ) {
53 // Anons don't get a watchlist
54 $this->requireLogin( 'watchlistanontext' );
55
56 $output = $this->getOutput();
57 $request = $this->getRequest();
58 $this->addHelpLink( 'Help:Watching pages' );
59 $output->addModules( [
60 'mediawiki.special.changeslist.visitedstatus',
61 'mediawiki.special.watchlist',
62 ] );
63 $output->addModuleStyles( [ 'mediawiki.special.watchlist.styles' ] );
64
65 $mode = SpecialEditWatchlist::getMode( $request, $subpage );
66 if ( $mode !== false ) {
67 if ( $mode === SpecialEditWatchlist::EDIT_RAW ) {
68 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'raw' );
69 } elseif ( $mode === SpecialEditWatchlist::EDIT_CLEAR ) {
70 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'clear' );
71 } else {
72 $title = SpecialPage::getTitleFor( 'EditWatchlist' );
73 }
74
75 $output->redirect( $title->getLocalURL() );
76
77 return;
78 }
79
80 $this->checkPermissions();
81
82 $user = $this->getUser();
83 $opts = $this->getOptions();
84
85 $config = $this->getConfig();
86 if ( ( $config->get( 'EnotifWatchlist' ) || $config->get( 'ShowUpdatedMarker' ) )
87 && $request->getVal( 'reset' )
88 && $request->wasPosted()
89 && $user->matchEditToken( $request->getVal( 'token' ) )
90 ) {
91 $user->clearAllNotifications();
92 $output->redirect( $this->getPageTitle()->getFullURL( $opts->getChangedValues() ) );
93
94 return;
95 }
96
97 parent::execute( $subpage );
98
99 if ( $this->isStructuredFilterUiEnabled() ) {
100 $output->addModuleStyles( [ 'mediawiki.rcfilters.highlightCircles.seenunseen.styles' ] );
101
102 $output->addJsConfigVars( 'wgStructuredChangeFiltersLiveUpdateSupported', false );
103 $output->addJsConfigVars(
104 'wgStructuredChangeFiltersSavedQueriesPreferenceName',
105 'rcfilters-wl-saved-queries'
106 );
107 $output->addJsConfigVars(
108 'wgStructuredChangeFiltersEditWatchlistUrl',
109 SpecialPage::getTitleFor( 'EditWatchlist' )->getLocalURL()
110 );
111 }
112 }
113
114 public function isStructuredFilterUiEnabled() {
115 return $this->getRequest()->getBool( 'rcfilters' ) || (
116 $this->getConfig()->get( 'StructuredChangeFiltersOnWatchlist' ) &&
117 $this->getUser()->getOption( 'rcenhancedfilters' )
118 );
119 }
120
121 public function isStructuredFilterUiEnabledByDefault() {
122 return $this->getConfig()->get( 'StructuredChangeFiltersOnWatchlist' ) &&
123 $this->getUser()->getDefaultOption( 'rcenhancedfilters' );
124 }
125
126 /**
127 * Return an array of subpages that this special page will accept.
128 *
129 * @see also SpecialEditWatchlist::getSubpagesForPrefixSearch
130 * @return string[] subpages
131 */
132 public function getSubpagesForPrefixSearch() {
133 return [
134 'clear',
135 'edit',
136 'raw',
137 ];
138 }
139
140 /**
141 * @inheritDoc
142 */
143 protected function transformFilterDefinition( array $filterDefinition ) {
144 if ( isset( $filterDefinition['showHideSuffix'] ) ) {
145 $filterDefinition['showHide'] = 'wl' . $filterDefinition['showHideSuffix'];
146 }
147
148 return $filterDefinition;
149 }
150
151 /**
152 * @inheritDoc
153 */
154 protected function registerFilters() {
155 parent::registerFilters();
156
157 // legacy 'extended' filter
158 $this->registerFilterGroup( new ChangesListBooleanFilterGroup( [
159 'name' => 'extended-group',
160 'filters' => [
161 [
162 'name' => 'extended',
163 'isReplacedInStructuredUi' => true,
164 'activeValue' => false,
165 'default' => $this->getUser()->getBoolOption( 'extendwatchlist' ),
166 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables,
167 &$fields, &$conds, &$query_options, &$join_conds ) {
168 $nonRevisionTypes = [ RC_LOG ];
169 Hooks::run( 'SpecialWatchlistGetNonRevisionTypes', [ &$nonRevisionTypes ] );
170 if ( $nonRevisionTypes ) {
171 $conds[] = $dbr->makeList(
172 [
173 'rc_this_oldid=page_latest',
174 'rc_type' => $nonRevisionTypes,
175 ],
176 LIST_OR
177 );
178 }
179 },
180 ]
181 ],
182
183 ] ) );
184
185 if ( $this->isStructuredFilterUiEnabled() ) {
186 $this->getFilterGroup( 'lastRevision' )
187 ->getFilter( 'hidepreviousrevisions' )
188 ->setDefault( !$this->getUser()->getBoolOption( 'extendwatchlist' ) );
189 }
190
191 $this->registerFilterGroup( new ChangesListStringOptionsFilterGroup( [
192 'name' => 'watchlistactivity',
193 'title' => 'rcfilters-filtergroup-watchlistactivity',
194 'class' => ChangesListStringOptionsFilterGroup::class,
195 'priority' => 3,
196 'isFullCoverage' => true,
197 'filters' => [
198 [
199 'name' => 'unseen',
200 'label' => 'rcfilters-filter-watchlistactivity-unseen-label',
201 'description' => 'rcfilters-filter-watchlistactivity-unseen-description',
202 'cssClassSuffix' => 'watchedunseen',
203 'isRowApplicableCallable' => function ( $ctx, $rc ) {
204 $changeTs = $rc->getAttribute( 'rc_timestamp' );
205 $lastVisitTs = $rc->getAttribute( 'wl_notificationtimestamp' );
206 return $lastVisitTs !== null && $changeTs >= $lastVisitTs;
207 },
208 ],
209 [
210 'name' => 'seen',
211 'label' => 'rcfilters-filter-watchlistactivity-seen-label',
212 'description' => 'rcfilters-filter-watchlistactivity-seen-description',
213 'cssClassSuffix' => 'watchedseen',
214 'isRowApplicableCallable' => function ( $ctx, $rc ) {
215 $changeTs = $rc->getAttribute( 'rc_timestamp' );
216 $lastVisitTs = $rc->getAttribute( 'wl_notificationtimestamp' );
217 return $lastVisitTs === null || $changeTs < $lastVisitTs;
218 }
219 ],
220 ],
221 'default' => ChangesListStringOptionsFilterGroup::NONE,
222 'queryCallable' => function ( $specialPageClassName, $context, $dbr,
223 &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selectedValues ) {
224 if ( $selectedValues === [ 'seen' ] ) {
225 $conds[] = $dbr->makeList( [
226 'wl_notificationtimestamp IS NULL',
227 'rc_timestamp < wl_notificationtimestamp'
228 ], LIST_OR );
229 } elseif ( $selectedValues === [ 'unseen' ] ) {
230 $conds[] = $dbr->makeList( [
231 'wl_notificationtimestamp IS NOT NULL',
232 'rc_timestamp >= wl_notificationtimestamp'
233 ], LIST_AND );
234 }
235 }
236 ] ) );
237
238 $user = $this->getUser();
239
240 $significance = $this->getFilterGroup( 'significance' );
241 $hideMinor = $significance->getFilter( 'hideminor' );
242 $hideMinor->setDefault( $user->getBoolOption( 'watchlisthideminor' ) );
243
244 $automated = $this->getFilterGroup( 'automated' );
245 $hideBots = $automated->getFilter( 'hidebots' );
246 $hideBots->setDefault( $user->getBoolOption( 'watchlisthidebots' ) );
247
248 $registration = $this->getFilterGroup( 'registration' );
249 $hideAnons = $registration->getFilter( 'hideanons' );
250 $hideAnons->setDefault( $user->getBoolOption( 'watchlisthideanons' ) );
251 $hideLiu = $registration->getFilter( 'hideliu' );
252 $hideLiu->setDefault( $user->getBoolOption( 'watchlisthideliu' ) );
253
254 $reviewStatus = $this->getFilterGroup( 'reviewStatus' );
255 if ( $reviewStatus !== null ) {
256 // Conditional on feature being available and rights
257 $hidePatrolled = $reviewStatus->getFilter( 'hidepatrolled' );
258 $hidePatrolled->setDefault( $user->getBoolOption( 'watchlisthidepatrolled' ) );
259 }
260
261 $authorship = $this->getFilterGroup( 'authorship' );
262 $hideMyself = $authorship->getFilter( 'hidemyself' );
263 $hideMyself->setDefault( $user->getBoolOption( 'watchlisthideown' ) );
264
265 $changeType = $this->getFilterGroup( 'changeType' );
266 $hideCategorization = $changeType->getFilter( 'hidecategorization' );
267 if ( $hideCategorization !== null ) {
268 // Conditional on feature being available
269 $hideCategorization->setDefault( $user->getBoolOption( 'watchlisthidecategorization' ) );
270 }
271 }
272
273 /**
274 * Get a FormOptions object containing the default options
275 *
276 * @return FormOptions
277 */
278 public function getDefaultOptions() {
279 $opts = parent::getDefaultOptions();
280 $user = $this->getUser();
281
282 $opts->add( 'days', $user->getOption( 'watchlistdays' ), FormOptions::FLOAT );
283 $opts->add( 'limit', $user->getIntOption( 'wllimit' ), FormOptions::INT );
284
285 return $opts;
286 }
287
288 public function validateOptions( FormOptions $opts ) {
289 $opts->validateBounds( 'days', 0, $this->maxDays );
290 $opts->validateIntBounds( 'limit', 0, 5000 );
291 parent::validateOptions( $opts );
292 }
293
294 /**
295 * Get all custom filters
296 *
297 * @return array Map of filter URL param names to properties (msg/default)
298 */
299 protected function getCustomFilters() {
300 if ( $this->customFilters === null ) {
301 $this->customFilters = parent::getCustomFilters();
302 Hooks::run( 'SpecialWatchlistFilters', [ $this, &$this->customFilters ], '1.23' );
303 }
304
305 return $this->customFilters;
306 }
307
308 /**
309 * Fetch values for a FormOptions object from the WebRequest associated with this instance.
310 *
311 * Maps old pre-1.23 request parameters Watchlist used to use (different from Recentchanges' ones)
312 * to the current ones.
313 *
314 * @param FormOptions $opts
315 * @return FormOptions
316 */
317 protected function fetchOptionsFromRequest( $opts ) {
318 static $compatibilityMap = [
319 'hideMinor' => 'hideminor',
320 'hideBots' => 'hidebots',
321 'hideAnons' => 'hideanons',
322 'hideLiu' => 'hideliu',
323 'hidePatrolled' => 'hidepatrolled',
324 'hideOwn' => 'hidemyself',
325 ];
326
327 $params = $this->getRequest()->getValues();
328 foreach ( $compatibilityMap as $from => $to ) {
329 if ( isset( $params[$from] ) ) {
330 $params[$to] = $params[$from];
331 unset( $params[$from] );
332 }
333 }
334
335 if ( $this->getRequest()->getVal( 'action' ) == 'submit' ) {
336 $allBooleansFalse = [];
337
338 // If the user submitted the form, start with a baseline of "all
339 // booleans are false", then change the ones they checked. This
340 // means we ignore the defaults.
341
342 // This is how we handle the fact that HTML forms don't submit
343 // unchecked boxes.
344 foreach ( $this->filterGroups as $filterGroup ) {
345 if ( $filterGroup instanceof ChangesListBooleanFilterGroup ) {
346 /** @var ChangesListBooleanFilter $filter */
347 foreach ( $filterGroup->getFilters() as $filter ) {
348 if ( $filter->displaysOnUnstructuredUi() ) {
349 $allBooleansFalse[$filter->getName()] = false;
350 }
351 }
352 }
353 }
354
355 $params = $params + $allBooleansFalse;
356 }
357
358 // Not the prettiest way to achieve this… FormOptions internally depends on data sanitization
359 // methods defined on WebRequest and removing this dependency would cause some code duplication.
360 $request = new DerivativeRequest( $this->getRequest(), $params );
361 $opts->fetchValuesFromRequest( $request );
362
363 return $opts;
364 }
365
366 /**
367 * @inheritDoc
368 */
369 protected function buildQuery( &$tables, &$fields, &$conds, &$query_options,
370 &$join_conds, FormOptions $opts
371 ) {
372 $dbr = $this->getDB();
373 parent::buildQuery( $tables, $fields, $conds, $query_options, $join_conds,
374 $opts );
375
376 // Calculate cutoff
377 if ( $opts['days'] > 0 ) {
378 $conds[] = 'rc_timestamp > ' .
379 $dbr->addQuotes( $dbr->timestamp( time() - $opts['days'] * 3600 * 24 ) );
380 }
381 }
382
383 /**
384 * @inheritDoc
385 */
386 protected function doMainQuery( $tables, $fields, $conds, $query_options,
387 $join_conds, FormOptions $opts
388 ) {
389 $dbr = $this->getDB();
390 $user = $this->getUser();
391
392 $tables = array_merge( [ 'recentchanges', 'watchlist' ], $tables );
393 $fields = array_merge( RecentChange::selectFields(), $fields );
394
395 $join_conds = array_merge(
396 [
397 'watchlist' => [
398 'INNER JOIN',
399 [
400 'wl_user' => $user->getId(),
401 'wl_namespace=rc_namespace',
402 'wl_title=rc_title'
403 ],
404 ],
405 ],
406 $join_conds
407 );
408
409 $tables[] = 'page';
410 $fields[] = 'page_latest';
411 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
412
413 $fields[] = 'wl_notificationtimestamp';
414
415 // Log entries with DELETED_ACTION must not show up unless the user has
416 // the necessary rights.
417 if ( !$user->isAllowed( 'deletedhistory' ) ) {
418 $bitmask = LogPage::DELETED_ACTION;
419 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
420 $bitmask = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
421 } else {
422 $bitmask = 0;
423 }
424 if ( $bitmask ) {
425 $conds[] = $dbr->makeList( [
426 'rc_type != ' . RC_LOG,
427 $dbr->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
428 ], LIST_OR );
429 }
430
431 $tagFilter = $opts['tagfilter'] ? explode( '|', $opts['tagfilter'] ) : [];
432 ChangeTags::modifyDisplayQuery(
433 $tables,
434 $fields,
435 $conds,
436 $join_conds,
437 $query_options,
438 $tagFilter
439 );
440
441 $this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts );
442
443 if ( $this->areFiltersInConflict() ) {
444 return false;
445 }
446
447 $orderByAndLimit = [
448 'ORDER BY' => 'rc_timestamp DESC',
449 'LIMIT' => $opts['limit']
450 ];
451 if ( in_array( 'DISTINCT', $query_options ) ) {
452 // ChangeTags::modifyDisplayQuery() adds DISTINCT when filtering on multiple tags.
453 // In order to prevent DISTINCT from causing query performance problems,
454 // we have to GROUP BY the primary key. This in turn requires us to add
455 // the primary key to the end of the ORDER BY, and the old ORDER BY to the
456 // start of the GROUP BY
457 $orderByAndLimit['ORDER BY'] = 'rc_timestamp DESC, rc_id DESC';
458 $orderByAndLimit['GROUP BY'] = 'rc_timestamp, rc_id';
459 }
460 // array_merge() is used intentionally here so that hooks can, should
461 // they so desire, override the ORDER BY / LIMIT condition(s)
462 $query_options = array_merge( $orderByAndLimit, $query_options );
463
464 return $dbr->select(
465 $tables,
466 $fields,
467 $conds,
468 __METHOD__,
469 $query_options,
470 $join_conds
471 );
472 }
473
474 protected function runMainQueryHook( &$tables, &$fields, &$conds, &$query_options,
475 &$join_conds, $opts
476 ) {
477 return parent::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
478 && Hooks::run(
479 'SpecialWatchlistQuery',
480 [ &$conds, &$tables, &$join_conds, &$fields, $opts ],
481 '1.23'
482 );
483 }
484
485 /**
486 * Return a IDatabase object for reading
487 *
488 * @return IDatabase
489 */
490 protected function getDB() {
491 return wfGetDB( DB_REPLICA, 'watchlist' );
492 }
493
494 /**
495 * Output feed links.
496 */
497 public function outputFeedLinks() {
498 $user = $this->getUser();
499 $wlToken = $user->getTokenFromOption( 'watchlisttoken' );
500 if ( $wlToken ) {
501 $this->addFeedLinks( [
502 'action' => 'feedwatchlist',
503 'allrev' => 1,
504 'wlowner' => $user->getName(),
505 'wltoken' => $wlToken,
506 ] );
507 }
508 }
509
510 /**
511 * Build and output the actual changes list.
512 *
513 * @param ResultWrapper $rows Database rows
514 * @param FormOptions $opts
515 */
516 public function outputChangesList( $rows, $opts ) {
517 $dbr = $this->getDB();
518 $user = $this->getUser();
519 $output = $this->getOutput();
520
521 # Show a message about replica DB lag, if applicable
522 $lag = wfGetLB()->safeGetLag( $dbr );
523 if ( $lag > 0 ) {
524 $output->showLagWarning( $lag );
525 }
526
527 # If no rows to display, show message before try to render the list
528 if ( $rows->numRows() == 0 ) {
529 $output->wrapWikiMsg(
530 "<div class='mw-changeslist-empty'>\n$1\n</div>", 'recentchanges-noresult'
531 );
532 return;
533 }
534
535 $dbr->dataSeek( $rows, 0 );
536
537 $list = ChangesList::newFromContext( $this->getContext(), $this->filterGroups );
538 $list->setWatchlistDivs();
539 $list->initChangesListRows( $rows );
540 if ( $user->getOption( 'watchlistunwatchlinks' ) ) {
541 $list->setChangeLinePrefixer( function ( RecentChange $rc, ChangesList $cl, $grouped ) {
542 // Don't show unwatch link if the line is a grouped log entry using EnhancedChangesList,
543 // since EnhancedChangesList groups log entries by performer rather than by target article
544 if ( $rc->mAttribs['rc_type'] == RC_LOG && $cl instanceof EnhancedChangesList &&
545 $grouped ) {
546 return '';
547 } else {
548 return $this->getLinkRenderer()
549 ->makeKnownLink( $rc->getTitle(),
550 $this->msg( 'watchlist-unwatch' )->text(), [
551 'class' => 'mw-unwatch-link',
552 'title' => $this->msg( 'tooltip-ca-unwatch' )->text()
553 ], [ 'action' => 'unwatch' ] ) . '&#160;';
554 }
555 } );
556 }
557 $dbr->dataSeek( $rows, 0 );
558
559 if ( $this->getConfig()->get( 'RCShowWatchingUsers' )
560 && $user->getOption( 'shownumberswatching' )
561 ) {
562 $watchedItemStore = MediaWikiServices::getInstance()->getWatchedItemStore();
563 }
564
565 $s = $list->beginRecentChangesList();
566
567 if ( $this->isStructuredFilterUiEnabled() ) {
568 $s .= $this->makeLegend();
569 }
570
571 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
572 $counter = 1;
573 foreach ( $rows as $obj ) {
574 # Make RC entry
575 $rc = RecentChange::newFromRow( $obj );
576
577 # Skip CatWatch entries for hidden cats based on user preference
578 if (
579 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE &&
580 !$userShowHiddenCats &&
581 $rc->getParam( 'hidden-cat' )
582 ) {
583 continue;
584 }
585
586 $rc->counter = $counter++;
587
588 if ( $this->getConfig()->get( 'ShowUpdatedMarker' ) ) {
589 $updated = $obj->wl_notificationtimestamp;
590 } else {
591 $updated = false;
592 }
593
594 if ( isset( $watchedItemStore ) ) {
595 $rcTitleValue = new TitleValue( (int)$obj->rc_namespace, $obj->rc_title );
596 $rc->numberofWatchingusers = $watchedItemStore->countWatchers( $rcTitleValue );
597 } else {
598 $rc->numberofWatchingusers = 0;
599 }
600
601 $changeLine = $list->recentChangesLine( $rc, $updated, $counter );
602 if ( $changeLine !== false ) {
603 $s .= $changeLine;
604 }
605 }
606 $s .= $list->endRecentChangesList();
607
608 $output->addHTML( $s );
609 }
610
611 /**
612 * Set the text to be displayed above the changes
613 *
614 * @param FormOptions $opts
615 * @param int $numRows Number of rows in the result to show after this header
616 */
617 public function doHeader( $opts, $numRows ) {
618 $user = $this->getUser();
619 $out = $this->getOutput();
620
621 $out->addSubtitle(
622 $this->msg( 'watchlistfor2', $user->getName() )
623 ->rawParams( SpecialEditWatchlist::buildTools(
624 $this->getLanguage(),
625 $this->getLinkRenderer()
626 ) )
627 );
628
629 $this->setTopText( $opts );
630
631 $form = '';
632
633 $form .= Xml::openElement( 'form', [
634 'method' => 'get',
635 'action' => wfScript(),
636 'id' => 'mw-watchlist-form'
637 ] );
638 $form .= Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
639 $form .= Xml::fieldset(
640 $this->msg( 'watchlist-options' )->text(),
641 false,
642 [ 'id' => 'mw-watchlist-options', 'class' => 'cloptions' ]
643 );
644
645 if ( !$this->isStructuredFilterUiEnabled() ) {
646 $form .= $this->makeLegend();
647 }
648
649 $lang = $this->getLanguage();
650 if ( $opts['days'] > 0 ) {
651 $days = $opts['days'];
652 } else {
653 $days = $this->maxDays;
654 }
655 $timestamp = wfTimestampNow();
656 $wlInfo = Html::rawElement(
657 'span',
658 [ 'class' => 'wlinfo' ],
659 $this->msg( 'wlnote' )->numParams( $numRows, round( $days * 24 ) )->params(
660 $lang->userDate( $timestamp, $user ), $lang->userTime( $timestamp, $user )
661 )->parse()
662 ) . "<br />\n";
663
664 $nondefaults = $opts->getChangedValues();
665 $cutofflinks = Html::rawElement(
666 'span',
667 [ 'class' => 'cldays cloption' ],
668 $this->msg( 'wlshowtime' ) . ' ' . $this->cutoffselector( $opts )
669 );
670
671 # Spit out some control panel links
672 $links = [];
673 $namesOfDisplayedFilters = [];
674 foreach ( $this->getFilterGroups() as $groupName => $group ) {
675 if ( !$group->isPerGroupRequestParameter() ) {
676 foreach ( $group->getFilters() as $filterName => $filter ) {
677 if ( $filter->displaysOnUnstructuredUi( $this ) ) {
678 $namesOfDisplayedFilters[] = $filterName;
679 $links[] = $this->showHideCheck(
680 $nondefaults,
681 $filter->getShowHide(),
682 $filterName,
683 $opts[$filterName],
684 $filter->isFeatureAvailableOnStructuredUi( $this )
685 );
686 }
687 }
688 }
689 }
690
691 $hiddenFields = $nondefaults;
692 $hiddenFields['action'] = 'submit';
693 unset( $hiddenFields['namespace'] );
694 unset( $hiddenFields['invert'] );
695 unset( $hiddenFields['associated'] );
696 unset( $hiddenFields['days'] );
697 foreach ( $namesOfDisplayedFilters as $filterName ) {
698 unset( $hiddenFields[$filterName] );
699 }
700
701 # Namespace filter and put the whole form together.
702 $form .= $wlInfo;
703 $form .= $cutofflinks;
704 $form .= Html::rawElement(
705 'span',
706 [ 'class' => 'clshowhide' ],
707 $this->msg( 'watchlist-hide' ) .
708 $this->msg( 'colon-separator' )->escaped() .
709 implode( ' ', $links )
710 );
711 $form .= "\n<br />\n";
712
713 $namespaceForm = Html::namespaceSelector(
714 [
715 'selected' => $opts['namespace'],
716 'all' => '',
717 'label' => $this->msg( 'namespace' )->text()
718 ], [
719 'name' => 'namespace',
720 'id' => 'namespace',
721 'class' => 'namespaceselector',
722 ]
723 ) . "\n";
724 $namespaceForm .= '<span class="mw-input-with-label">' . Xml::checkLabel(
725 $this->msg( 'invert' )->text(),
726 'invert',
727 'nsinvert',
728 $opts['invert'],
729 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
730 ) . "</span>\n";
731 $namespaceForm .= '<span class="mw-input-with-label">' . Xml::checkLabel(
732 $this->msg( 'namespace_association' )->text(),
733 'associated',
734 'nsassociated',
735 $opts['associated'],
736 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
737 ) . "</span>\n";
738 $form .= Html::rawElement(
739 'span',
740 [ 'class' => 'namespaceForm cloption' ],
741 $namespaceForm
742 );
743
744 $form .= Xml::submitButton(
745 $this->msg( 'watchlist-submit' )->text(),
746 [ 'class' => 'cloption-submit' ]
747 ) . "\n";
748 foreach ( $hiddenFields as $key => $value ) {
749 $form .= Html::hidden( $key, $value ) . "\n";
750 }
751 $form .= Xml::closeElement( 'fieldset' ) . "\n";
752 $form .= Xml::closeElement( 'form' ) . "\n";
753
754 // Insert a placeholder for RCFilters
755 if ( $this->isStructuredFilterUiEnabled() ) {
756 $rcfilterContainer = Html::element(
757 'div',
758 [ 'class' => 'rcfilters-container' ]
759 );
760
761 $loadingContainer = Html::rawElement(
762 'div',
763 [ 'class' => 'rcfilters-spinner' ],
764 Html::element(
765 'div',
766 [ 'class' => 'rcfilters-spinner-bounce' ]
767 )
768 );
769
770 // Wrap both with rcfilters-head
771 $this->getOutput()->addHTML(
772 Html::rawElement(
773 'div',
774 [ 'class' => 'rcfilters-head' ],
775 $rcfilterContainer . $form
776 )
777 );
778
779 // Add spinner
780 $this->getOutput()->addHTML( $loadingContainer );
781 } else {
782 $this->getOutput()->addHTML( $form );
783 }
784
785 $this->setBottomText( $opts );
786 }
787
788 function cutoffselector( $options ) {
789 // Cast everything to strings immediately, so that we know all of the values have the same
790 // precision, and can be compared with '==='. 2/24 has a few more decimal places than its
791 // default string representation, for example, and would confuse comparisons.
792
793 // Misleadingly, the 'days' option supports hours too.
794 $days = array_map( 'strval', [ 1 / 24, 2 / 24, 6 / 24, 12 / 24, 1, 3, 7 ] );
795
796 $userWatchlistOption = (string)$this->getUser()->getOption( 'watchlistdays' );
797 // add the user preference, if it isn't available already
798 if ( !in_array( $userWatchlistOption, $days ) && $userWatchlistOption !== '0' ) {
799 $days[] = $userWatchlistOption;
800 }
801
802 $maxDays = (string)$this->maxDays;
803 // add the maximum possible value, if it isn't available already
804 if ( !in_array( $maxDays, $days ) ) {
805 $days[] = $maxDays;
806 }
807
808 $selected = (string)$options['days'];
809 if ( $selected <= 0 ) {
810 $selected = $maxDays;
811 }
812
813 // add the currently selected value, if it isn't available already
814 if ( !in_array( $selected, $days ) ) {
815 $days[] = $selected;
816 }
817
818 $select = new XmlSelect( 'days', 'days', $selected );
819
820 asort( $days );
821 foreach ( $days as $value ) {
822 if ( $value < 1 ) {
823 $name = $this->msg( 'hours' )->numParams( $value * 24 )->text();
824 } else {
825 $name = $this->msg( 'days' )->numParams( $value )->text();
826 }
827 $select->addOption( $name, $value );
828 }
829
830 return $select->getHTML() . "\n<br />\n";
831 }
832
833 function setTopText( FormOptions $opts ) {
834 $nondefaults = $opts->getChangedValues();
835 $form = '';
836 $user = $this->getUser();
837
838 $numItems = $this->countItems();
839 $showUpdatedMarker = $this->getConfig()->get( 'ShowUpdatedMarker' );
840
841 // Show watchlist header
842 $watchlistHeader = '';
843 if ( $numItems == 0 ) {
844 $watchlistHeader = $this->msg( 'nowatchlist' )->parse();
845 } else {
846 $watchlistHeader .= $this->msg( 'watchlist-details' )->numParams( $numItems )->parse() . "\n";
847 if ( $this->getConfig()->get( 'EnotifWatchlist' )
848 && $user->getOption( 'enotifwatchlistpages' )
849 ) {
850 $watchlistHeader .= $this->msg( 'wlheader-enotif' )->parse() . "\n";
851 }
852 if ( $showUpdatedMarker ) {
853 $watchlistHeader .= $this->msg(
854 $this->isStructuredFilterUiEnabled() ?
855 'rcfilters-watchlist-showupdated' :
856 'wlheader-showupdated'
857 )->parse() . "\n";
858 }
859 }
860 $form .= Html::rawElement(
861 'div',
862 [ 'class' => 'watchlistDetails' ],
863 $watchlistHeader
864 );
865
866 if ( $numItems > 0 && $showUpdatedMarker ) {
867 $form .= Xml::openElement( 'form', [ 'method' => 'post',
868 'action' => $this->getPageTitle()->getLocalURL(),
869 'id' => 'mw-watchlist-resetbutton' ] ) . "\n" .
870 Xml::submitButton( $this->msg( 'enotif_reset' )->text(),
871 [ 'name' => 'mw-watchlist-reset-submit' ] ) . "\n" .
872 Html::hidden( 'token', $user->getEditToken() ) . "\n" .
873 Html::hidden( 'reset', 'all' ) . "\n";
874 foreach ( $nondefaults as $key => $value ) {
875 $form .= Html::hidden( $key, $value ) . "\n";
876 }
877 $form .= Xml::closeElement( 'form' ) . "\n";
878 }
879
880 $this->getOutput()->addHTML( $form );
881 }
882
883 protected function showHideCheck( $options, $message, $name, $value, $inStructuredUi ) {
884 $options[$name] = 1 - (int)$value;
885
886 $attribs = [ 'class' => 'mw-input-with-label clshowhideoption cloption' ];
887 if ( $inStructuredUi ) {
888 $attribs[ 'data-feature-in-structured-ui' ] = true;
889 }
890
891 return Html::rawElement(
892 'span',
893 $attribs,
894 Xml::checkLabel(
895 $this->msg( $message, '' )->text(),
896 $name,
897 $name,
898 (int)$value
899 )
900 );
901 }
902
903 /**
904 * Count the number of paired items on a user's watchlist.
905 * The assumption made here is that when a subject page is watched a talk page is also watched.
906 * Hence the number of individual items is halved.
907 *
908 * @return int
909 */
910 protected function countItems() {
911 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
912 $count = $store->countWatchedItems( $this->getUser() );
913 return floor( $count / 2 );
914 }
915
916 function getDefaultLimit() {
917 return $this->getUser()->getIntOption( 'wllimit' );
918 }
919
920 function getDefaultDays() {
921 return $this->getUser()->getIntOption( 'watchlistdays' );
922 }
923 }