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