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