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