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