Merge "Make DBAccessBase use DBConnRef, rename $wiki, and hide getLoadBalancer()"
[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 /** @var float|int */
41 private $maxDays;
42 /** WatchedItemStore */
43 private $watchStore;
44
45 public function __construct( $page = 'Watchlist', $restriction = 'viewmywatchlist' ) {
46 parent::__construct( $page, $restriction );
47
48 $this->maxDays = $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 );
49 $this->watchStore = MediaWikiServices::getInstance()->getWatchedItemStore();
50 }
51
52 public function doesWrites() {
53 return true;
54 }
55
56 /**
57 * Main execution point
58 *
59 * @param string $subpage
60 */
61 function execute( $subpage ) {
62 // Anons don't get a watchlist
63 $this->requireLogin( 'watchlistanontext' );
64
65 $output = $this->getOutput();
66 $request = $this->getRequest();
67 $this->addHelpLink( 'Help:Watching pages' );
68 $output->addModuleStyles( [ 'mediawiki.special' ] );
69 $output->addModules( [
70 'mediawiki.special.recentchanges',
71 'mediawiki.special.watchlist',
72 ] );
73
74 $mode = SpecialEditWatchlist::getMode( $request, $subpage );
75 if ( $mode !== false ) {
76 if ( $mode === SpecialEditWatchlist::EDIT_RAW ) {
77 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'raw' );
78 } elseif ( $mode === SpecialEditWatchlist::EDIT_CLEAR ) {
79 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'clear' );
80 } else {
81 $title = SpecialPage::getTitleFor( 'EditWatchlist' );
82 }
83
84 $output->redirect( $title->getLocalURL() );
85
86 return;
87 }
88
89 $this->checkPermissions();
90
91 $user = $this->getUser();
92 $opts = $this->getOptions();
93
94 $config = $this->getConfig();
95 if ( ( $config->get( 'EnotifWatchlist' ) || $config->get( 'ShowUpdatedMarker' ) )
96 && $request->getVal( 'reset' )
97 && $request->wasPosted()
98 && $user->matchEditToken( $request->getVal( 'token' ) )
99 ) {
100 $user->clearAllNotifications();
101 $output->redirect( $this->getPageTitle()->getFullURL( $opts->getChangedValues() ) );
102
103 return;
104 }
105
106 parent::execute( $subpage );
107
108 if ( $this->isStructuredFilterUiEnabled() ) {
109 $output->addModuleStyles( [ 'mediawiki.rcfilters.highlightCircles.seenunseen.styles' ] );
110 }
111 }
112
113 /**
114 * @see ChangesListSpecialPage::checkStructuredFilterUiEnabled
115 */
116 public static function checkStructuredFilterUiEnabled( $user ) {
117 if ( $user instanceof Config ) {
118 wfDeprecated( __METHOD__ . ' with Config argument', '1.34' );
119 $user = func_get_arg( 1 );
120 }
121 return !$user->getOption( 'wlenhancedfilters-disable' );
122 }
123
124 /**
125 * Return an array of subpages that this special page will accept.
126 *
127 * @see also SpecialEditWatchlist::getSubpagesForPrefixSearch
128 * @return string[] subpages
129 */
130 public function getSubpagesForPrefixSearch() {
131 return [
132 'clear',
133 'edit',
134 'raw',
135 ];
136 }
137
138 /**
139 * @inheritDoc
140 */
141 protected function transformFilterDefinition( array $filterDefinition ) {
142 if ( isset( $filterDefinition['showHideSuffix'] ) ) {
143 $filterDefinition['showHide'] = 'wl' . $filterDefinition['showHideSuffix'];
144 }
145
146 return $filterDefinition;
147 }
148
149 /**
150 * @inheritDoc
151 * @suppress PhanUndeclaredMethod
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, RecentChange $rc ) {
203 return !$this->isChangeEffectivelySeen( $rc );
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, RecentChange $rc ) {
212 return $this->isChangeEffectivelySeen( $rc );
213 }
214 ],
215 ],
216 'default' => ChangesListStringOptionsFilterGroup::NONE,
217 'queryCallable' => function (
218 $specialPageClassName,
219 $context,
220 IDatabase $dbr,
221 &$tables,
222 &$fields,
223 &$conds,
224 &$query_options,
225 &$join_conds,
226 $selectedValues
227 ) {
228 if ( $selectedValues === [ 'seen' ] ) {
229 $conds[] = $dbr->makeList( [
230 'wl_notificationtimestamp IS NULL',
231 'rc_timestamp < wl_notificationtimestamp'
232 ], LIST_OR );
233 } elseif ( $selectedValues === [ 'unseen' ] ) {
234 $conds[] = $dbr->makeList( [
235 'wl_notificationtimestamp IS NOT NULL',
236 'rc_timestamp >= wl_notificationtimestamp'
237 ], LIST_AND );
238 }
239 }
240 ] ) );
241
242 $user = $this->getUser();
243
244 $significance = $this->getFilterGroup( 'significance' );
245 $hideMinor = $significance->getFilter( 'hideminor' );
246 $hideMinor->setDefault( $user->getBoolOption( 'watchlisthideminor' ) );
247
248 $automated = $this->getFilterGroup( 'automated' );
249 $hideBots = $automated->getFilter( 'hidebots' );
250 $hideBots->setDefault( $user->getBoolOption( 'watchlisthidebots' ) );
251
252 $registration = $this->getFilterGroup( 'registration' );
253 $hideAnons = $registration->getFilter( 'hideanons' );
254 $hideAnons->setDefault( $user->getBoolOption( 'watchlisthideanons' ) );
255 $hideLiu = $registration->getFilter( 'hideliu' );
256 $hideLiu->setDefault( $user->getBoolOption( 'watchlisthideliu' ) );
257
258 // Selecting both hideanons and hideliu on watchlist preferances
259 // gives mutually exclusive filters, so those are ignored
260 if ( $user->getBoolOption( 'watchlisthideanons' ) &&
261 !$user->getBoolOption( 'watchlisthideliu' )
262 ) {
263 $this->getFilterGroup( 'userExpLevel' )
264 ->setDefault( 'registered' );
265 }
266
267 if ( $user->getBoolOption( 'watchlisthideliu' ) &&
268 !$user->getBoolOption( 'watchlisthideanons' )
269 ) {
270 $this->getFilterGroup( 'userExpLevel' )
271 ->setDefault( 'unregistered' );
272 }
273
274 $reviewStatus = $this->getFilterGroup( 'reviewStatus' );
275 if ( $reviewStatus !== null ) {
276 // Conditional on feature being available and rights
277 if ( $user->getBoolOption( 'watchlisthidepatrolled' ) ) {
278 $reviewStatus->setDefault( 'unpatrolled' );
279 $legacyReviewStatus = $this->getFilterGroup( 'legacyReviewStatus' );
280 $legacyHidePatrolled = $legacyReviewStatus->getFilter( 'hidepatrolled' );
281 $legacyHidePatrolled->setDefault( true );
282 }
283 }
284
285 $authorship = $this->getFilterGroup( 'authorship' );
286 $hideMyself = $authorship->getFilter( 'hidemyself' );
287 $hideMyself->setDefault( $user->getBoolOption( 'watchlisthideown' ) );
288
289 $changeType = $this->getFilterGroup( 'changeType' );
290 $hideCategorization = $changeType->getFilter( 'hidecategorization' );
291 if ( $hideCategorization !== null ) {
292 // Conditional on feature being available
293 $hideCategorization->setDefault( $user->getBoolOption( 'watchlisthidecategorization' ) );
294 }
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 '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 ( !MediaWikiServices::getInstance()
387 ->getPermissionManager()
388 ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
389 ) {
390 $bitmask = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
391 } else {
392 $bitmask = 0;
393 }
394 if ( $bitmask ) {
395 $conds[] = $dbr->makeList( [
396 'rc_type != ' . RC_LOG,
397 $dbr->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
398 ], LIST_OR );
399 }
400
401 $tagFilter = $opts['tagfilter'] ? explode( '|', $opts['tagfilter'] ) : [];
402 ChangeTags::modifyDisplayQuery(
403 $tables,
404 $fields,
405 $conds,
406 $join_conds,
407 $query_options,
408 $tagFilter
409 );
410
411 $this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts );
412
413 if ( $this->areFiltersInConflict() ) {
414 return false;
415 }
416
417 $orderByAndLimit = [
418 'ORDER BY' => 'rc_timestamp DESC',
419 'LIMIT' => $opts['limit']
420 ];
421 if ( in_array( 'DISTINCT', $query_options ) ) {
422 // ChangeTags::modifyDisplayQuery() adds DISTINCT when filtering on multiple tags.
423 // In order to prevent DISTINCT from causing query performance problems,
424 // we have to GROUP BY the primary key. This in turn requires us to add
425 // the primary key to the end of the ORDER BY, and the old ORDER BY to the
426 // start of the GROUP BY
427 $orderByAndLimit['ORDER BY'] = 'rc_timestamp DESC, rc_id DESC';
428 $orderByAndLimit['GROUP BY'] = 'rc_timestamp, rc_id';
429 }
430 // array_merge() is used intentionally here so that hooks can, should
431 // they so desire, override the ORDER BY / LIMIT condition(s)
432 $query_options = array_merge( $orderByAndLimit, $query_options );
433
434 return $dbr->select(
435 $tables,
436 $fields,
437 $conds,
438 __METHOD__,
439 $query_options,
440 $join_conds
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 IResultWrapper $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 $services = MediaWikiServices::getInstance();
480
481 # Show a message about replica DB lag, if applicable
482 $lag = $dbr->getSessionLagStatus()['lag'];
483 if ( $lag > 0 ) {
484 $output->showLagWarning( $lag );
485 }
486
487 # If no rows to display, show message before try to render the list
488 if ( $rows->numRows() == 0 ) {
489 $output->wrapWikiMsg(
490 "<div class='mw-changeslist-empty'>\n$1\n</div>", 'recentchanges-noresult'
491 );
492 return;
493 }
494
495 $dbr->dataSeek( $rows, 0 );
496
497 $list = ChangesList::newFromContext( $this->getContext(), $this->filterGroups );
498 $list->setWatchlistDivs();
499 $list->initChangesListRows( $rows );
500 if ( $user->getOption( 'watchlistunwatchlinks' ) ) {
501 $list->setChangeLinePrefixer( function ( RecentChange $rc, ChangesList $cl, $grouped ) {
502 // Don't show unwatch link if the line is a grouped log entry using EnhancedChangesList,
503 // since EnhancedChangesList groups log entries by performer rather than by target article
504 if ( $rc->mAttribs['rc_type'] == RC_LOG && $cl instanceof EnhancedChangesList &&
505 $grouped ) {
506 return '';
507 } else {
508 return $this->getLinkRenderer()
509 ->makeKnownLink( $rc->getTitle(),
510 $this->msg( 'watchlist-unwatch' )->text(), [
511 'class' => 'mw-unwatch-link',
512 'title' => $this->msg( 'tooltip-ca-unwatch' )->text()
513 ], [ 'action' => 'unwatch' ] ) . "\u{00A0}";
514 }
515 } );
516 }
517 $dbr->dataSeek( $rows, 0 );
518
519 if ( $this->getConfig()->get( 'RCShowWatchingUsers' )
520 && $user->getOption( 'shownumberswatching' )
521 ) {
522 $watchedItemStore = $services->getWatchedItemStore();
523 }
524
525 $s = $list->beginRecentChangesList();
526
527 if ( $this->isStructuredFilterUiEnabled() ) {
528 $s .= $this->makeLegend();
529 }
530
531 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
532 $counter = 1;
533 foreach ( $rows as $obj ) {
534 # Make RC entry
535 $rc = RecentChange::newFromRow( $obj );
536
537 # Skip CatWatch entries for hidden cats based on user preference
538 if (
539 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE &&
540 !$userShowHiddenCats &&
541 $rc->getParam( 'hidden-cat' )
542 ) {
543 continue;
544 }
545
546 $rc->counter = $counter++;
547
548 if ( $this->getConfig()->get( 'ShowUpdatedMarker' ) ) {
549 $unseen = !$this->isChangeEffectivelySeen( $rc );
550 } else {
551 $unseen = false;
552 }
553
554 if ( isset( $watchedItemStore ) ) {
555 $rcTitleValue = new TitleValue( (int)$obj->rc_namespace, $obj->rc_title );
556 $rc->numberofWatchingusers = $watchedItemStore->countWatchers( $rcTitleValue );
557 } else {
558 $rc->numberofWatchingusers = 0;
559 }
560
561 // XXX: this treats pages with no unseen changes as "not on the watchlist" since
562 // everything is on the watchlist and it is an easy way to make pages with unseen
563 // changes appear bold. @TODO: clean this up.
564 $changeLine = $list->recentChangesLine( $rc, $unseen, $counter );
565 if ( $changeLine !== false ) {
566 $s .= $changeLine;
567 }
568 }
569 $s .= $list->endRecentChangesList();
570
571 $output->addHTML( $s );
572 }
573
574 /**
575 * Set the text to be displayed above the changes
576 *
577 * @param FormOptions $opts
578 * @param int $numRows Number of rows in the result to show after this header
579 */
580 public function doHeader( $opts, $numRows ) {
581 $user = $this->getUser();
582 $out = $this->getOutput();
583
584 $out->addSubtitle(
585 $this->msg( 'watchlistfor2', $user->getName() )
586 ->rawParams( SpecialEditWatchlist::buildTools(
587 $this->getLanguage(),
588 $this->getLinkRenderer()
589 ) )
590 );
591
592 $this->setTopText( $opts );
593
594 $form = '';
595
596 $form .= Xml::openElement( 'form', [
597 'method' => 'get',
598 'action' => wfScript(),
599 'id' => 'mw-watchlist-form'
600 ] );
601 $form .= Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
602 $form .= Xml::openElement(
603 'fieldset',
604 [ 'id' => 'mw-watchlist-options', 'class' => 'cloptions' ]
605 );
606 $form .= Xml::element(
607 'legend', null, $this->msg( 'watchlist-options' )->text()
608 );
609
610 if ( !$this->isStructuredFilterUiEnabled() ) {
611 $form .= $this->makeLegend();
612 }
613
614 $lang = $this->getLanguage();
615 $timestamp = wfTimestampNow();
616 $now = $lang->userTimeAndDate( $timestamp, $user );
617 $wlInfo = Html::rawElement(
618 'span',
619 [
620 'class' => 'wlinfo',
621 'data-params' => json_encode( [ 'from' => $timestamp, 'fromFormatted' => $now ] ),
622 ],
623 $this->msg( 'wlnote' )->numParams( $numRows, round( $opts['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->getLegacyShowHideFilters() as $filterName => $filter ) {
639 $namesOfDisplayedFilters[] = $filterName;
640 $links[] = $this->showHideCheck(
641 $nondefaults,
642 $filter->getShowHide(),
643 $filterName,
644 $opts[ $filterName ],
645 $filter->isFeatureAvailableOnStructuredUi( $this )
646 );
647 }
648
649 $hiddenFields = $nondefaults;
650 $hiddenFields['action'] = 'submit';
651 unset( $hiddenFields['namespace'] );
652 unset( $hiddenFields['invert'] );
653 unset( $hiddenFields['associated'] );
654 unset( $hiddenFields['days'] );
655 foreach ( $namesOfDisplayedFilters as $filterName ) {
656 unset( $hiddenFields[$filterName] );
657 }
658
659 # Namespace filter and put the whole form together.
660 $form .= $wlInfo;
661 $form .= $cutofflinks;
662 $form .= Html::rawElement(
663 'span',
664 [ 'class' => 'clshowhide' ],
665 $this->msg( 'watchlist-hide' ) .
666 $this->msg( 'colon-separator' )->escaped() .
667 implode( ' ', $links )
668 );
669 $form .= "\n<br />\n";
670
671 $namespaceForm = Html::namespaceSelector(
672 [
673 'selected' => $opts['namespace'],
674 'all' => '',
675 'label' => $this->msg( 'namespace' )->text(),
676 'in-user-lang' => true,
677 ], [
678 'name' => 'namespace',
679 'id' => 'namespace',
680 'class' => 'namespaceselector',
681 ]
682 ) . "\n";
683 $hidden = $opts['namespace'] === '' ? ' mw-input-hidden' : '';
684 $namespaceForm .= '<span class="mw-input-with-label' . $hidden . '">' . Xml::checkLabel(
685 $this->msg( 'invert' )->text(),
686 'invert',
687 'nsinvert',
688 $opts['invert'],
689 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
690 ) . "</span>\n";
691 $namespaceForm .= '<span class="mw-input-with-label' . $hidden . '">' . Xml::checkLabel(
692 $this->msg( 'namespace_association' )->text(),
693 'associated',
694 'nsassociated',
695 $opts['associated'],
696 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
697 ) . "</span>\n";
698 $form .= Html::rawElement(
699 'span',
700 [ 'class' => 'namespaceForm cloption' ],
701 $namespaceForm
702 );
703
704 $form .= Xml::submitButton(
705 $this->msg( 'watchlist-submit' )->text(),
706 [ 'class' => 'cloption-submit' ]
707 ) . "\n";
708 foreach ( $hiddenFields as $key => $value ) {
709 $form .= Html::hidden( $key, $value ) . "\n";
710 }
711 $form .= Xml::closeElement( 'fieldset' ) . "\n";
712 $form .= Xml::closeElement( 'form' ) . "\n";
713
714 // Insert a placeholder for RCFilters
715 if ( $this->isStructuredFilterUiEnabled() ) {
716 $rcfilterContainer = Html::element(
717 'div',
718 // TODO: Remove deprecated rcfilters-container class
719 [ 'class' => 'rcfilters-container mw-rcfilters-container' ]
720 );
721
722 $loadingContainer = Html::rawElement(
723 'div',
724 [ 'class' => 'mw-rcfilters-spinner' ],
725 Html::element(
726 'div',
727 [ 'class' => 'mw-rcfilters-spinner-bounce' ]
728 )
729 );
730
731 // Wrap both with rcfilters-head
732 $this->getOutput()->addHTML(
733 Html::rawElement(
734 'div',
735 // TODO: Remove deprecated rcfilters-head class
736 [ 'class' => 'rcfilters-head mw-rcfilters-head' ],
737 $rcfilterContainer . $form
738 )
739 );
740
741 // Add spinner
742 $this->getOutput()->addHTML( $loadingContainer );
743 } else {
744 $this->getOutput()->addHTML( $form );
745 }
746
747 $this->setBottomText( $opts );
748 }
749
750 function cutoffselector( $options ) {
751 $selected = (float)$options['days'];
752 if ( $selected <= 0 ) {
753 $selected = $this->maxDays;
754 }
755
756 $selectedHours = round( $selected * 24 );
757
758 $hours = array_unique( array_filter( [
759 1,
760 2,
761 6,
762 12,
763 24,
764 72,
765 168,
766 24 * (float)$this->getUser()->getOption( 'watchlistdays', 0 ),
767 24 * $this->maxDays,
768 $selectedHours
769 ] ) );
770 asort( $hours );
771
772 $select = new XmlSelect( 'days', 'days', (float)( $selectedHours / 24 ) );
773
774 foreach ( $hours as $value ) {
775 if ( $value < 24 ) {
776 $name = $this->msg( 'hours' )->numParams( $value )->text();
777 } else {
778 $name = $this->msg( 'days' )->numParams( $value / 24 )->text();
779 }
780 $select->addOption( $name, (float)( $value / 24 ) );
781 }
782
783 return $select->getHTML() . "\n<br />\n";
784 }
785
786 function setTopText( FormOptions $opts ) {
787 $nondefaults = $opts->getChangedValues();
788 $form = '';
789 $user = $this->getUser();
790
791 $numItems = $this->countItems();
792 $showUpdatedMarker = $this->getConfig()->get( 'ShowUpdatedMarker' );
793
794 // Show watchlist header
795 $watchlistHeader = '';
796 if ( $numItems == 0 ) {
797 $watchlistHeader = $this->msg( 'nowatchlist' )->parse();
798 } else {
799 $watchlistHeader .= $this->msg( 'watchlist-details' )->numParams( $numItems )->parse() . "\n";
800 if ( $this->getConfig()->get( 'EnotifWatchlist' )
801 && $user->getOption( 'enotifwatchlistpages' )
802 ) {
803 $watchlistHeader .= $this->msg( 'wlheader-enotif' )->parse() . "\n";
804 }
805 if ( $showUpdatedMarker ) {
806 $watchlistHeader .= $this->msg(
807 $this->isStructuredFilterUiEnabled() ?
808 'rcfilters-watchlist-showupdated' :
809 'wlheader-showupdated'
810 )->parse() . "\n";
811 }
812 }
813 $form .= Html::rawElement(
814 'div',
815 [ 'class' => 'watchlistDetails' ],
816 $watchlistHeader
817 );
818
819 if ( $numItems > 0 && $showUpdatedMarker ) {
820 $form .= Xml::openElement( 'form', [ 'method' => 'post',
821 'action' => $this->getPageTitle()->getLocalURL(),
822 'id' => 'mw-watchlist-resetbutton' ] ) . "\n" .
823 Xml::submitButton( $this->msg( 'enotif_reset' )->text(),
824 [ 'name' => 'mw-watchlist-reset-submit' ] ) . "\n" .
825 Html::hidden( 'token', $user->getEditToken() ) . "\n" .
826 Html::hidden( 'reset', 'all' ) . "\n";
827 foreach ( $nondefaults as $key => $value ) {
828 $form .= Html::hidden( $key, $value ) . "\n";
829 }
830 $form .= Xml::closeElement( 'form' ) . "\n";
831 }
832
833 $this->getOutput()->addHTML( $form );
834 }
835
836 protected function showHideCheck( $options, $message, $name, $value, $inStructuredUi ) {
837 $options[$name] = 1 - (int)$value;
838
839 $attribs = [ 'class' => 'mw-input-with-label clshowhideoption cloption' ];
840 if ( $inStructuredUi ) {
841 $attribs[ 'data-feature-in-structured-ui' ] = true;
842 }
843
844 return Html::rawElement(
845 'span',
846 $attribs,
847 // not using Html::checkLabel because that would escape the contents
848 Html::check( $name, (int)$value, [ 'id' => $name ] ) . Html::rawElement(
849 'label',
850 $attribs + [ 'for' => $name ],
851 // <nowiki/> at beginning to avoid messages with "$1 ..." being parsed as pre tags
852 $this->msg( $message, '<nowiki/>' )->parse()
853 )
854 );
855 }
856
857 /**
858 * Count the number of paired items on a user's watchlist.
859 * The assumption made here is that when a subject page is watched a talk page is also watched.
860 * Hence the number of individual items is halved.
861 *
862 * @return int
863 */
864 protected function countItems() {
865 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
866 $count = $store->countWatchedItems( $this->getUser() );
867 return floor( $count / 2 );
868 }
869
870 /**
871 * @param RecentChange $rc
872 * @return bool User viewed the revision or a newer one
873 */
874 protected function isChangeEffectivelySeen( RecentChange $rc ) {
875 $firstUnseen = $this->getLatestNotificationTimestamp( $rc );
876
877 return ( $firstUnseen === null || $firstUnseen > $rc->getAttribute( 'rc_timestamp' ) );
878 }
879
880 /**
881 * @param RecentChange $rc
882 * @return string|null TS_MW timestamp of first unseen revision or null if there isn't one
883 */
884 private function getLatestNotificationTimestamp( RecentChange $rc ) {
885 return $this->watchStore->getLatestNotificationTimestamp(
886 $rc->getAttribute( 'wl_notificationtimestamp' ),
887 $this->getUser(),
888 $rc->getTitle()
889 );
890 }
891 }