Introduce ContentHandler::getSecondaryDataUpdates.
[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\IResultWrapper;
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 protected static $collapsedPreferenceName = 'rcfilters-wl-collapsed';
39
40 private $maxDays;
41
42 public function __construct( $page = 'Watchlist', $restriction = 'viewmywatchlist' ) {
43 parent::__construct( $page, $restriction );
44
45 $this->maxDays = $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 );
46 }
47
48 public function doesWrites() {
49 return true;
50 }
51
52 /**
53 * Main execution point
54 *
55 * @param string $subpage
56 */
57 function execute( $subpage ) {
58 // Anons don't get a watchlist
59 $this->requireLogin( 'watchlistanontext' );
60
61 $output = $this->getOutput();
62 $request = $this->getRequest();
63 $this->addHelpLink( 'Help:Watching pages' );
64 $output->addModuleStyles( [ 'mediawiki.special' ] );
65 $output->addModules( [
66 'mediawiki.special.watchlist',
67 ] );
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 if ( !$config->get( 'StructuredChangeFiltersOnWatchlist' ) ) {
115 return false;
116 }
117
118 if ( $config->get( 'StructuredChangeFiltersShowWatchlistPreference' ) ) {
119 return !$user->getOption( 'wlenhancedfilters-disable' );
120 } else {
121 return $user->getOption( 'rcenhancedfilters' );
122 }
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 if ( $user->getBoolOption( 'watchlisthidepatrolled' ) ) {
273 $reviewStatus->setDefault( 'unpatrolled' );
274 $legacyReviewStatus = $this->getFilterGroup( 'legacyReviewStatus' );
275 $legacyHidePatrolled = $legacyReviewStatus->getFilter( 'hidepatrolled' );
276 $legacyHidePatrolled->setDefault( true );
277 }
278 }
279
280 $authorship = $this->getFilterGroup( 'authorship' );
281 $hideMyself = $authorship->getFilter( 'hidemyself' );
282 $hideMyself->setDefault( $user->getBoolOption( 'watchlisthideown' ) );
283
284 $changeType = $this->getFilterGroup( 'changeType' );
285 $hideCategorization = $changeType->getFilter( 'hidecategorization' );
286 if ( $hideCategorization !== null ) {
287 // Conditional on feature being available
288 $hideCategorization->setDefault( $user->getBoolOption( 'watchlisthidecategorization' ) );
289 }
290 }
291
292 /**
293 * Get all custom filters
294 *
295 * @return array Map of filter URL param names to properties (msg/default)
296 */
297 protected function getCustomFilters() {
298 if ( $this->customFilters === null ) {
299 $this->customFilters = parent::getCustomFilters();
300 Hooks::run( 'SpecialWatchlistFilters', [ $this, &$this->customFilters ], '1.23' );
301 }
302
303 return $this->customFilters;
304 }
305
306 /**
307 * Fetch values for a FormOptions object from the WebRequest associated with this instance.
308 *
309 * Maps old pre-1.23 request parameters Watchlist used to use (different from Recentchanges' ones)
310 * to the current ones.
311 *
312 * @param FormOptions $opts
313 * @return FormOptions
314 */
315 protected function fetchOptionsFromRequest( $opts ) {
316 static $compatibilityMap = [
317 'hideMinor' => 'hideminor',
318 'hideBots' => 'hidebots',
319 'hideAnons' => 'hideanons',
320 'hideLiu' => 'hideliu',
321 'hidePatrolled' => 'hidepatrolled',
322 'hideOwn' => 'hidemyself',
323 ];
324
325 $params = $this->getRequest()->getValues();
326 foreach ( $compatibilityMap as $from => $to ) {
327 if ( isset( $params[$from] ) ) {
328 $params[$to] = $params[$from];
329 unset( $params[$from] );
330 }
331 }
332
333 if ( $this->getRequest()->getVal( 'action' ) == 'submit' ) {
334 $allBooleansFalse = [];
335
336 // If the user submitted the form, start with a baseline of "all
337 // booleans are false", then change the ones they checked. This
338 // means we ignore the defaults.
339
340 // This is how we handle the fact that HTML forms don't submit
341 // unchecked boxes.
342 foreach ( $this->getLegacyShowHideFilters() as $filter ) {
343 $allBooleansFalse[ $filter->getName() ] = false;
344 }
345
346 $params = $params + $allBooleansFalse;
347 }
348
349 // Not the prettiest way to achieve this… FormOptions internally depends on data sanitization
350 // methods defined on WebRequest and removing this dependency would cause some code duplication.
351 $request = new DerivativeRequest( $this->getRequest(), $params );
352 $opts->fetchValuesFromRequest( $request );
353
354 return $opts;
355 }
356
357 /**
358 * @inheritDoc
359 */
360 protected function doMainQuery( $tables, $fields, $conds, $query_options,
361 $join_conds, FormOptions $opts
362 ) {
363 $dbr = $this->getDB();
364 $user = $this->getUser();
365
366 $rcQuery = RecentChange::getQueryInfo();
367 $tables = array_merge( $tables, $rcQuery['tables'], [ 'watchlist' ] );
368 $fields = array_merge( $rcQuery['fields'], $fields );
369
370 $join_conds = array_merge(
371 [
372 'watchlist' => [
373 'INNER JOIN',
374 [
375 'wl_user' => $user->getId(),
376 'wl_namespace=rc_namespace',
377 'wl_title=rc_title'
378 ],
379 ],
380 ],
381 $rcQuery['joins'],
382 $join_conds
383 );
384
385 $tables[] = 'page';
386 $fields[] = 'page_latest';
387 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
388
389 $fields[] = 'wl_notificationtimestamp';
390
391 // Log entries with DELETED_ACTION must not show up unless the user has
392 // the necessary rights.
393 if ( !$user->isAllowed( 'deletedhistory' ) ) {
394 $bitmask = LogPage::DELETED_ACTION;
395 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
396 $bitmask = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
397 } else {
398 $bitmask = 0;
399 }
400 if ( $bitmask ) {
401 $conds[] = $dbr->makeList( [
402 'rc_type != ' . RC_LOG,
403 $dbr->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
404 ], LIST_OR );
405 }
406
407 $tagFilter = $opts['tagfilter'] ? explode( '|', $opts['tagfilter'] ) : [];
408 ChangeTags::modifyDisplayQuery(
409 $tables,
410 $fields,
411 $conds,
412 $join_conds,
413 $query_options,
414 $tagFilter
415 );
416
417 $this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts );
418
419 if ( $this->areFiltersInConflict() ) {
420 return false;
421 }
422
423 $orderByAndLimit = [
424 'ORDER BY' => 'rc_timestamp DESC',
425 'LIMIT' => $opts['limit']
426 ];
427 if ( in_array( 'DISTINCT', $query_options ) ) {
428 // ChangeTags::modifyDisplayQuery() adds DISTINCT when filtering on multiple tags.
429 // In order to prevent DISTINCT from causing query performance problems,
430 // we have to GROUP BY the primary key. This in turn requires us to add
431 // the primary key to the end of the ORDER BY, and the old ORDER BY to the
432 // start of the GROUP BY
433 $orderByAndLimit['ORDER BY'] = 'rc_timestamp DESC, rc_id DESC';
434 $orderByAndLimit['GROUP BY'] = 'rc_timestamp, rc_id';
435 }
436 // array_merge() is used intentionally here so that hooks can, should
437 // they so desire, override the ORDER BY / LIMIT condition(s)
438 $query_options = array_merge( $orderByAndLimit, $query_options );
439
440 return $dbr->select(
441 $tables,
442 $fields,
443 $conds,
444 __METHOD__,
445 $query_options,
446 $join_conds
447 );
448 }
449
450 protected function runMainQueryHook( &$tables, &$fields, &$conds, &$query_options,
451 &$join_conds, $opts
452 ) {
453 return parent::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
454 && Hooks::run(
455 'SpecialWatchlistQuery',
456 [ &$conds, &$tables, &$join_conds, &$fields, $opts ],
457 '1.23'
458 );
459 }
460
461 /**
462 * Return a IDatabase object for reading
463 *
464 * @return IDatabase
465 */
466 protected function getDB() {
467 return wfGetDB( DB_REPLICA, 'watchlist' );
468 }
469
470 /**
471 * Output feed links.
472 */
473 public function outputFeedLinks() {
474 $user = $this->getUser();
475 $wlToken = $user->getTokenFromOption( 'watchlisttoken' );
476 if ( $wlToken ) {
477 $this->addFeedLinks( [
478 'action' => 'feedwatchlist',
479 'allrev' => 1,
480 'wlowner' => $user->getName(),
481 'wltoken' => $wlToken,
482 ] );
483 }
484 }
485
486 /**
487 * Build and output the actual changes list.
488 *
489 * @param IResultWrapper $rows Database rows
490 * @param FormOptions $opts
491 */
492 public function outputChangesList( $rows, $opts ) {
493 $dbr = $this->getDB();
494 $user = $this->getUser();
495 $output = $this->getOutput();
496 $services = MediaWikiServices::getInstance();
497
498 # Show a message about replica DB lag, if applicable
499 $lag = $services->getDBLoadBalancer()->safeGetLag( $dbr );
500 if ( $lag > 0 ) {
501 $output->showLagWarning( $lag );
502 }
503
504 # If no rows to display, show message before try to render the list
505 if ( $rows->numRows() == 0 ) {
506 $output->wrapWikiMsg(
507 "<div class='mw-changeslist-empty'>\n$1\n</div>", 'recentchanges-noresult'
508 );
509 return;
510 }
511
512 $dbr->dataSeek( $rows, 0 );
513
514 $list = ChangesList::newFromContext( $this->getContext(), $this->filterGroups );
515 $list->setWatchlistDivs();
516 $list->initChangesListRows( $rows );
517 if ( $user->getOption( 'watchlistunwatchlinks' ) ) {
518 $list->setChangeLinePrefixer( function ( RecentChange $rc, ChangesList $cl, $grouped ) {
519 // Don't show unwatch link if the line is a grouped log entry using EnhancedChangesList,
520 // since EnhancedChangesList groups log entries by performer rather than by target article
521 if ( $rc->mAttribs['rc_type'] == RC_LOG && $cl instanceof EnhancedChangesList &&
522 $grouped ) {
523 return '';
524 } else {
525 return $this->getLinkRenderer()
526 ->makeKnownLink( $rc->getTitle(),
527 $this->msg( 'watchlist-unwatch' )->text(), [
528 'class' => 'mw-unwatch-link',
529 'title' => $this->msg( 'tooltip-ca-unwatch' )->text()
530 ], [ 'action' => 'unwatch' ] ) . "\u{00A0}";
531 }
532 } );
533 }
534 $dbr->dataSeek( $rows, 0 );
535
536 if ( $this->getConfig()->get( 'RCShowWatchingUsers' )
537 && $user->getOption( 'shownumberswatching' )
538 ) {
539 $watchedItemStore = $services->getWatchedItemStore();
540 }
541
542 $s = $list->beginRecentChangesList();
543
544 if ( $this->isStructuredFilterUiEnabled() ) {
545 $s .= $this->makeLegend();
546 }
547
548 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
549 $counter = 1;
550 foreach ( $rows as $obj ) {
551 # Make RC entry
552 $rc = RecentChange::newFromRow( $obj );
553
554 # Skip CatWatch entries for hidden cats based on user preference
555 if (
556 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE &&
557 !$userShowHiddenCats &&
558 $rc->getParam( 'hidden-cat' )
559 ) {
560 continue;
561 }
562
563 $rc->counter = $counter++;
564
565 if ( $this->getConfig()->get( 'ShowUpdatedMarker' ) ) {
566 $updated = $obj->wl_notificationtimestamp;
567 } else {
568 $updated = false;
569 }
570
571 if ( isset( $watchedItemStore ) ) {
572 $rcTitleValue = new TitleValue( (int)$obj->rc_namespace, $obj->rc_title );
573 $rc->numberofWatchingusers = $watchedItemStore->countWatchers( $rcTitleValue );
574 } else {
575 $rc->numberofWatchingusers = 0;
576 }
577
578 $changeLine = $list->recentChangesLine( $rc, $updated, $counter );
579 if ( $changeLine !== false ) {
580 $s .= $changeLine;
581 }
582 }
583 $s .= $list->endRecentChangesList();
584
585 $output->addHTML( $s );
586 }
587
588 /**
589 * Set the text to be displayed above the changes
590 *
591 * @param FormOptions $opts
592 * @param int $numRows Number of rows in the result to show after this header
593 */
594 public function doHeader( $opts, $numRows ) {
595 $user = $this->getUser();
596 $out = $this->getOutput();
597
598 $out->addSubtitle(
599 $this->msg( 'watchlistfor2', $user->getName() )
600 ->rawParams( SpecialEditWatchlist::buildTools(
601 $this->getLanguage(),
602 $this->getLinkRenderer()
603 ) )
604 );
605
606 $this->setTopText( $opts );
607
608 $form = '';
609
610 $form .= Xml::openElement( 'form', [
611 'method' => 'get',
612 'action' => wfScript(),
613 'id' => 'mw-watchlist-form'
614 ] );
615 $form .= Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
616 $form .= Xml::openElement(
617 'fieldset',
618 [ 'id' => 'mw-watchlist-options', 'class' => 'cloptions' ]
619 );
620 $form .= Xml::element(
621 'legend', null, $this->msg( 'watchlist-options' )->text()
622 );
623
624 if ( !$this->isStructuredFilterUiEnabled() ) {
625 $form .= $this->makeLegend();
626 }
627
628 $lang = $this->getLanguage();
629 $timestamp = wfTimestampNow();
630 $wlInfo = Html::rawElement(
631 'span',
632 [
633 'class' => 'wlinfo',
634 'data-params' => json_encode( [ 'from' => $timestamp ] ),
635 ],
636 $this->msg( 'wlnote' )->numParams( $numRows, round( $opts['days'] * 24 ) )->params(
637 $lang->userDate( $timestamp, $user ), $lang->userTime( $timestamp, $user )
638 )->parse()
639 ) . "<br />\n";
640
641 $nondefaults = $opts->getChangedValues();
642 $cutofflinks = Html::rawElement(
643 'span',
644 [ 'class' => 'cldays cloption' ],
645 $this->msg( 'wlshowtime' ) . ' ' . $this->cutoffselector( $opts )
646 );
647
648 # Spit out some control panel links
649 $links = [];
650 $namesOfDisplayedFilters = [];
651 foreach ( $this->getLegacyShowHideFilters() as $filterName => $filter ) {
652 $namesOfDisplayedFilters[] = $filterName;
653 $links[] = $this->showHideCheck(
654 $nondefaults,
655 $filter->getShowHide(),
656 $filterName,
657 $opts[ $filterName ],
658 $filter->isFeatureAvailableOnStructuredUi( $this )
659 );
660 }
661
662 $hiddenFields = $nondefaults;
663 $hiddenFields['action'] = 'submit';
664 unset( $hiddenFields['namespace'] );
665 unset( $hiddenFields['invert'] );
666 unset( $hiddenFields['associated'] );
667 unset( $hiddenFields['days'] );
668 foreach ( $namesOfDisplayedFilters as $filterName ) {
669 unset( $hiddenFields[$filterName] );
670 }
671
672 # Namespace filter and put the whole form together.
673 $form .= $wlInfo;
674 $form .= $cutofflinks;
675 $form .= Html::rawElement(
676 'span',
677 [ 'class' => 'clshowhide' ],
678 $this->msg( 'watchlist-hide' ) .
679 $this->msg( 'colon-separator' )->escaped() .
680 implode( ' ', $links )
681 );
682 $form .= "\n<br />\n";
683
684 $namespaceForm = Html::namespaceSelector(
685 [
686 'selected' => $opts['namespace'],
687 'all' => '',
688 'label' => $this->msg( 'namespace' )->text()
689 ], [
690 'name' => 'namespace',
691 'id' => 'namespace',
692 'class' => 'namespaceselector',
693 ]
694 ) . "\n";
695 $namespaceForm .= '<span class="mw-input-with-label">' . Xml::checkLabel(
696 $this->msg( 'invert' )->text(),
697 'invert',
698 'nsinvert',
699 $opts['invert'],
700 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
701 ) . "</span>\n";
702 $namespaceForm .= '<span class="mw-input-with-label">' . Xml::checkLabel(
703 $this->msg( 'namespace_association' )->text(),
704 'associated',
705 'nsassociated',
706 $opts['associated'],
707 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
708 ) . "</span>\n";
709 $form .= Html::rawElement(
710 'span',
711 [ 'class' => 'namespaceForm cloption' ],
712 $namespaceForm
713 );
714
715 $form .= Xml::submitButton(
716 $this->msg( 'watchlist-submit' )->text(),
717 [ 'class' => 'cloption-submit' ]
718 ) . "\n";
719 foreach ( $hiddenFields as $key => $value ) {
720 $form .= Html::hidden( $key, $value ) . "\n";
721 }
722 $form .= Xml::closeElement( 'fieldset' ) . "\n";
723 $form .= Xml::closeElement( 'form' ) . "\n";
724
725 // Insert a placeholder for RCFilters
726 if ( $this->isStructuredFilterUiEnabled() ) {
727 $rcfilterContainer = Html::element(
728 'div',
729 [ 'class' => 'rcfilters-container' ]
730 );
731
732 $loadingContainer = Html::rawElement(
733 'div',
734 [ 'class' => 'rcfilters-spinner' ],
735 Html::element(
736 'div',
737 [ 'class' => 'rcfilters-spinner-bounce' ]
738 )
739 );
740
741 // Wrap both with rcfilters-head
742 $this->getOutput()->addHTML(
743 Html::rawElement(
744 'div',
745 [ 'class' => 'rcfilters-head' ],
746 $rcfilterContainer . $form
747 )
748 );
749
750 // Add spinner
751 $this->getOutput()->addHTML( $loadingContainer );
752 } else {
753 $this->getOutput()->addHTML( $form );
754 }
755
756 $this->setBottomText( $opts );
757 }
758
759 function cutoffselector( $options ) {
760 $selected = (float)$options['days'];
761 if ( $selected <= 0 ) {
762 $selected = $this->maxDays;
763 }
764
765 $selectedHours = round( $selected * 24 );
766
767 $hours = array_unique( array_filter( [
768 1,
769 2,
770 6,
771 12,
772 24,
773 72,
774 168,
775 24 * (float)$this->getUser()->getOption( 'watchlistdays', 0 ),
776 24 * $this->maxDays,
777 $selectedHours
778 ] ) );
779 asort( $hours );
780
781 $select = new XmlSelect( 'days', 'days', (float)( $selectedHours / 24 ) );
782
783 foreach ( $hours as $value ) {
784 if ( $value < 24 ) {
785 $name = $this->msg( 'hours' )->numParams( $value )->text();
786 } else {
787 $name = $this->msg( 'days' )->numParams( $value / 24 )->text();
788 }
789 $select->addOption( $name, (float)( $value / 24 ) );
790 }
791
792 return $select->getHTML() . "\n<br />\n";
793 }
794
795 function setTopText( FormOptions $opts ) {
796 $nondefaults = $opts->getChangedValues();
797 $form = '';
798 $user = $this->getUser();
799
800 $numItems = $this->countItems();
801 $showUpdatedMarker = $this->getConfig()->get( 'ShowUpdatedMarker' );
802
803 // Show watchlist header
804 $watchlistHeader = '';
805 if ( $numItems == 0 ) {
806 $watchlistHeader = $this->msg( 'nowatchlist' )->parse();
807 } else {
808 $watchlistHeader .= $this->msg( 'watchlist-details' )->numParams( $numItems )->parse() . "\n";
809 if ( $this->getConfig()->get( 'EnotifWatchlist' )
810 && $user->getOption( 'enotifwatchlistpages' )
811 ) {
812 $watchlistHeader .= $this->msg( 'wlheader-enotif' )->parse() . "\n";
813 }
814 if ( $showUpdatedMarker ) {
815 $watchlistHeader .= $this->msg(
816 $this->isStructuredFilterUiEnabled() ?
817 'rcfilters-watchlist-showupdated' :
818 'wlheader-showupdated'
819 )->parse() . "\n";
820 }
821 }
822 $form .= Html::rawElement(
823 'div',
824 [ 'class' => 'watchlistDetails' ],
825 $watchlistHeader
826 );
827
828 if ( $numItems > 0 && $showUpdatedMarker ) {
829 $form .= Xml::openElement( 'form', [ 'method' => 'post',
830 'action' => $this->getPageTitle()->getLocalURL(),
831 'id' => 'mw-watchlist-resetbutton' ] ) . "\n" .
832 Xml::submitButton( $this->msg( 'enotif_reset' )->text(),
833 [ 'name' => 'mw-watchlist-reset-submit' ] ) . "\n" .
834 Html::hidden( 'token', $user->getEditToken() ) . "\n" .
835 Html::hidden( 'reset', 'all' ) . "\n";
836 foreach ( $nondefaults as $key => $value ) {
837 $form .= Html::hidden( $key, $value ) . "\n";
838 }
839 $form .= Xml::closeElement( 'form' ) . "\n";
840 }
841
842 $this->getOutput()->addHTML( $form );
843 }
844
845 protected function showHideCheck( $options, $message, $name, $value, $inStructuredUi ) {
846 $options[$name] = 1 - (int)$value;
847
848 $attribs = [ 'class' => 'mw-input-with-label clshowhideoption cloption' ];
849 if ( $inStructuredUi ) {
850 $attribs[ 'data-feature-in-structured-ui' ] = true;
851 }
852
853 return Html::rawElement(
854 'span',
855 $attribs,
856 // not using Html::checkLabel because that would escape the contents
857 Html::check( $name, (int)$value, [ 'id' => $name ] ) . Html::rawElement(
858 'label',
859 $attribs + [ 'for' => $name ],
860 // <nowiki/> at beginning to avoid messages with "$1 ..." being parsed as pre tags
861 $this->msg( $message, '<nowiki/>' )->parse()
862 )
863 );
864 }
865
866 /**
867 * Count the number of paired items on a user's watchlist.
868 * The assumption made here is that when a subject page is watched a talk page is also watched.
869 * Hence the number of individual items is halved.
870 *
871 * @return int
872 */
873 protected function countItems() {
874 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
875 $count = $store->countWatchedItems( $this->getUser() );
876 return floor( $count / 2 );
877 }
878 }