AuthManager: Break AuthPlugin::addUser more explicitly
[mediawiki.git] / includes / specials / SpecialWatchlist.php
blob58cde7e55ab8ed562bc004520a3a96939615c35f
1 <?php
2 /**
3 * Implements Special:Watchlist
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.
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.
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
20 * @file
21 * @ingroup SpecialPage
24 use MediaWiki\MediaWikiServices;
26 /**
27 * A special page that lists last changes made to the wiki,
28 * limited to user-defined list of titles.
30 * @ingroup SpecialPage
32 class SpecialWatchlist extends ChangesListSpecialPage {
33 public function __construct( $page = 'Watchlist', $restriction = 'viewmywatchlist' ) {
34 parent::__construct( $page, $restriction );
37 public function doesWrites() {
38 return true;
41 /**
42 * Main execution point
44 * @param string $subpage
46 function execute( $subpage ) {
47 // Anons don't get a watchlist
48 $this->requireLogin( 'watchlistanontext' );
50 $output = $this->getOutput();
51 $request = $this->getRequest();
52 $this->addHelpLink( 'Help:Watching pages' );
53 $output->addModules( [
54 'mediawiki.special.changeslist.visitedstatus',
55 ] );
57 $mode = SpecialEditWatchlist::getMode( $request, $subpage );
58 if ( $mode !== false ) {
59 if ( $mode === SpecialEditWatchlist::EDIT_RAW ) {
60 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'raw' );
61 } elseif ( $mode === SpecialEditWatchlist::EDIT_CLEAR ) {
62 $title = SpecialPage::getTitleFor( 'EditWatchlist', 'clear' );
63 } else {
64 $title = SpecialPage::getTitleFor( 'EditWatchlist' );
67 $output->redirect( $title->getLocalURL() );
69 return;
72 $this->checkPermissions();
74 $user = $this->getUser();
75 $opts = $this->getOptions();
77 $config = $this->getConfig();
78 if ( ( $config->get( 'EnotifWatchlist' ) || $config->get( 'ShowUpdatedMarker' ) )
79 && $request->getVal( 'reset' )
80 && $request->wasPosted()
81 ) {
82 $user->clearAllNotifications();
83 $output->redirect( $this->getPageTitle()->getFullURL( $opts->getChangedValues() ) );
85 return;
88 parent::execute( $subpage );
91 /**
92 * Return an array of subpages that this special page will accept.
94 * @see also SpecialEditWatchlist::getSubpagesForPrefixSearch
95 * @return string[] subpages
97 public function getSubpagesForPrefixSearch() {
98 return [
99 'clear',
100 'edit',
101 'raw',
106 * Get a FormOptions object containing the default options
108 * @return FormOptions
110 public function getDefaultOptions() {
111 $opts = parent::getDefaultOptions();
112 $user = $this->getUser();
114 $opts->add( 'days', $user->getOption( 'watchlistdays' ), FormOptions::FLOAT );
115 $opts->add( 'extended', $user->getBoolOption( 'extendwatchlist' ) );
116 if ( $this->getRequest()->getVal( 'action' ) == 'submit' ) {
117 // The user has submitted the form, so we dont need the default values
118 return $opts;
121 $opts->add( 'hideminor', $user->getBoolOption( 'watchlisthideminor' ) );
122 $opts->add( 'hidebots', $user->getBoolOption( 'watchlisthidebots' ) );
123 $opts->add( 'hideanons', $user->getBoolOption( 'watchlisthideanons' ) );
124 $opts->add( 'hideliu', $user->getBoolOption( 'watchlisthideliu' ) );
125 $opts->add( 'hidepatrolled', $user->getBoolOption( 'watchlisthidepatrolled' ) );
126 $opts->add( 'hidemyself', $user->getBoolOption( 'watchlisthideown' ) );
127 $opts->add( 'hidecategorization', $user->getBoolOption( 'watchlisthidecategorization' ) );
129 return $opts;
133 * Get custom show/hide filters
135 * @return array Map of filter URL param names to properties (msg/default)
137 protected function getCustomFilters() {
138 if ( $this->customFilters === null ) {
139 $this->customFilters = parent::getCustomFilters();
140 Hooks::run( 'SpecialWatchlistFilters', [ $this, &$this->customFilters ], '1.23' );
143 return $this->customFilters;
147 * Fetch values for a FormOptions object from the WebRequest associated with this instance.
149 * Maps old pre-1.23 request parameters Watchlist used to use (different from Recentchanges' ones)
150 * to the current ones.
152 * @param FormOptions $opts
153 * @return FormOptions
155 protected function fetchOptionsFromRequest( $opts ) {
156 static $compatibilityMap = [
157 'hideMinor' => 'hideminor',
158 'hideBots' => 'hidebots',
159 'hideAnons' => 'hideanons',
160 'hideLiu' => 'hideliu',
161 'hidePatrolled' => 'hidepatrolled',
162 'hideOwn' => 'hidemyself',
165 $params = $this->getRequest()->getValues();
166 foreach ( $compatibilityMap as $from => $to ) {
167 if ( isset( $params[$from] ) ) {
168 $params[$to] = $params[$from];
169 unset( $params[$from] );
173 // Not the prettiest way to achieve this… FormOptions internally depends on data sanitization
174 // methods defined on WebRequest and removing this dependency would cause some code duplication.
175 $request = new DerivativeRequest( $this->getRequest(), $params );
176 $opts->fetchValuesFromRequest( $request );
178 return $opts;
182 * Return an array of conditions depending of options set in $opts
184 * @param FormOptions $opts
185 * @return array
187 public function buildMainQueryConds( FormOptions $opts ) {
188 $dbr = $this->getDB();
189 $conds = parent::buildMainQueryConds( $opts );
191 // Calculate cutoff
192 if ( $opts['days'] > 0 ) {
193 $conds[] = 'rc_timestamp > ' .
194 $dbr->addQuotes( $dbr->timestamp( time() - intval( $opts['days'] * 86400 ) ) );
197 return $conds;
201 * Process the query
203 * @param array $conds
204 * @param FormOptions $opts
205 * @return bool|ResultWrapper Result or false (for Recentchangeslinked only)
207 public function doMainQuery( $conds, $opts ) {
208 $dbr = $this->getDB();
209 $user = $this->getUser();
211 # Toggle watchlist content (all recent edits or just the latest)
212 if ( $opts['extended'] ) {
213 $limitWatchlist = $user->getIntOption( 'wllimit' );
214 $usePage = false;
215 } else {
216 # Top log Ids for a page are not stored
217 $nonRevisionTypes = [ RC_LOG ];
218 Hooks::run( 'SpecialWatchlistGetNonRevisionTypes', [ &$nonRevisionTypes ] );
219 if ( $nonRevisionTypes ) {
220 $conds[] = $dbr->makeList(
222 'rc_this_oldid=page_latest',
223 'rc_type' => $nonRevisionTypes,
225 LIST_OR
228 $limitWatchlist = 0;
229 $usePage = true;
232 $tables = [ 'recentchanges', 'watchlist' ];
233 $fields = RecentChange::selectFields();
234 $query_options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
235 $join_conds = [
236 'watchlist' => [
237 'INNER JOIN',
239 'wl_user' => $user->getId(),
240 'wl_namespace=rc_namespace',
241 'wl_title=rc_title'
246 if ( $this->getConfig()->get( 'ShowUpdatedMarker' ) ) {
247 $fields[] = 'wl_notificationtimestamp';
249 if ( $limitWatchlist ) {
250 $query_options['LIMIT'] = $limitWatchlist;
253 $rollbacker = $user->isAllowed( 'rollback' );
254 if ( $usePage || $rollbacker ) {
255 $tables[] = 'page';
256 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
257 if ( $rollbacker ) {
258 $fields[] = 'page_latest';
262 // Log entries with DELETED_ACTION must not show up unless the user has
263 // the necessary rights.
264 if ( !$user->isAllowed( 'deletedhistory' ) ) {
265 $bitmask = LogPage::DELETED_ACTION;
266 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
267 $bitmask = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
268 } else {
269 $bitmask = 0;
271 if ( $bitmask ) {
272 $conds[] = $dbr->makeList( [
273 'rc_type != ' . RC_LOG,
274 $dbr->bitAnd( 'rc_deleted', $bitmask ) . " != $bitmask",
275 ], LIST_OR );
278 ChangeTags::modifyDisplayQuery(
279 $tables,
280 $fields,
281 $conds,
282 $join_conds,
283 $query_options,
287 $this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts );
289 return $dbr->select(
290 $tables,
291 $fields,
292 $conds,
293 __METHOD__,
294 $query_options,
295 $join_conds
299 protected function runMainQueryHook( &$tables, &$fields, &$conds, &$query_options,
300 &$join_conds, $opts
302 return parent::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
303 && Hooks::run(
304 'SpecialWatchlistQuery',
305 [ &$conds, &$tables, &$join_conds, &$fields, $opts ],
306 '1.23'
311 * Return a IDatabase object for reading
313 * @return IDatabase
315 protected function getDB() {
316 return wfGetDB( DB_SLAVE, 'watchlist' );
320 * Output feed links.
322 public function outputFeedLinks() {
323 $user = $this->getUser();
324 $wlToken = $user->getTokenFromOption( 'watchlisttoken' );
325 if ( $wlToken ) {
326 $this->addFeedLinks( [
327 'action' => 'feedwatchlist',
328 'allrev' => 1,
329 'wlowner' => $user->getName(),
330 'wltoken' => $wlToken,
331 ] );
336 * Build and output the actual changes list.
338 * @param ResultWrapper $rows Database rows
339 * @param FormOptions $opts
341 public function outputChangesList( $rows, $opts ) {
342 $dbr = $this->getDB();
343 $user = $this->getUser();
344 $output = $this->getOutput();
346 # Show a message about slave lag, if applicable
347 $lag = wfGetLB()->safeGetLag( $dbr );
348 if ( $lag > 0 ) {
349 $output->showLagWarning( $lag );
352 # If no rows to display, show message before try to render the list
353 if ( $rows->numRows() == 0 ) {
354 $output->wrapWikiMsg(
355 "<div class='mw-changeslist-empty'>\n$1\n</div>", 'recentchanges-noresult'
357 return;
360 $dbr->dataSeek( $rows, 0 );
362 $list = ChangesList::newFromContext( $this->getContext() );
363 $list->setWatchlistDivs();
364 $list->initChangesListRows( $rows );
365 $dbr->dataSeek( $rows, 0 );
367 if ( $this->getConfig()->get( 'RCShowWatchingUsers' )
368 && $user->getOption( 'shownumberswatching' )
370 $watchedItemStore = MediaWikiServices::getInstance()->getWatchedItemStore();
373 $s = $list->beginRecentChangesList();
374 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
375 $counter = 1;
376 foreach ( $rows as $obj ) {
377 # Make RC entry
378 $rc = RecentChange::newFromRow( $obj );
380 # Skip CatWatch entries for hidden cats based on user preference
381 if (
382 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE &&
383 !$userShowHiddenCats &&
384 $rc->getParam( 'hidden-cat' )
386 continue;
389 $rc->counter = $counter++;
391 if ( $this->getConfig()->get( 'ShowUpdatedMarker' ) ) {
392 $updated = $obj->wl_notificationtimestamp;
393 } else {
394 $updated = false;
397 if ( isset( $watchedItemStore ) ) {
398 $rcTitleValue = new TitleValue( (int)$obj->rc_namespace, $obj->rc_title );
399 $rc->numberofWatchingusers = $watchedItemStore->countWatchers( $rcTitleValue );
400 } else {
401 $rc->numberofWatchingusers = 0;
404 $changeLine = $list->recentChangesLine( $rc, $updated, $counter );
405 if ( $changeLine !== false ) {
406 $s .= $changeLine;
409 $s .= $list->endRecentChangesList();
411 $output->addHTML( $s );
415 * Set the text to be displayed above the changes
417 * @param FormOptions $opts
418 * @param int $numRows Number of rows in the result to show after this header
420 public function doHeader( $opts, $numRows ) {
421 $user = $this->getUser();
422 $out = $this->getOutput();
424 // if the user wishes, that the watchlist is reloaded, whenever a filter changes,
425 // add the module for that
426 if ( $user->getBoolOption( 'watchlistreloadautomatically' ) ) {
427 $out->addModules( [ 'mediawiki.special.watchlist' ] );
430 $out->addSubtitle(
431 $this->msg( 'watchlistfor2', $user->getName() )
432 ->rawParams( SpecialEditWatchlist::buildTools( null ) )
435 $this->setTopText( $opts );
437 $lang = $this->getLanguage();
438 if ( $opts['days'] > 0 ) {
439 $days = $opts['days'];
440 } else {
441 $days = $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 );
443 $timestamp = wfTimestampNow();
444 $wlInfo = $this->msg( 'wlnote' )->numParams( $numRows, round( $days * 24 ) )->params(
445 $lang->userDate( $timestamp, $user ), $lang->userTime( $timestamp, $user )
446 )->parse() . "<br />\n";
448 $nondefaults = $opts->getChangedValues();
449 $cutofflinks = $this->msg( 'wlshowtime' ) . ' ' . $this->cutoffselector( $opts );
451 # Spit out some control panel links
452 $filters = [
453 'hideminor' => 'wlshowhideminor',
454 'hidebots' => 'wlshowhidebots',
455 'hideanons' => 'wlshowhideanons',
456 'hideliu' => 'wlshowhideliu',
457 'hidemyself' => 'wlshowhidemine',
458 'hidepatrolled' => 'wlshowhidepatr'
461 if ( $this->getConfig()->get( 'RCWatchCategoryMembership' ) ) {
462 $filters['hidecategorization'] = 'wlshowhidecategorization';
465 foreach ( $this->getCustomFilters() as $key => $params ) {
466 $filters[$key] = $params['msg'];
468 // Disable some if needed
469 if ( !$user->useRCPatrol() ) {
470 unset( $filters['hidepatrolled'] );
473 $links = [];
474 foreach ( $filters as $name => $msg ) {
475 $links[] = $this->showHideCheck( $nondefaults, $msg, $name, $opts[$name] );
478 $hiddenFields = $nondefaults;
479 $hiddenFields['action'] = 'submit';
480 unset( $hiddenFields['namespace'] );
481 unset( $hiddenFields['invert'] );
482 unset( $hiddenFields['associated'] );
483 unset( $hiddenFields['days'] );
484 foreach ( $filters as $key => $value ) {
485 unset( $hiddenFields[$key] );
488 # Create output
489 $form = '';
491 # Namespace filter and put the whole form together.
492 $form .= $wlInfo;
493 $form .= $cutofflinks;
494 $form .= $this->msg( 'watchlist-hide' ) .
495 $this->msg( 'colon-separator' )->escaped() .
496 implode( ' ', $links );
497 $form .= "\n<br />\n";
498 $form .= Html::namespaceSelector(
500 'selected' => $opts['namespace'],
501 'all' => '',
502 'label' => $this->msg( 'namespace' )->text()
503 ], [
504 'name' => 'namespace',
505 'id' => 'namespace',
506 'class' => 'namespaceselector',
508 ) . "\n";
509 $form .= '<span class="mw-input-with-label">' . Xml::checkLabel(
510 $this->msg( 'invert' )->text(),
511 'invert',
512 'nsinvert',
513 $opts['invert'],
514 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
515 ) . "</span>\n";
516 $form .= '<span class="mw-input-with-label">' . Xml::checkLabel(
517 $this->msg( 'namespace_association' )->text(),
518 'associated',
519 'nsassociated',
520 $opts['associated'],
521 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
522 ) . "</span>\n";
523 $form .= Xml::submitButton( $this->msg( 'watchlist-submit' )->text() ) . "\n";
524 foreach ( $hiddenFields as $key => $value ) {
525 $form .= Html::hidden( $key, $value ) . "\n";
527 $form .= Xml::closeElement( 'fieldset' ) . "\n";
528 $form .= Xml::closeElement( 'form' ) . "\n";
529 $this->getOutput()->addHTML( $form );
531 $this->setBottomText( $opts );
534 function cutoffselector( $options ) {
535 // Cast everything to strings immediately, so that we know all of the values have the same
536 // precision, and can be compared with '==='. 2/24 has a few more decimal places than its
537 // default string representation, for example, and would confuse comparisons.
539 // Misleadingly, the 'days' option supports hours too.
540 $days = array_map( 'strval', [ 1/24, 2/24, 6/24, 12/24, 1, 3, 7 ] );
542 $userWatchlistOption = (string)$this->getUser()->getOption( 'watchlistdays' );
543 // add the user preference, if it isn't available already
544 if ( !in_array( $userWatchlistOption, $days ) && $userWatchlistOption !== '0' ) {
545 $days[] = $userWatchlistOption;
548 $maxDays = (string)( $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
549 // add the maximum possible value, if it isn't available already
550 if ( !in_array( $maxDays, $days ) ) {
551 $days[] = $maxDays;
554 $selected = (string)$options['days'];
555 if ( $selected <= 0 ) {
556 $selected = $maxDays;
559 // add the currently selected value, if it isn't available already
560 if ( !in_array( $selected, $days ) ) {
561 $days[] = $selected;
564 $select = new XmlSelect( 'days', 'days', $selected );
566 asort( $days );
567 foreach ( $days as $value ) {
568 if ( $value < 1 ) {
569 $name = $this->msg( 'hours' )->numParams( $value * 24 )->text();
570 } else {
571 $name = $this->msg( 'days' )->numParams( $value )->text();
573 $select->addOption( $name, $value );
576 return $select->getHTML() . "\n<br />\n";
579 function setTopText( FormOptions $opts ) {
580 $nondefaults = $opts->getChangedValues();
581 $form = "";
582 $user = $this->getUser();
584 $numItems = $this->countItems();
585 $showUpdatedMarker = $this->getConfig()->get( 'ShowUpdatedMarker' );
587 // Show watchlist header
588 $form .= "<p>";
589 if ( $numItems == 0 ) {
590 $form .= $this->msg( 'nowatchlist' )->parse() . "\n";
591 } else {
592 $form .= $this->msg( 'watchlist-details' )->numParams( $numItems )->parse() . "\n";
593 if ( $this->getConfig()->get( 'EnotifWatchlist' )
594 && $user->getOption( 'enotifwatchlistpages' )
596 $form .= $this->msg( 'wlheader-enotif' )->parse() . "\n";
598 if ( $showUpdatedMarker ) {
599 $form .= $this->msg( 'wlheader-showupdated' )->parse() . "\n";
602 $form .= "</p>";
604 if ( $numItems > 0 && $showUpdatedMarker ) {
605 $form .= Xml::openElement( 'form', [ 'method' => 'post',
606 'action' => $this->getPageTitle()->getLocalURL(),
607 'id' => 'mw-watchlist-resetbutton' ] ) . "\n" .
608 Xml::submitButton( $this->msg( 'enotif_reset' )->text(), [ 'name' => 'dummy' ] ) . "\n" .
609 Html::hidden( 'reset', 'all' ) . "\n";
610 foreach ( $nondefaults as $key => $value ) {
611 $form .= Html::hidden( $key, $value ) . "\n";
613 $form .= Xml::closeElement( 'form' ) . "\n";
616 $form .= Xml::openElement( 'form', [
617 'method' => 'get',
618 'action' => $this->getPageTitle()->getLocalURL(),
619 'id' => 'mw-watchlist-form'
620 ] );
621 $form .= Xml::fieldset(
622 $this->msg( 'watchlist-options' )->text(),
623 false,
624 [ 'id' => 'mw-watchlist-options' ]
627 $form .= $this->makeLegend();
629 $this->getOutput()->addHTML( $form );
632 protected function showHideCheck( $options, $message, $name, $value ) {
633 $options[$name] = 1 - (int)$value;
635 return '<span class="mw-input-with-label">' . Xml::checkLabel(
636 $this->msg( $message, '' )->text(),
637 $name,
638 $name,
639 (int)$value
640 ) . '</span>';
644 * Count the number of paired items on a user's watchlist.
645 * The assumption made here is that when a subject page is watched a talk page is also watched.
646 * Hence the number of individual items is halved.
648 * @return int
650 protected function countItems() {
651 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
652 $count = $store->countWatchedItems( $this->getUser() );
653 return floor( $count / 2 );