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