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