Merge "Remove implicitGroupby() use in ImageListPager"
[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::openElement(
639 'fieldset',
640 [ 'id' => 'mw-watchlist-options', 'class' => 'cloptions' ]
641 );
642 $form .= Xml::element(
643 'legend', null, $this->msg( 'watchlist-options' )->text()
644 );
645
646 if ( !$this->isStructuredFilterUiEnabled() ) {
647 $form .= $this->makeLegend();
648 }
649
650 $lang = $this->getLanguage();
651 if ( $opts['days'] > 0 ) {
652 $days = $opts['days'];
653 } else {
654 $days = $this->maxDays;
655 }
656 $timestamp = wfTimestampNow();
657 $wlInfo = Html::rawElement(
658 'span',
659 [ 'class' => 'wlinfo' ],
660 $this->msg( 'wlnote' )->numParams( $numRows, round( $days * 24 ) )->params(
661 $lang->userDate( $timestamp, $user ), $lang->userTime( $timestamp, $user )
662 )->parse()
663 ) . "<br />\n";
664
665 $nondefaults = $opts->getChangedValues();
666 $cutofflinks = Html::rawElement(
667 'span',
668 [ 'class' => 'cldays cloption' ],
669 $this->msg( 'wlshowtime' ) . ' ' . $this->cutoffselector( $opts )
670 );
671
672 # Spit out some control panel links
673 $links = [];
674 $namesOfDisplayedFilters = [];
675 foreach ( $this->getFilterGroups() as $groupName => $group ) {
676 if ( !$group->isPerGroupRequestParameter() ) {
677 foreach ( $group->getFilters() as $filterName => $filter ) {
678 if ( $filter->displaysOnUnstructuredUi( $this ) ) {
679 $namesOfDisplayedFilters[] = $filterName;
680 $links[] = $this->showHideCheck(
681 $nondefaults,
682 $filter->getShowHide(),
683 $filterName,
684 $opts[$filterName],
685 $filter->isFeatureAvailableOnStructuredUi( $this )
686 );
687 }
688 }
689 }
690 }
691
692 $hiddenFields = $nondefaults;
693 $hiddenFields['action'] = 'submit';
694 unset( $hiddenFields['namespace'] );
695 unset( $hiddenFields['invert'] );
696 unset( $hiddenFields['associated'] );
697 unset( $hiddenFields['days'] );
698 foreach ( $namesOfDisplayedFilters as $filterName ) {
699 unset( $hiddenFields[$filterName] );
700 }
701
702 # Namespace filter and put the whole form together.
703 $form .= $wlInfo;
704 $form .= $cutofflinks;
705 $form .= Html::rawElement(
706 'span',
707 [ 'class' => 'clshowhide' ],
708 $this->msg( 'watchlist-hide' ) .
709 $this->msg( 'colon-separator' )->escaped() .
710 implode( ' ', $links )
711 );
712 $form .= "\n<br />\n";
713
714 $namespaceForm = Html::namespaceSelector(
715 [
716 'selected' => $opts['namespace'],
717 'all' => '',
718 'label' => $this->msg( 'namespace' )->text()
719 ], [
720 'name' => 'namespace',
721 'id' => 'namespace',
722 'class' => 'namespaceselector',
723 ]
724 ) . "\n";
725 $namespaceForm .= '<span class="mw-input-with-label">' . Xml::checkLabel(
726 $this->msg( 'invert' )->text(),
727 'invert',
728 'nsinvert',
729 $opts['invert'],
730 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
731 ) . "</span>\n";
732 $namespaceForm .= '<span class="mw-input-with-label">' . Xml::checkLabel(
733 $this->msg( 'namespace_association' )->text(),
734 'associated',
735 'nsassociated',
736 $opts['associated'],
737 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
738 ) . "</span>\n";
739 $form .= Html::rawElement(
740 'span',
741 [ 'class' => 'namespaceForm cloption' ],
742 $namespaceForm
743 );
744
745 $form .= Xml::submitButton(
746 $this->msg( 'watchlist-submit' )->text(),
747 [ 'class' => 'cloption-submit' ]
748 ) . "\n";
749 foreach ( $hiddenFields as $key => $value ) {
750 $form .= Html::hidden( $key, $value ) . "\n";
751 }
752 $form .= Xml::closeElement( 'fieldset' ) . "\n";
753 $form .= Xml::closeElement( 'form' ) . "\n";
754
755 // Insert a placeholder for RCFilters
756 if ( $this->isStructuredFilterUiEnabled() ) {
757 $rcfilterContainer = Html::element(
758 'div',
759 [ 'class' => 'rcfilters-container' ]
760 );
761
762 $loadingContainer = Html::rawElement(
763 'div',
764 [ 'class' => 'rcfilters-spinner' ],
765 Html::element(
766 'div',
767 [ 'class' => 'rcfilters-spinner-bounce' ]
768 )
769 );
770
771 // Wrap both with rcfilters-head
772 $this->getOutput()->addHTML(
773 Html::rawElement(
774 'div',
775 [ 'class' => 'rcfilters-head' ],
776 $rcfilterContainer . $form
777 )
778 );
779
780 // Add spinner
781 $this->getOutput()->addHTML( $loadingContainer );
782 } else {
783 $this->getOutput()->addHTML( $form );
784 }
785
786 $this->setBottomText( $opts );
787 }
788
789 function cutoffselector( $options ) {
790 // Cast everything to strings immediately, so that we know all of the values have the same
791 // precision, and can be compared with '==='. 2/24 has a few more decimal places than its
792 // default string representation, for example, and would confuse comparisons.
793
794 // Misleadingly, the 'days' option supports hours too.
795 $days = array_map( 'strval', [ 1 / 24, 2 / 24, 6 / 24, 12 / 24, 1, 3, 7 ] );
796
797 $userWatchlistOption = (string)$this->getUser()->getOption( 'watchlistdays' );
798 // add the user preference, if it isn't available already
799 if ( !in_array( $userWatchlistOption, $days ) && $userWatchlistOption !== '0' ) {
800 $days[] = $userWatchlistOption;
801 }
802
803 $maxDays = (string)$this->maxDays;
804 // add the maximum possible value, if it isn't available already
805 if ( !in_array( $maxDays, $days ) ) {
806 $days[] = $maxDays;
807 }
808
809 $selected = (string)$options['days'];
810 if ( $selected <= 0 ) {
811 $selected = $maxDays;
812 }
813
814 // add the currently selected value, if it isn't available already
815 if ( !in_array( $selected, $days ) ) {
816 $days[] = $selected;
817 }
818
819 $select = new XmlSelect( 'days', 'days', $selected );
820
821 asort( $days );
822 foreach ( $days as $value ) {
823 if ( $value < 1 ) {
824 $name = $this->msg( 'hours' )->numParams( $value * 24 )->text();
825 } else {
826 $name = $this->msg( 'days' )->numParams( $value )->text();
827 }
828 $select->addOption( $name, $value );
829 }
830
831 return $select->getHTML() . "\n<br />\n";
832 }
833
834 function setTopText( FormOptions $opts ) {
835 $nondefaults = $opts->getChangedValues();
836 $form = '';
837 $user = $this->getUser();
838
839 $numItems = $this->countItems();
840 $showUpdatedMarker = $this->getConfig()->get( 'ShowUpdatedMarker' );
841
842 // Show watchlist header
843 $watchlistHeader = '';
844 if ( $numItems == 0 ) {
845 $watchlistHeader = $this->msg( 'nowatchlist' )->parse();
846 } else {
847 $watchlistHeader .= $this->msg( 'watchlist-details' )->numParams( $numItems )->parse() . "\n";
848 if ( $this->getConfig()->get( 'EnotifWatchlist' )
849 && $user->getOption( 'enotifwatchlistpages' )
850 ) {
851 $watchlistHeader .= $this->msg( 'wlheader-enotif' )->parse() . "\n";
852 }
853 if ( $showUpdatedMarker ) {
854 $watchlistHeader .= $this->msg(
855 $this->isStructuredFilterUiEnabled() ?
856 'rcfilters-watchlist-showupdated' :
857 'wlheader-showupdated'
858 )->parse() . "\n";
859 }
860 }
861 $form .= Html::rawElement(
862 'div',
863 [ 'class' => 'watchlistDetails' ],
864 $watchlistHeader
865 );
866
867 if ( $numItems > 0 && $showUpdatedMarker ) {
868 $form .= Xml::openElement( 'form', [ 'method' => 'post',
869 'action' => $this->getPageTitle()->getLocalURL(),
870 'id' => 'mw-watchlist-resetbutton' ] ) . "\n" .
871 Xml::submitButton( $this->msg( 'enotif_reset' )->text(),
872 [ 'name' => 'mw-watchlist-reset-submit' ] ) . "\n" .
873 Html::hidden( 'token', $user->getEditToken() ) . "\n" .
874 Html::hidden( 'reset', 'all' ) . "\n";
875 foreach ( $nondefaults as $key => $value ) {
876 $form .= Html::hidden( $key, $value ) . "\n";
877 }
878 $form .= Xml::closeElement( 'form' ) . "\n";
879 }
880
881 $this->getOutput()->addHTML( $form );
882 }
883
884 protected function showHideCheck( $options, $message, $name, $value, $inStructuredUi ) {
885 $options[$name] = 1 - (int)$value;
886
887 $attribs = [ 'class' => 'mw-input-with-label clshowhideoption cloption' ];
888 if ( $inStructuredUi ) {
889 $attribs[ 'data-feature-in-structured-ui' ] = true;
890 }
891
892 return Html::rawElement(
893 'span',
894 $attribs,
895 Xml::checkLabel(
896 $this->msg( $message, '' )->text(),
897 $name,
898 $name,
899 (int)$value
900 )
901 );
902 }
903
904 /**
905 * Count the number of paired items on a user's watchlist.
906 * The assumption made here is that when a subject page is watched a talk page is also watched.
907 * Hence the number of individual items is halved.
908 *
909 * @return int
910 */
911 protected function countItems() {
912 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
913 $count = $store->countWatchedItems( $this->getUser() );
914 return floor( $count / 2 );
915 }
916
917 function getDefaultLimit() {
918 return $this->getUser()->getIntOption( 'wllimit' );
919 }
920
921 function getDefaultDays() {
922 return floatval( $this->getUser()->getOption( 'watchlistdays' ) );
923 }
924 }