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