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