3 * @defgroup Watchlist Users watchlist handling
7 * Implements Special:EditWatchlist
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
25 * @ingroup SpecialPage
29 use MediaWiki\Linker\LinkRenderer
;
30 use MediaWiki\Linker\LinkTarget
;
31 use MediaWiki\MediaWikiServices
;
34 * Provides the UI through which users can perform editing
35 * operations on their watchlist
37 * @ingroup SpecialPage
39 * @author Rob Church <robchur@gmail.com>
41 class SpecialEditWatchlist
extends UnlistedSpecialPage
{
43 * Editing modes. EDIT_CLEAR is no longer used; the "Clear" link scared people
44 * too much. Now it's passed on to the raw editor, from which it's very easy to clear.
48 const EDIT_NORMAL
= 3;
50 protected $successMessage;
54 private $badItems = [];
61 public function __construct() {
62 parent
::__construct( 'EditWatchlist', 'editmywatchlist' );
66 * Initialize any services we'll need (unless it has already been provided via a setter).
67 * This allows for dependency injection even though we don't control object creation.
69 private function initServices() {
70 if ( !$this->titleParser
) {
71 $this->titleParser
= MediaWikiServices
::getInstance()->getTitleParser();
75 public function doesWrites() {
80 * Main execution point
84 public function execute( $mode ) {
85 $this->initServices();
88 # Anons don't get a watchlist
89 $this->requireLogin( 'watchlistanontext' );
91 $out = $this->getOutput();
93 $this->checkPermissions();
94 $this->checkReadOnly();
96 $this->outputHeader();
97 $this->outputSubtitle();
98 $out->addModuleStyles( 'mediawiki.special' );
100 # B/C: $mode used to be waaay down the parameter list, and the first parameter
102 if ( $mode instanceof User
) {
103 $args = func_get_args();
104 if ( count( $args ) >= 4 ) {
108 $mode = self
::getMode( $this->getRequest(), $mode );
112 $out->setPageTitle( $this->msg( 'watchlistedit-raw-title' ) );
113 $form = $this->getRawForm();
114 if ( $form->show() ) {
115 $out->addHTML( $this->successMessage
);
116 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
119 case self
::EDIT_CLEAR
:
120 $out->setPageTitle( $this->msg( 'watchlistedit-clear-title' ) );
121 $form = $this->getClearForm();
122 if ( $form->show() ) {
123 $out->addHTML( $this->successMessage
);
124 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
128 case self
::EDIT_NORMAL
:
130 $this->executeViewEditWatchlist();
136 * Renders a subheader on the watchlist page.
138 protected function outputSubtitle() {
139 $out = $this->getOutput();
140 $out->addSubtitle( $this->msg( 'watchlistfor2', $this->getUser()->getName() )
143 $this->getLanguage(),
144 $this->getLinkRenderer()
151 * Executes an edit mode for the watchlist view, from which you can manage your watchlist
153 protected function executeViewEditWatchlist() {
154 $out = $this->getOutput();
155 $out->setPageTitle( $this->msg( 'watchlistedit-normal-title' ) );
156 $form = $this->getNormalForm();
157 if ( $form->show() ) {
158 $out->addHTML( $this->successMessage
);
159 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
160 } elseif ( $this->toc
!== false ) {
161 $out->prependHTML( $this->toc
);
162 $out->addModules( 'mediawiki.toc' );
167 * Return an array of subpages that this special page will accept.
169 * @see also SpecialWatchlist::getSubpagesForPrefixSearch
170 * @return string[] subpages
172 public function getSubpagesForPrefixSearch() {
173 // SpecialWatchlist uses SpecialEditWatchlist::getMode, so new types should be added
174 // here and there - no 'edit' here, because that the default for this page
182 * Extract a list of titles from a blob of text, returning
183 * (prefixed) strings; unwatchable titles are ignored
185 * @param string $list
188 private function extractTitles( $list ) {
189 $list = explode( "\n", trim( $list ) );
190 if ( !is_array( $list ) ) {
196 foreach ( $list as $text ) {
197 $text = trim( $text );
198 if ( strlen( $text ) > 0 ) {
199 $title = Title
::newFromText( $text );
200 if ( $title instanceof Title
&& $title->isWatchable() ) {
206 MediaWikiServices
::getInstance()->getGenderCache()->doTitlesArray( $titles );
209 /** @var Title $title */
210 foreach ( $titles as $title ) {
211 $list[] = $title->getPrefixedText();
214 return array_unique( $list );
217 public function submitRaw( $data ) {
218 $wanted = $this->extractTitles( $data['Titles'] );
219 $current = $this->getWatchlist();
221 if ( count( $wanted ) > 0 ) {
222 $toWatch = array_diff( $wanted, $current );
223 $toUnwatch = array_diff( $current, $wanted );
224 $this->watchTitles( $toWatch );
225 $this->unwatchTitles( $toUnwatch );
226 $this->getUser()->invalidateCache();
228 if ( count( $toWatch ) > 0 ||
count( $toUnwatch ) > 0 ) {
229 $this->successMessage
= $this->msg( 'watchlistedit-raw-done' )->parse();
234 if ( count( $toWatch ) > 0 ) {
235 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-added' )
236 ->numParams( count( $toWatch ) )->parse();
237 $this->showTitles( $toWatch, $this->successMessage
);
240 if ( count( $toUnwatch ) > 0 ) {
241 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-removed' )
242 ->numParams( count( $toUnwatch ) )->parse();
243 $this->showTitles( $toUnwatch, $this->successMessage
);
246 $this->clearWatchlist();
247 $this->getUser()->invalidateCache();
249 if ( count( $current ) > 0 ) {
250 $this->successMessage
= $this->msg( 'watchlistedit-raw-done' )->parse();
255 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-removed' )
256 ->numParams( count( $current ) )->parse();
257 $this->showTitles( $current, $this->successMessage
);
263 public function submitClear( $data ) {
264 $current = $this->getWatchlist();
265 $this->clearWatchlist();
266 $this->getUser()->invalidateCache();
267 $this->successMessage
= $this->msg( 'watchlistedit-clear-done' )->parse();
268 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-clear-removed' )
269 ->numParams( count( $current ) )->parse();
270 $this->showTitles( $current, $this->successMessage
);
276 * Print out a list of linked titles
278 * $titles can be an array of strings or Title objects; the former
279 * is preferred, since Titles are very memory-heavy
281 * @param array $titles Array of strings, or Title objects
282 * @param string $output
284 private function showTitles( $titles, &$output ) {
285 $talk = $this->msg( 'talkpagelinktext' )->text();
286 // Do a batch existence check
287 $batch = new LinkBatch();
288 if ( count( $titles ) >= 100 ) {
289 $output = $this->msg( 'watchlistedit-too-many' )->parse();
292 foreach ( $titles as $title ) {
293 if ( !$title instanceof Title
) {
294 $title = Title
::newFromText( $title );
297 if ( $title instanceof Title
) {
298 $batch->addObj( $title );
299 $batch->addObj( $title->getTalkPage() );
305 // Print out the list
308 $linkRenderer = $this->getLinkRenderer();
309 foreach ( $titles as $title ) {
310 if ( !$title instanceof Title
) {
311 $title = Title
::newFromText( $title );
314 if ( $title instanceof Title
) {
316 $linkRenderer->makeLink( $title ) . ' ' .
317 $this->msg( 'parentheses' )->rawParams(
318 $linkRenderer->makeLink( $title->getTalkPage(), $talk )
324 $output .= "</ul>\n";
328 * Prepare a list of titles on a user's watchlist (excluding talk pages)
329 * and return an array of (prefixed) strings
333 private function getWatchlist() {
336 $watchedItems = MediaWikiServices
::getInstance()->getWatchedItemStore()->getWatchedItemsForUser(
338 [ 'forWrite' => $this->getRequest()->wasPosted() ]
341 if ( $watchedItems ) {
342 /** @var Title[] $titles */
344 foreach ( $watchedItems as $watchedItem ) {
345 $namespace = $watchedItem->getLinkTarget()->getNamespace();
346 $dbKey = $watchedItem->getLinkTarget()->getDBkey();
347 $title = Title
::makeTitleSafe( $namespace, $dbKey );
349 if ( $this->checkTitle( $title, $namespace, $dbKey )
350 && !$title->isTalkPage()
356 MediaWikiServices
::getInstance()->getGenderCache()->doTitlesArray( $titles );
358 foreach ( $titles as $title ) {
359 $list[] = $title->getPrefixedText();
363 $this->cleanupWatchlist();
369 * Get a list of titles on a user's watchlist, excluding talk pages,
370 * and return as a two-dimensional array with namespace and title.
374 protected function getWatchlistInfo() {
377 $watchedItems = MediaWikiServices
::getInstance()->getWatchedItemStore()
378 ->getWatchedItemsForUser( $this->getUser(), [ 'sort' => WatchedItemStore
::SORT_ASC
] );
380 $lb = new LinkBatch();
382 foreach ( $watchedItems as $watchedItem ) {
383 $namespace = $watchedItem->getLinkTarget()->getNamespace();
384 $dbKey = $watchedItem->getLinkTarget()->getDBkey();
385 $lb->add( $namespace, $dbKey );
386 if ( !MWNamespace
::isTalk( $namespace ) ) {
387 $titles[$namespace][$dbKey] = 1;
397 * Validates watchlist entry
399 * @param Title $title
400 * @param int $namespace
401 * @param string $dbKey
402 * @return bool Whether this item is valid
404 private function checkTitle( $title, $namespace, $dbKey ) {
406 && ( $title->isExternal()
407 ||
$title->getNamespace() < 0
410 $title = false; // unrecoverable
414 ||
$title->getNamespace() != $namespace
415 ||
$title->getDBkey() != $dbKey
417 $this->badItems
[] = [ $title, $namespace, $dbKey ];
424 * Attempts to clean up broken items
426 private function cleanupWatchlist() {
427 if ( !count( $this->badItems
) ) {
428 return; // nothing to do
431 $user = $this->getUser();
432 $badItems = $this->badItems
;
433 DeferredUpdates
::addCallableUpdate( function () use ( $user, $badItems ) {
434 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
435 foreach ( $badItems as $row ) {
436 list( $title, $namespace, $dbKey ) = $row;
437 $action = $title ?
'cleaning up' : 'deleting';
438 wfDebug( "User {$user->getName()} has broken watchlist item " .
439 "ns($namespace):$dbKey, $action.\n" );
441 $store->removeWatch( $user, new TitleValue( (int)$namespace, $dbKey ) );
442 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
444 $user->addWatch( $title );
451 * Remove all titles from a user's watchlist
453 private function clearWatchlist() {
454 $dbw = wfGetDB( DB_MASTER
);
457 [ 'wl_user' => $this->getUser()->getId() ],
463 * Add a list of targets to a user's watchlist
465 * @param string[]|LinkTarget[] $targets
467 private function watchTitles( $targets ) {
468 $expandedTargets = [];
469 foreach ( $targets as $target ) {
470 if ( !$target instanceof LinkTarget
) {
472 $target = $this->titleParser
->parseTitle( $target, NS_MAIN
);
474 catch ( MalformedTitleException
$e ) {
479 $ns = $target->getNamespace();
480 $dbKey = $target->getDBkey();
481 $expandedTargets[] = new TitleValue( MWNamespace
::getSubject( $ns ), $dbKey );
482 $expandedTargets[] = new TitleValue( MWNamespace
::getTalk( $ns ), $dbKey );
485 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
492 * Remove a list of titles from a user's watchlist
494 * $titles can be an array of strings or Title objects; the former
495 * is preferred, since Titles are very memory-heavy
497 * @param array $titles Array of strings, or Title objects
499 private function unwatchTitles( $titles ) {
500 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
502 foreach ( $titles as $title ) {
503 if ( !$title instanceof Title
) {
504 $title = Title
::newFromText( $title );
507 if ( $title instanceof Title
) {
508 $store->removeWatch( $this->getUser(), $title->getSubjectPage() );
509 $store->removeWatch( $this->getUser(), $title->getTalkPage() );
511 $page = WikiPage
::factory( $title );
512 Hooks
::run( 'UnwatchArticleComplete', [ $this->getUser(), &$page ] );
517 public function submitNormal( $data ) {
520 foreach ( $data as $titles ) {
521 $this->unwatchTitles( $titles );
522 $removed = array_merge( $removed, $titles );
525 if ( count( $removed ) > 0 ) {
526 $this->successMessage
= $this->msg( 'watchlistedit-normal-done'
527 )->numParams( count( $removed ) )->parse();
528 $this->showTitles( $removed, $this->successMessage
);
537 * Get the standard watchlist editing form
541 protected function getNormalForm() {
547 // Allow subscribers to manipulate the list of watched pages (or use it
548 // to preload lots of details at once)
549 $watchlistInfo = $this->getWatchlistInfo();
551 'WatchlistEditorBeforeFormRender',
555 foreach ( $watchlistInfo as $namespace => $pages ) {
558 foreach ( array_keys( $pages ) as $dbkey ) {
559 $title = Title
::makeTitleSafe( $namespace, $dbkey );
561 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
562 $text = $this->buildRemoveLine( $title );
563 $options[$text] = $title->getPrefixedText();
568 // checkTitle can filter some options out, avoid empty sections
569 if ( count( $options ) > 0 ) {
570 $fields['TitlesNs' . $namespace] = [
571 'class' => 'EditWatchlistCheckboxSeriesField',
572 'options' => $options,
573 'section' => "ns$namespace",
577 $this->cleanupWatchlist();
579 if ( count( $fields ) > 1 && $count > 30 ) {
580 $this->toc
= Linker
::tocIndent();
583 foreach ( $fields as $data ) {
584 # strip out the 'ns' prefix from the section name:
585 $ns = substr( $data['section'], 2 );
587 $nsText = ( $ns == NS_MAIN
)
588 ?
$this->msg( 'blanknamespace' )->escaped()
589 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
590 $this->toc
.= Linker
::tocLine( "editwatchlist-{$data['section']}", $nsText,
591 $this->getLanguage()->formatNum( ++
$tocLength ), 1 ) . Linker
::tocLineEnd();
594 $this->toc
= Linker
::tocList( $this->toc
);
599 $context = new DerivativeContext( $this->getContext() );
600 $context->setTitle( $this->getPageTitle() ); // Remove subpage
601 $form = new EditWatchlistNormalHTMLForm( $fields, $context );
602 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
603 $form->setSubmitDestructive();
605 # 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
606 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
607 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
608 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
609 $form->setSubmitCallback( [ $this, 'submitNormal' ] );
615 * Build the label for a checkbox, with a link to the title, and various additional bits
617 * @param Title $title
620 private function buildRemoveLine( $title ) {
621 $linkRenderer = $this->getLinkRenderer();
622 $link = $linkRenderer->makeLink( $title );
624 $tools['talk'] = $linkRenderer->makeLink(
625 $title->getTalkPage(),
626 $this->msg( 'talkpagelinktext' )->text()
629 if ( $title->exists() ) {
630 $tools['history'] = $linkRenderer->makeKnownLink(
632 $this->msg( 'history_small' )->text(),
634 [ 'action' => 'history' ]
638 if ( $title->getNamespace() == NS_USER
&& !$title->isSubpage() ) {
639 $tools['contributions'] = $linkRenderer->makeKnownLink(
640 SpecialPage
::getTitleFor( 'Contributions', $title->getText() ),
641 $this->msg( 'contributions' )->text()
646 'WatchlistEditorBuildRemoveLine',
647 [ &$tools, $title, $title->isRedirect(), $this->getSkin(), &$link ]
650 if ( $title->isRedirect() ) {
651 // Linker already makes class mw-redirect, so this is redundant
652 $link = '<span class="watchlistredir">' . $link . '</span>';
656 $this->msg( 'parentheses' )->rawParams( $this->getLanguage()->pipeList( $tools ) )->escaped();
660 * Get a form for editing the watchlist in "raw" mode
664 protected function getRawForm() {
665 $titles = implode( $this->getWatchlist(), "\n" );
668 'type' => 'textarea',
669 'label-message' => 'watchlistedit-raw-titles',
670 'default' => $titles,
673 $context = new DerivativeContext( $this->getContext() );
674 $context->setTitle( $this->getPageTitle( 'raw' ) ); // Reset subpage
675 $form = new HTMLForm( $fields, $context );
676 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
677 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
678 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
679 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
680 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
681 $form->setSubmitCallback( [ $this, 'submitRaw' ] );
687 * Get a form for clearing the watchlist
691 protected function getClearForm() {
692 $context = new DerivativeContext( $this->getContext() );
693 $context->setTitle( $this->getPageTitle( 'clear' ) ); // Reset subpage
694 $form = new HTMLForm( [], $context );
695 $form->setSubmitTextMsg( 'watchlistedit-clear-submit' );
696 # Used message keys: 'accesskey-watchlistedit-clear-submit', 'tooltip-watchlistedit-clear-submit'
697 $form->setSubmitTooltip( 'watchlistedit-clear-submit' );
698 $form->setWrapperLegendMsg( 'watchlistedit-clear-legend' );
699 $form->addHeaderText( $this->msg( 'watchlistedit-clear-explain' )->parse() );
700 $form->setSubmitCallback( [ $this, 'submitClear' ] );
701 $form->setSubmitDestructive();
707 * Determine whether we are editing the watchlist, and if so, what
708 * kind of editing operation
710 * @param WebRequest $request
714 public static function getMode( $request, $par ) {
715 $mode = strtolower( $request->getVal( 'action', $par ) );
719 case self
::EDIT_CLEAR
:
720 return self
::EDIT_CLEAR
;
723 return self
::EDIT_RAW
;
725 case self
::EDIT_NORMAL
:
726 return self
::EDIT_NORMAL
;
733 * Build a set of links for convenient navigation
734 * between watchlist viewing and editing modes
736 * @param Language $lang
737 * @param LinkRenderer|null $linkRenderer
740 public static function buildTools( $lang, LinkRenderer
$linkRenderer = null ) {
741 if ( !$lang instanceof Language
) {
742 // back-compat where the first parameter was $unused
746 if ( !$linkRenderer ) {
747 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
752 'view' => [ 'Watchlist', false ],
753 'edit' => [ 'EditWatchlist', false ],
754 'raw' => [ 'EditWatchlist', 'raw' ],
755 'clear' => [ 'EditWatchlist', 'clear' ],
758 foreach ( $modes as $mode => $arr ) {
759 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
760 $tools[] = $linkRenderer->makeKnownLink(
761 SpecialPage
::getTitleFor( $arr[0], $arr[1] ),
762 wfMessage( "watchlisttools-{$mode}" )->text()
766 return Html
::rawElement(
768 [ 'class' => 'mw-watchlist-toollinks' ],
769 wfMessage( 'parentheses' )->rawParams( $lang->pipeList( $tools ) )->escaped()
775 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
777 class EditWatchlistNormalHTMLForm
extends HTMLForm
{
778 public function getLegend( $namespace ) {
779 $namespace = substr( $namespace, 2 );
781 return $namespace == NS_MAIN
782 ?
$this->msg( 'blanknamespace' )->escaped()
783 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
786 public function getBody() {
787 return $this->displaySection( $this->mFieldTree
, '', 'editwatchlist-' );
791 class EditWatchlistCheckboxSeriesField
extends HTMLMultiSelectField
{
793 * HTMLMultiSelectField throws validation errors if we get input data
794 * that doesn't match the data set in the form setup. This causes
795 * problems if something gets removed from the watchlist while the
796 * form is open (bug 32126), but we know that invalid items will
797 * be harmless so we can override it here.
799 * @param string $value The value the field was submitted with
800 * @param array $alldata The data collected from the form
801 * @return bool|string Bool true on success, or String error to display.
803 function validate( $value, $alldata ) {
804 // Need to call into grandparent to be a good citizen. :)
805 return HTMLFormField
::validate( $value, $alldata );