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