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