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
;
32 use Wikimedia\Rdbms\DBReadOnlyError
;
35 * Provides the UI through which users can perform editing
36 * operations on their watchlist
38 * @ingroup SpecialPage
40 * @author Rob Church <robchur@gmail.com>
42 class SpecialEditWatchlist
extends UnlistedSpecialPage
{
44 * Editing modes. EDIT_CLEAR is no longer used; the "Clear" link scared people
45 * too much. Now it's passed on to the raw editor, from which it's very easy to clear.
49 const EDIT_NORMAL
= 3;
51 protected $successMessage;
55 private $badItems = [];
62 public function __construct() {
63 parent
::__construct( 'EditWatchlist', 'editmywatchlist' );
67 * Initialize any services we'll need (unless it has already been provided via a setter).
68 * This allows for dependency injection even though we don't control object creation.
70 private function initServices() {
71 if ( !$this->titleParser
) {
72 $this->titleParser
= MediaWikiServices
::getInstance()->getTitleParser();
76 public function doesWrites() {
81 * Main execution point
85 public function execute( $mode ) {
86 $this->initServices();
89 # Anons don't get a watchlist
90 $this->requireLogin( 'watchlistanontext' );
92 $out = $this->getOutput();
94 $this->checkPermissions();
95 $this->checkReadOnly();
97 $this->outputHeader();
98 $this->outputSubtitle();
99 $out->addModuleStyles( 'mediawiki.special' );
101 # B/C: $mode used to be waaay down the parameter list, and the first parameter
103 if ( $mode instanceof User
) {
104 $args = func_get_args();
105 if ( count( $args ) >= 4 ) {
109 $mode = self
::getMode( $this->getRequest(), $mode );
113 $out->setPageTitle( $this->msg( 'watchlistedit-raw-title' ) );
114 $form = $this->getRawForm();
115 if ( $form->show() ) {
116 $out->addHTML( $this->successMessage
);
117 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
120 case self
::EDIT_CLEAR
:
121 $out->setPageTitle( $this->msg( 'watchlistedit-clear-title' ) );
122 $form = $this->getClearForm();
123 if ( $form->show() ) {
124 $out->addHTML( $this->successMessage
);
125 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
129 case self
::EDIT_NORMAL
:
131 $this->executeViewEditWatchlist();
137 * Renders a subheader on the watchlist page.
139 protected function outputSubtitle() {
140 $out = $this->getOutput();
141 $out->addSubtitle( $this->msg( 'watchlistfor2', $this->getUser()->getName() )
144 $this->getLanguage(),
145 $this->getLinkRenderer()
152 * Executes an edit mode for the watchlist view, from which you can manage your watchlist
154 protected function executeViewEditWatchlist() {
155 $out = $this->getOutput();
156 $out->setPageTitle( $this->msg( 'watchlistedit-normal-title' ) );
157 $form = $this->getNormalForm();
158 if ( $form->show() ) {
159 $out->addHTML( $this->successMessage
);
160 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
161 } elseif ( $this->toc
!== false ) {
162 $out->prependHTML( $this->toc
);
163 $out->addModules( 'mediawiki.toc' );
168 * Return an array of subpages that this special page will accept.
170 * @see also SpecialWatchlist::getSubpagesForPrefixSearch
171 * @return string[] subpages
173 public function getSubpagesForPrefixSearch() {
174 // SpecialWatchlist uses SpecialEditWatchlist::getMode, so new types should be added
175 // here and there - no 'edit' here, because that the default for this page
183 * Extract a list of titles from a blob of text, returning
184 * (prefixed) strings; unwatchable titles are ignored
186 * @param string $list
189 private function extractTitles( $list ) {
190 $list = explode( "\n", trim( $list ) );
191 if ( !is_array( $list ) ) {
197 foreach ( $list as $text ) {
198 $text = trim( $text );
199 if ( strlen( $text ) > 0 ) {
200 $title = Title
::newFromText( $text );
201 if ( $title instanceof Title
&& $title->isWatchable() ) {
207 MediaWikiServices
::getInstance()->getGenderCache()->doTitlesArray( $titles );
210 /** @var Title $title */
211 foreach ( $titles as $title ) {
212 $list[] = $title->getPrefixedText();
215 return array_unique( $list );
218 public function submitRaw( $data ) {
219 $wanted = $this->extractTitles( $data['Titles'] );
220 $current = $this->getWatchlist();
222 if ( count( $wanted ) > 0 ) {
223 $toWatch = array_diff( $wanted, $current );
224 $toUnwatch = array_diff( $current, $wanted );
225 $this->watchTitles( $toWatch );
226 $this->unwatchTitles( $toUnwatch );
227 $this->getUser()->invalidateCache();
229 if ( count( $toWatch ) > 0 ||
count( $toUnwatch ) > 0 ) {
230 $this->successMessage
= $this->msg( 'watchlistedit-raw-done' )->parse();
235 if ( count( $toWatch ) > 0 ) {
236 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-added' )
237 ->numParams( count( $toWatch ) )->parse();
238 $this->showTitles( $toWatch, $this->successMessage
);
241 if ( count( $toUnwatch ) > 0 ) {
242 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-removed' )
243 ->numParams( count( $toUnwatch ) )->parse();
244 $this->showTitles( $toUnwatch, $this->successMessage
);
247 $this->clearWatchlist();
248 $this->getUser()->invalidateCache();
250 if ( count( $current ) > 0 ) {
251 $this->successMessage
= $this->msg( 'watchlistedit-raw-done' )->parse();
256 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-removed' )
257 ->numParams( count( $current ) )->parse();
258 $this->showTitles( $current, $this->successMessage
);
264 public function submitClear( $data ) {
265 $current = $this->getWatchlist();
266 $this->clearWatchlist();
267 $this->getUser()->invalidateCache();
268 $this->successMessage
= $this->msg( 'watchlistedit-clear-done' )->parse();
269 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-clear-removed' )
270 ->numParams( count( $current ) )->parse();
271 $this->showTitles( $current, $this->successMessage
);
277 * Print out a list of linked titles
279 * $titles can be an array of strings or Title objects; the former
280 * is preferred, since Titles are very memory-heavy
282 * @param array $titles Array of strings, or Title objects
283 * @param string $output
285 private function showTitles( $titles, &$output ) {
286 $talk = $this->msg( 'talkpagelinktext' )->text();
287 // Do a batch existence check
288 $batch = new LinkBatch();
289 if ( count( $titles ) >= 100 ) {
290 $output = $this->msg( 'watchlistedit-too-many' )->parse();
293 foreach ( $titles as $title ) {
294 if ( !$title instanceof Title
) {
295 $title = Title
::newFromText( $title );
298 if ( $title instanceof Title
) {
299 $batch->addObj( $title );
300 $batch->addObj( $title->getTalkPage() );
306 // Print out the list
309 $linkRenderer = $this->getLinkRenderer();
310 foreach ( $titles as $title ) {
311 if ( !$title instanceof Title
) {
312 $title = Title
::newFromText( $title );
315 if ( $title instanceof Title
) {
317 $linkRenderer->makeLink( $title ) . ' ' .
318 $this->msg( 'parentheses' )->rawParams(
319 $linkRenderer->makeLink( $title->getTalkPage(), $talk )
325 $output .= "</ul>\n";
329 * Prepare a list of titles on a user's watchlist (excluding talk pages)
330 * and return an array of (prefixed) strings
334 private function getWatchlist() {
337 $watchedItems = MediaWikiServices
::getInstance()->getWatchedItemStore()->getWatchedItemsForUser(
339 [ 'forWrite' => $this->getRequest()->wasPosted() ]
342 if ( $watchedItems ) {
343 /** @var Title[] $titles */
345 foreach ( $watchedItems as $watchedItem ) {
346 $namespace = $watchedItem->getLinkTarget()->getNamespace();
347 $dbKey = $watchedItem->getLinkTarget()->getDBkey();
348 $title = Title
::makeTitleSafe( $namespace, $dbKey );
350 if ( $this->checkTitle( $title, $namespace, $dbKey )
351 && !$title->isTalkPage()
357 MediaWikiServices
::getInstance()->getGenderCache()->doTitlesArray( $titles );
359 foreach ( $titles as $title ) {
360 $list[] = $title->getPrefixedText();
364 $this->cleanupWatchlist();
370 * Get a list of titles on a user's watchlist, excluding talk pages,
371 * and return as a two-dimensional array with namespace and title.
375 protected function getWatchlistInfo() {
378 $watchedItems = MediaWikiServices
::getInstance()->getWatchedItemStore()
379 ->getWatchedItemsForUser( $this->getUser(), [ 'sort' => WatchedItemStore
::SORT_ASC
] );
381 $lb = new LinkBatch();
383 foreach ( $watchedItems as $watchedItem ) {
384 $namespace = $watchedItem->getLinkTarget()->getNamespace();
385 $dbKey = $watchedItem->getLinkTarget()->getDBkey();
386 $lb->add( $namespace, $dbKey );
387 if ( !MWNamespace
::isTalk( $namespace ) ) {
388 $titles[$namespace][$dbKey] = 1;
398 * Validates watchlist entry
400 * @param Title $title
401 * @param int $namespace
402 * @param string $dbKey
403 * @return bool Whether this item is valid
405 private function checkTitle( $title, $namespace, $dbKey ) {
407 && ( $title->isExternal()
408 ||
$title->getNamespace() < 0
411 $title = false; // unrecoverable
415 ||
$title->getNamespace() != $namespace
416 ||
$title->getDBkey() != $dbKey
418 $this->badItems
[] = [ $title, $namespace, $dbKey ];
425 * Attempts to clean up broken items
427 private function cleanupWatchlist() {
428 if ( !count( $this->badItems
) ) {
429 return; // nothing to do
432 $user = $this->getUser();
433 $badItems = $this->badItems
;
434 DeferredUpdates
::addCallableUpdate( function () use ( $user, $badItems ) {
435 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
436 foreach ( $badItems as $row ) {
437 list( $title, $namespace, $dbKey ) = $row;
438 $action = $title ?
'cleaning up' : 'deleting';
439 wfDebug( "User {$user->getName()} has broken watchlist item " .
440 "ns($namespace):$dbKey, $action.\n" );
442 $store->removeWatch( $user, new TitleValue( (int)$namespace, $dbKey ) );
443 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
445 $user->addWatch( $title );
452 * Remove all titles from a user's watchlist
454 private function clearWatchlist() {
455 if ( $this->getConfig()->get( 'ReadOnlyWatchedItemStore' ) ) {
456 throw new DBReadOnlyError( null, 'The watchlist is currently readonly.' );
459 $dbw = wfGetDB( DB_MASTER
);
462 [ 'wl_user' => $this->getUser()->getId() ],
468 * Add a list of targets to a user's watchlist
470 * @param string[]|LinkTarget[] $targets
472 private function watchTitles( $targets ) {
473 $expandedTargets = [];
474 foreach ( $targets as $target ) {
475 if ( !$target instanceof LinkTarget
) {
477 $target = $this->titleParser
->parseTitle( $target, NS_MAIN
);
479 catch ( MalformedTitleException
$e ) {
484 $ns = $target->getNamespace();
485 $dbKey = $target->getDBkey();
486 $expandedTargets[] = new TitleValue( MWNamespace
::getSubject( $ns ), $dbKey );
487 $expandedTargets[] = new TitleValue( MWNamespace
::getTalk( $ns ), $dbKey );
490 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
497 * Remove a list of titles from a user's watchlist
499 * $titles can be an array of strings or Title objects; the former
500 * is preferred, since Titles are very memory-heavy
502 * @param array $titles Array of strings, or Title objects
504 private function unwatchTitles( $titles ) {
505 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
507 foreach ( $titles as $title ) {
508 if ( !$title instanceof Title
) {
509 $title = Title
::newFromText( $title );
512 if ( $title instanceof Title
) {
513 $store->removeWatch( $this->getUser(), $title->getSubjectPage() );
514 $store->removeWatch( $this->getUser(), $title->getTalkPage() );
516 $page = WikiPage
::factory( $title );
517 Hooks
::run( 'UnwatchArticleComplete', [ $this->getUser(), &$page ] );
522 public function submitNormal( $data ) {
525 foreach ( $data as $titles ) {
526 $this->unwatchTitles( $titles );
527 $removed = array_merge( $removed, $titles );
530 if ( count( $removed ) > 0 ) {
531 $this->successMessage
= $this->msg( 'watchlistedit-normal-done'
532 )->numParams( count( $removed ) )->parse();
533 $this->showTitles( $removed, $this->successMessage
);
542 * Get the standard watchlist editing form
546 protected function getNormalForm() {
552 // Allow subscribers to manipulate the list of watched pages (or use it
553 // to preload lots of details at once)
554 $watchlistInfo = $this->getWatchlistInfo();
556 'WatchlistEditorBeforeFormRender',
560 foreach ( $watchlistInfo as $namespace => $pages ) {
563 foreach ( array_keys( $pages ) as $dbkey ) {
564 $title = Title
::makeTitleSafe( $namespace, $dbkey );
566 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
567 $text = $this->buildRemoveLine( $title );
568 $options[$text] = $title->getPrefixedText();
573 // checkTitle can filter some options out, avoid empty sections
574 if ( count( $options ) > 0 ) {
575 $fields['TitlesNs' . $namespace] = [
576 'class' => EditWatchlistCheckboxSeriesField
::class,
577 'options' => $options,
578 'section' => "ns$namespace",
582 $this->cleanupWatchlist();
584 if ( count( $fields ) > 1 && $count > 30 ) {
585 $this->toc
= Linker
::tocIndent();
588 foreach ( $fields as $data ) {
589 # strip out the 'ns' prefix from the section name:
590 $ns = substr( $data['section'], 2 );
592 $nsText = ( $ns == NS_MAIN
)
593 ?
$this->msg( 'blanknamespace' )->escaped()
594 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
595 $this->toc
.= Linker
::tocLine( "editwatchlist-{$data['section']}", $nsText,
596 $this->getLanguage()->formatNum( ++
$tocLength ), 1 ) . Linker
::tocLineEnd();
599 $this->toc
= Linker
::tocList( $this->toc
);
604 $context = new DerivativeContext( $this->getContext() );
605 $context->setTitle( $this->getPageTitle() ); // Remove subpage
606 $form = new EditWatchlistNormalHTMLForm( $fields, $context );
607 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
608 $form->setSubmitDestructive();
610 # 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
611 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
612 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
613 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
614 $form->setSubmitCallback( [ $this, 'submitNormal' ] );
620 * Build the label for a checkbox, with a link to the title, and various additional bits
622 * @param Title $title
625 private function buildRemoveLine( $title ) {
626 $linkRenderer = $this->getLinkRenderer();
627 $link = $linkRenderer->makeLink( $title );
629 $tools['talk'] = $linkRenderer->makeLink(
630 $title->getTalkPage(),
631 $this->msg( 'talkpagelinktext' )->text()
634 if ( $title->exists() ) {
635 $tools['history'] = $linkRenderer->makeKnownLink(
637 $this->msg( 'history_small' )->text(),
639 [ 'action' => 'history' ]
643 if ( $title->getNamespace() == NS_USER
&& !$title->isSubpage() ) {
644 $tools['contributions'] = $linkRenderer->makeKnownLink(
645 SpecialPage
::getTitleFor( 'Contributions', $title->getText() ),
646 $this->msg( 'contributions' )->text()
651 'WatchlistEditorBuildRemoveLine',
652 [ &$tools, $title, $title->isRedirect(), $this->getSkin(), &$link ]
655 if ( $title->isRedirect() ) {
656 // Linker already makes class mw-redirect, so this is redundant
657 $link = '<span class="watchlistredir">' . $link . '</span>';
661 $this->msg( 'parentheses' )->rawParams( $this->getLanguage()->pipeList( $tools ) )->escaped();
665 * Get a form for editing the watchlist in "raw" mode
669 protected function getRawForm() {
670 $titles = implode( $this->getWatchlist(), "\n" );
673 'type' => 'textarea',
674 'label-message' => 'watchlistedit-raw-titles',
675 'default' => $titles,
678 $context = new DerivativeContext( $this->getContext() );
679 $context->setTitle( $this->getPageTitle( 'raw' ) ); // Reset subpage
680 $form = new HTMLForm( $fields, $context );
681 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
682 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
683 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
684 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
685 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
686 $form->setSubmitCallback( [ $this, 'submitRaw' ] );
692 * Get a form for clearing the watchlist
696 protected function getClearForm() {
697 $context = new DerivativeContext( $this->getContext() );
698 $context->setTitle( $this->getPageTitle( 'clear' ) ); // Reset subpage
699 $form = new HTMLForm( [], $context );
700 $form->setSubmitTextMsg( 'watchlistedit-clear-submit' );
701 # Used message keys: 'accesskey-watchlistedit-clear-submit', 'tooltip-watchlistedit-clear-submit'
702 $form->setSubmitTooltip( 'watchlistedit-clear-submit' );
703 $form->setWrapperLegendMsg( 'watchlistedit-clear-legend' );
704 $form->addHeaderText( $this->msg( 'watchlistedit-clear-explain' )->parse() );
705 $form->setSubmitCallback( [ $this, 'submitClear' ] );
706 $form->setSubmitDestructive();
712 * Determine whether we are editing the watchlist, and if so, what
713 * kind of editing operation
715 * @param WebRequest $request
719 public static function getMode( $request, $par ) {
720 $mode = strtolower( $request->getVal( 'action', $par ) );
724 case self
::EDIT_CLEAR
:
725 return self
::EDIT_CLEAR
;
728 return self
::EDIT_RAW
;
730 case self
::EDIT_NORMAL
:
731 return self
::EDIT_NORMAL
;
738 * Build a set of links for convenient navigation
739 * between watchlist viewing and editing modes
741 * @param Language $lang
742 * @param LinkRenderer|null $linkRenderer
745 public static function buildTools( $lang, LinkRenderer
$linkRenderer = null ) {
746 if ( !$lang instanceof Language
) {
747 // back-compat where the first parameter was $unused
751 if ( !$linkRenderer ) {
752 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
757 'view' => [ 'Watchlist', false ],
758 'edit' => [ 'EditWatchlist', false ],
759 'raw' => [ 'EditWatchlist', 'raw' ],
760 'clear' => [ 'EditWatchlist', 'clear' ],
763 foreach ( $modes as $mode => $arr ) {
764 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
765 $tools[] = $linkRenderer->makeKnownLink(
766 SpecialPage
::getTitleFor( $arr[0], $arr[1] ),
767 wfMessage( "watchlisttools-{$mode}" )->text()
771 return Html
::rawElement(
773 [ 'class' => 'mw-watchlist-toollinks' ],
774 wfMessage( 'parentheses' )->rawParams( $lang->pipeList( $tools ) )->escaped()