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
);
247 if ( count( $current ) === 0 ) {
251 $this->clearUserWatchedItems( $current, 'raw' );
252 $this->showTitles( $current, $this->successMessage
);
258 public function submitClear( $data ) {
259 $current = $this->getWatchlist();
260 $this->clearUserWatchedItems( $current, 'clear' );
261 $this->showTitles( $current, $this->successMessage
);
266 * @param array $current
267 * @param string $messageFor 'raw' or 'clear'
269 private function clearUserWatchedItems( $current, $messageFor ) {
270 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
271 if ( $watchedItemStore->clearUserWatchedItems( $this->getUser() ) ) {
272 $this->successMessage
= $this->msg( 'watchlistedit-' . $messageFor . '-done' )->parse();
273 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-' . $messageFor . '-removed' )
274 ->numParams( count( $current ) )->parse();
275 $this->getUser()->invalidateCache();
277 $watchedItemStore->clearUserWatchedItemsUsingJobQueue( $this->getUser() );
278 $this->successMessage
= $this->msg( 'watchlistedit-clear-jobqueue' )->parse();
283 * Print out a list of linked titles
285 * $titles can be an array of strings or Title objects; the former
286 * is preferred, since Titles are very memory-heavy
288 * @param array $titles Array of strings, or Title objects
289 * @param string $output
291 private function showTitles( $titles, &$output ) {
292 $talk = $this->msg( 'talkpagelinktext' )->text();
293 // Do a batch existence check
294 $batch = new LinkBatch();
295 if ( count( $titles ) >= 100 ) {
296 $output = $this->msg( 'watchlistedit-too-many' )->parse();
299 foreach ( $titles as $title ) {
300 if ( !$title instanceof Title
) {
301 $title = Title
::newFromText( $title );
304 if ( $title instanceof Title
) {
305 $batch->addObj( $title );
306 $batch->addObj( $title->getTalkPage() );
312 // Print out the list
315 $linkRenderer = $this->getLinkRenderer();
316 foreach ( $titles as $title ) {
317 if ( !$title instanceof Title
) {
318 $title = Title
::newFromText( $title );
321 if ( $title instanceof Title
) {
323 $linkRenderer->makeLink( $title ) . ' ' .
324 $this->msg( 'parentheses' )->rawParams(
325 $linkRenderer->makeLink( $title->getTalkPage(), $talk )
331 $output .= "</ul>\n";
335 * Prepare a list of titles on a user's watchlist (excluding talk pages)
336 * and return an array of (prefixed) strings
340 private function getWatchlist() {
343 $watchedItems = MediaWikiServices
::getInstance()->getWatchedItemStore()->getWatchedItemsForUser(
345 [ 'forWrite' => $this->getRequest()->wasPosted() ]
348 if ( $watchedItems ) {
349 /** @var Title[] $titles */
351 foreach ( $watchedItems as $watchedItem ) {
352 $namespace = $watchedItem->getLinkTarget()->getNamespace();
353 $dbKey = $watchedItem->getLinkTarget()->getDBkey();
354 $title = Title
::makeTitleSafe( $namespace, $dbKey );
356 if ( $this->checkTitle( $title, $namespace, $dbKey )
357 && !$title->isTalkPage()
363 MediaWikiServices
::getInstance()->getGenderCache()->doTitlesArray( $titles );
365 foreach ( $titles as $title ) {
366 $list[] = $title->getPrefixedText();
370 $this->cleanupWatchlist();
376 * Get a list of titles on a user's watchlist, excluding talk pages,
377 * and return as a two-dimensional array with namespace and title.
381 protected function getWatchlistInfo() {
384 $watchedItems = MediaWikiServices
::getInstance()->getWatchedItemStore()
385 ->getWatchedItemsForUser( $this->getUser(), [ 'sort' => WatchedItemStore
::SORT_ASC
] );
387 $lb = new LinkBatch();
389 foreach ( $watchedItems as $watchedItem ) {
390 $namespace = $watchedItem->getLinkTarget()->getNamespace();
391 $dbKey = $watchedItem->getLinkTarget()->getDBkey();
392 $lb->add( $namespace, $dbKey );
393 if ( !MWNamespace
::isTalk( $namespace ) ) {
394 $titles[$namespace][$dbKey] = 1;
404 * Validates watchlist entry
406 * @param Title $title
407 * @param int $namespace
408 * @param string $dbKey
409 * @return bool Whether this item is valid
411 private function checkTitle( $title, $namespace, $dbKey ) {
413 && ( $title->isExternal()
414 ||
$title->getNamespace() < 0
417 $title = false; // unrecoverable
421 ||
$title->getNamespace() != $namespace
422 ||
$title->getDBkey() != $dbKey
424 $this->badItems
[] = [ $title, $namespace, $dbKey ];
431 * Attempts to clean up broken items
433 private function cleanupWatchlist() {
434 if ( !count( $this->badItems
) ) {
435 return; // nothing to do
438 $user = $this->getUser();
439 $badItems = $this->badItems
;
440 DeferredUpdates
::addCallableUpdate( function () use ( $user, $badItems ) {
441 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
442 foreach ( $badItems as $row ) {
443 list( $title, $namespace, $dbKey ) = $row;
444 $action = $title ?
'cleaning up' : 'deleting';
445 wfDebug( "User {$user->getName()} has broken watchlist item " .
446 "ns($namespace):$dbKey, $action.\n" );
448 $store->removeWatch( $user, new TitleValue( (int)$namespace, $dbKey ) );
449 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
451 $user->addWatch( $title );
458 * Add a list of targets to a user's watchlist
460 * @param string[]|LinkTarget[] $targets
462 private function watchTitles( $targets ) {
463 $expandedTargets = [];
464 foreach ( $targets as $target ) {
465 if ( !$target instanceof LinkTarget
) {
467 $target = $this->titleParser
->parseTitle( $target, NS_MAIN
);
469 catch ( MalformedTitleException
$e ) {
474 $ns = $target->getNamespace();
475 $dbKey = $target->getDBkey();
476 $expandedTargets[] = new TitleValue( MWNamespace
::getSubject( $ns ), $dbKey );
477 $expandedTargets[] = new TitleValue( MWNamespace
::getTalk( $ns ), $dbKey );
480 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
487 * Remove a list of titles from a user's watchlist
489 * $titles can be an array of strings or Title objects; the former
490 * is preferred, since Titles are very memory-heavy
492 * @param array $titles Array of strings, or Title objects
494 private function unwatchTitles( $titles ) {
495 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
497 foreach ( $titles as $title ) {
498 if ( !$title instanceof Title
) {
499 $title = Title
::newFromText( $title );
502 if ( $title instanceof Title
) {
503 $store->removeWatch( $this->getUser(), $title->getSubjectPage() );
504 $store->removeWatch( $this->getUser(), $title->getTalkPage() );
506 $page = WikiPage
::factory( $title );
507 Hooks
::run( 'UnwatchArticleComplete', [ $this->getUser(), &$page ] );
512 public function submitNormal( $data ) {
515 foreach ( $data as $titles ) {
516 $this->unwatchTitles( $titles );
517 $removed = array_merge( $removed, $titles );
520 if ( count( $removed ) > 0 ) {
521 $this->successMessage
= $this->msg( 'watchlistedit-normal-done'
522 )->numParams( count( $removed ) )->parse();
523 $this->showTitles( $removed, $this->successMessage
);
532 * Get the standard watchlist editing form
536 protected function getNormalForm() {
542 // Allow subscribers to manipulate the list of watched pages (or use it
543 // to preload lots of details at once)
544 $watchlistInfo = $this->getWatchlistInfo();
546 'WatchlistEditorBeforeFormRender',
550 foreach ( $watchlistInfo as $namespace => $pages ) {
553 foreach ( array_keys( $pages ) as $dbkey ) {
554 $title = Title
::makeTitleSafe( $namespace, $dbkey );
556 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
557 $text = $this->buildRemoveLine( $title );
558 $options[$text] = $title->getPrefixedText();
563 // checkTitle can filter some options out, avoid empty sections
564 if ( count( $options ) > 0 ) {
565 $fields['TitlesNs' . $namespace] = [
566 'class' => EditWatchlistCheckboxSeriesField
::class,
567 'options' => $options,
568 'section' => "ns$namespace",
572 $this->cleanupWatchlist();
574 if ( count( $fields ) > 1 && $count > 30 ) {
575 $this->toc
= Linker
::tocIndent();
578 foreach ( $fields as $data ) {
579 # strip out the 'ns' prefix from the section name:
580 $ns = substr( $data['section'], 2 );
582 $nsText = ( $ns == NS_MAIN
)
583 ?
$this->msg( 'blanknamespace' )->escaped()
584 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
585 $this->toc
.= Linker
::tocLine( "editwatchlist-{$data['section']}", $nsText,
586 $this->getLanguage()->formatNum( ++
$tocLength ), 1 ) . Linker
::tocLineEnd();
589 $this->toc
= Linker
::tocList( $this->toc
);
594 $context = new DerivativeContext( $this->getContext() );
595 $context->setTitle( $this->getPageTitle() ); // Remove subpage
596 $form = new EditWatchlistNormalHTMLForm( $fields, $context );
597 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
598 $form->setSubmitDestructive();
600 # 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
601 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
602 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
603 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
604 $form->setSubmitCallback( [ $this, 'submitNormal' ] );
610 * Build the label for a checkbox, with a link to the title, and various additional bits
612 * @param Title $title
615 private function buildRemoveLine( $title ) {
616 $linkRenderer = $this->getLinkRenderer();
617 $link = $linkRenderer->makeLink( $title );
619 $tools['talk'] = $linkRenderer->makeLink(
620 $title->getTalkPage(),
621 $this->msg( 'talkpagelinktext' )->text()
624 if ( $title->exists() ) {
625 $tools['history'] = $linkRenderer->makeKnownLink(
627 $this->msg( 'history_small' )->text(),
629 [ 'action' => 'history' ]
633 if ( $title->getNamespace() == NS_USER
&& !$title->isSubpage() ) {
634 $tools['contributions'] = $linkRenderer->makeKnownLink(
635 SpecialPage
::getTitleFor( 'Contributions', $title->getText() ),
636 $this->msg( 'contributions' )->text()
641 'WatchlistEditorBuildRemoveLine',
642 [ &$tools, $title, $title->isRedirect(), $this->getSkin(), &$link ]
645 if ( $title->isRedirect() ) {
646 // Linker already makes class mw-redirect, so this is redundant
647 $link = '<span class="watchlistredir">' . $link . '</span>';
651 $this->msg( 'parentheses' )->rawParams( $this->getLanguage()->pipeList( $tools ) )->escaped();
655 * Get a form for editing the watchlist in "raw" mode
659 protected function getRawForm() {
660 $titles = implode( $this->getWatchlist(), "\n" );
663 'type' => 'textarea',
664 'label-message' => 'watchlistedit-raw-titles',
665 'default' => $titles,
668 $context = new DerivativeContext( $this->getContext() );
669 $context->setTitle( $this->getPageTitle( 'raw' ) ); // Reset subpage
670 $form = new HTMLForm( $fields, $context );
671 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
672 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
673 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
674 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
675 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
676 $form->setSubmitCallback( [ $this, 'submitRaw' ] );
682 * Get a form for clearing the watchlist
686 protected function getClearForm() {
687 $context = new DerivativeContext( $this->getContext() );
688 $context->setTitle( $this->getPageTitle( 'clear' ) ); // Reset subpage
689 $form = new HTMLForm( [], $context );
690 $form->setSubmitTextMsg( 'watchlistedit-clear-submit' );
691 # Used message keys: 'accesskey-watchlistedit-clear-submit', 'tooltip-watchlistedit-clear-submit'
692 $form->setSubmitTooltip( 'watchlistedit-clear-submit' );
693 $form->setWrapperLegendMsg( 'watchlistedit-clear-legend' );
694 $form->addHeaderText( $this->msg( 'watchlistedit-clear-explain' )->parse() );
695 $form->setSubmitCallback( [ $this, 'submitClear' ] );
696 $form->setSubmitDestructive();
702 * Determine whether we are editing the watchlist, and if so, what
703 * kind of editing operation
705 * @param WebRequest $request
709 public static function getMode( $request, $par ) {
710 $mode = strtolower( $request->getVal( 'action', $par ) );
714 case self
::EDIT_CLEAR
:
715 return self
::EDIT_CLEAR
;
718 return self
::EDIT_RAW
;
720 case self
::EDIT_NORMAL
:
721 return self
::EDIT_NORMAL
;
728 * Build a set of links for convenient navigation
729 * between watchlist viewing and editing modes
731 * @param Language $lang
732 * @param LinkRenderer|null $linkRenderer
735 public static function buildTools( $lang, LinkRenderer
$linkRenderer = null ) {
736 if ( !$lang instanceof Language
) {
737 // back-compat where the first parameter was $unused
741 if ( !$linkRenderer ) {
742 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
747 'view' => [ 'Watchlist', false ],
748 'edit' => [ 'EditWatchlist', false ],
749 'raw' => [ 'EditWatchlist', 'raw' ],
750 'clear' => [ 'EditWatchlist', 'clear' ],
753 foreach ( $modes as $mode => $arr ) {
754 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
755 $tools[] = $linkRenderer->makeKnownLink(
756 SpecialPage
::getTitleFor( $arr[0], $arr[1] ),
757 wfMessage( "watchlisttools-{$mode}" )->text()
761 return Html
::rawElement(
763 [ 'class' => 'mw-watchlist-toollinks' ],
764 wfMessage( 'parentheses' )->rawParams( $lang->pipeList( $tools ) )->escaped()