3 * @defgroup Watchlist Users watchlist handling
5 use MediaWiki\Linker\LinkTarget
;
8 * Implements Special:EditWatchlist
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 * @ingroup SpecialPage
30 use MediaWiki\MediaWikiServices
;
33 * Provides the UI through which users can perform editing
34 * operations on their watchlist
36 * @ingroup SpecialPage
38 * @author Rob Church <robchur@gmail.com>
40 class SpecialEditWatchlist
extends UnlistedSpecialPage
{
42 * Editing modes. EDIT_CLEAR is no longer used; the "Clear" link scared people
43 * too much. Now it's passed on to the raw editor, from which it's very easy to clear.
47 const EDIT_NORMAL
= 3;
49 protected $successMessage;
53 private $badItems = [];
60 public function __construct() {
61 parent
::__construct( 'EditWatchlist', 'editmywatchlist' );
65 * Initialize any services we'll need (unless it has already been provided via a setter).
66 * This allows for dependency injection even though we don't control object creation.
68 private function initServices() {
69 if ( !$this->titleParser
) {
70 $lang = $this->getContext()->getLanguage();
71 $this->titleParser
= new MediaWikiTitleCodec( $lang, GenderCache
::singleton() );
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() )
141 ->rawParams( SpecialEditWatchlist
::buildTools( null ) ) );
145 * Executes an edit mode for the watchlist view, from which you can manage your watchlist
148 protected function executeViewEditWatchlist() {
149 $out = $this->getOutput();
150 $out->setPageTitle( $this->msg( 'watchlistedit-normal-title' ) );
151 $form = $this->getNormalForm();
152 if ( $form->show() ) {
153 $out->addHTML( $this->successMessage
);
154 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
155 } elseif ( $this->toc
!== false ) {
156 $out->prependHTML( $this->toc
);
157 $out->addModules( 'mediawiki.toc' );
162 * Return an array of subpages that this special page will accept.
164 * @see also SpecialWatchlist::getSubpagesForPrefixSearch
165 * @return string[] subpages
167 public function getSubpagesForPrefixSearch() {
168 // SpecialWatchlist uses SpecialEditWatchlist::getMode, so new types should be added
169 // here and there - no 'edit' here, because that the default for this page
177 * Extract a list of titles from a blob of text, returning
178 * (prefixed) strings; unwatchable titles are ignored
180 * @param string $list
183 private function extractTitles( $list ) {
184 $list = explode( "\n", trim( $list ) );
185 if ( !is_array( $list ) ) {
191 foreach ( $list as $text ) {
192 $text = trim( $text );
193 if ( strlen( $text ) > 0 ) {
194 $title = Title
::newFromText( $text );
195 if ( $title instanceof Title
&& $title->isWatchable() ) {
201 GenderCache
::singleton()->doTitlesArray( $titles );
204 /** @var Title $title */
205 foreach ( $titles as $title ) {
206 $list[] = $title->getPrefixedText();
209 return array_unique( $list );
212 public function submitRaw( $data ) {
213 $wanted = $this->extractTitles( $data['Titles'] );
214 $current = $this->getWatchlist();
216 if ( count( $wanted ) > 0 ) {
217 $toWatch = array_diff( $wanted, $current );
218 $toUnwatch = array_diff( $current, $wanted );
219 $this->watchTitles( $toWatch );
220 $this->unwatchTitles( $toUnwatch );
221 $this->getUser()->invalidateCache();
223 if ( count( $toWatch ) > 0 ||
count( $toUnwatch ) > 0 ) {
224 $this->successMessage
= $this->msg( 'watchlistedit-raw-done' )->parse();
229 if ( count( $toWatch ) > 0 ) {
230 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-added' )
231 ->numParams( count( $toWatch ) )->parse();
232 $this->showTitles( $toWatch, $this->successMessage
);
235 if ( count( $toUnwatch ) > 0 ) {
236 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-removed' )
237 ->numParams( count( $toUnwatch ) )->parse();
238 $this->showTitles( $toUnwatch, $this->successMessage
);
241 $this->clearWatchlist();
242 $this->getUser()->invalidateCache();
244 if ( count( $current ) > 0 ) {
245 $this->successMessage
= $this->msg( 'watchlistedit-raw-done' )->parse();
250 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-removed' )
251 ->numParams( count( $current ) )->parse();
252 $this->showTitles( $current, $this->successMessage
);
258 public function submitClear( $data ) {
259 $current = $this->getWatchlist();
260 $this->clearWatchlist();
261 $this->getUser()->invalidateCache();
262 $this->successMessage
= $this->msg( 'watchlistedit-clear-done' )->parse();
263 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-clear-removed' )
264 ->numParams( count( $current ) )->parse();
265 $this->showTitles( $current, $this->successMessage
);
271 * Print out a list of linked titles
273 * $titles can be an array of strings or Title objects; the former
274 * is preferred, since Titles are very memory-heavy
276 * @param array $titles Array of strings, or Title objects
277 * @param string $output
279 private function showTitles( $titles, &$output ) {
280 $talk = $this->msg( 'talkpagelinktext' )->escaped();
281 // Do a batch existence check
282 $batch = new LinkBatch();
283 if ( count( $titles ) >= 100 ) {
284 $output = $this->msg( 'watchlistedit-too-many' )->parse();
287 foreach ( $titles as $title ) {
288 if ( !$title instanceof Title
) {
289 $title = Title
::newFromText( $title );
292 if ( $title instanceof Title
) {
293 $batch->addObj( $title );
294 $batch->addObj( $title->getTalkPage() );
300 // Print out the list
303 foreach ( $titles as $title ) {
304 if ( !$title instanceof Title
) {
305 $title = Title
::newFromText( $title );
308 if ( $title instanceof Title
) {
310 Linker
::link( $title ) . ' ' .
311 $this->msg( 'parentheses' )->rawParams(
312 Linker
::link( $title->getTalkPage(), $talk )
318 $output .= "</ul>\n";
322 * Prepare a list of titles on a user's watchlist (excluding talk pages)
323 * and return an array of (prefixed) strings
327 private function getWatchlist() {
330 $watchedItems = MediaWikiServices
::getInstance()->getWatchedItemStore()->getWatchedItemsForUser(
332 [ 'forWrite' => $this->getRequest()->wasPosted() ]
335 if ( $watchedItems ) {
336 /** @var Title[] $titles */
338 foreach ( $watchedItems as $watchedItem ) {
339 $namespace = $watchedItem->getLinkTarget()->getNamespace();
340 $dbKey = $watchedItem->getLinkTarget()->getDBkey();
341 $title = Title
::makeTitleSafe( $namespace, $dbKey );
343 if ( $this->checkTitle( $title, $namespace, $dbKey )
344 && !$title->isTalkPage()
350 GenderCache
::singleton()->doTitlesArray( $titles );
352 foreach ( $titles as $title ) {
353 $list[] = $title->getPrefixedText();
357 $this->cleanupWatchlist();
363 * Get a list of titles on a user's watchlist, excluding talk pages,
364 * and return as a two-dimensional array with namespace and title.
368 protected function getWatchlistInfo() {
371 $watchedItems = MediaWikiServices
::getInstance()->getWatchedItemStore()
372 ->getWatchedItemsForUser( $this->getUser(), [ 'sort' => WatchedItemStore
::SORT_ASC
] );
374 $lb = new LinkBatch();
376 foreach ( $watchedItems as $watchedItem ) {
377 $namespace = $watchedItem->getLinkTarget()->getNamespace();
378 $dbKey = $watchedItem->getLinkTarget()->getDBkey();
379 $lb->add( $namespace, $dbKey );
380 if ( !MWNamespace
::isTalk( $namespace ) ) {
381 $titles[$namespace][$dbKey] = 1;
391 * Validates watchlist entry
393 * @param Title $title
394 * @param int $namespace
395 * @param string $dbKey
396 * @return bool Whether this item is valid
398 private function checkTitle( $title, $namespace, $dbKey ) {
400 && ( $title->isExternal()
401 ||
$title->getNamespace() < 0
404 $title = false; // unrecoverable
408 ||
$title->getNamespace() != $namespace
409 ||
$title->getDBkey() != $dbKey
411 $this->badItems
[] = [ $title, $namespace, $dbKey ];
418 * Attempts to clean up broken items
420 private function cleanupWatchlist() {
421 if ( !count( $this->badItems
) ) {
422 return; // nothing to do
425 $user = $this->getUser();
426 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
428 foreach ( $this->badItems
as $row ) {
429 list( $title, $namespace, $dbKey ) = $row;
430 $action = $title ?
'cleaning up' : 'deleting';
431 wfDebug( "User {$user->getName()} has broken watchlist item ns($namespace):$dbKey, $action.\n" );
433 $store->removeWatch( $user, new TitleValue( (int)$namespace, $dbKey ) );
435 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
437 $user->addWatch( $title );
443 * Remove all titles from a user's watchlist
445 private function clearWatchlist() {
446 $dbw = wfGetDB( DB_MASTER
);
449 [ 'wl_user' => $this->getUser()->getId() ],
455 * Add a list of targets to a user's watchlist
457 * @param string[]|LinkTarget[] $targets
459 private function watchTitles( $targets ) {
460 $expandedTargets = [];
461 foreach ( $targets as $target ) {
462 if ( !$target instanceof LinkTarget
) {
464 $target = $this->titleParser
->parseTitle( $target, NS_MAIN
);
466 catch ( MalformedTitleException
$e ) {
471 $ns = $target->getNamespace();
472 $dbKey = $target->getDBkey();
473 $expandedTargets[] = new TitleValue( MWNamespace
::getSubject( $ns ), $dbKey );
474 $expandedTargets[] = new TitleValue( MWNamespace
::getTalk( $ns ), $dbKey );
477 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
484 * Remove a list of titles from a user's watchlist
486 * $titles can be an array of strings or Title objects; the former
487 * is preferred, since Titles are very memory-heavy
489 * @param array $titles Array of strings, or Title objects
491 private function unwatchTitles( $titles ) {
492 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
494 foreach ( $titles as $title ) {
495 if ( !$title instanceof Title
) {
496 $title = Title
::newFromText( $title );
499 if ( $title instanceof Title
) {
500 $store->removeWatch( $this->getUser(), $title->getSubjectPage() );
501 $store->removeWatch( $this->getUser(), $title->getTalkPage() );
503 $page = WikiPage
::factory( $title );
504 Hooks
::run( 'UnwatchArticleComplete', [ $this->getUser(), &$page ] );
509 public function submitNormal( $data ) {
512 foreach ( $data as $titles ) {
513 $this->unwatchTitles( $titles );
514 $removed = array_merge( $removed, $titles );
517 if ( count( $removed ) > 0 ) {
518 $this->successMessage
= $this->msg( 'watchlistedit-normal-done'
519 )->numParams( count( $removed ) )->parse();
520 $this->showTitles( $removed, $this->successMessage
);
529 * Get the standard watchlist editing form
533 protected function getNormalForm() {
539 // Allow subscribers to manipulate the list of watched pages (or use it
540 // to preload lots of details at once)
541 $watchlistInfo = $this->getWatchlistInfo();
543 'WatchlistEditorBeforeFormRender',
547 foreach ( $watchlistInfo as $namespace => $pages ) {
550 foreach ( array_keys( $pages ) as $dbkey ) {
551 $title = Title
::makeTitleSafe( $namespace, $dbkey );
553 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
554 $text = $this->buildRemoveLine( $title );
555 $options[$text] = $title->getPrefixedText();
560 // checkTitle can filter some options out, avoid empty sections
561 if ( count( $options ) > 0 ) {
562 $fields['TitlesNs' . $namespace] = [
563 'class' => 'EditWatchlistCheckboxSeriesField',
564 'options' => $options,
565 'section' => "ns$namespace",
569 $this->cleanupWatchlist();
571 if ( count( $fields ) > 1 && $count > 30 ) {
572 $this->toc
= Linker
::tocIndent();
575 foreach ( $fields as $data ) {
576 # strip out the 'ns' prefix from the section name:
577 $ns = substr( $data['section'], 2 );
579 $nsText = ( $ns == NS_MAIN
)
580 ?
$this->msg( 'blanknamespace' )->escaped()
581 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
582 $this->toc
.= Linker
::tocLine( "editwatchlist-{$data['section']}", $nsText,
583 $this->getLanguage()->formatNum( ++
$tocLength ), 1 ) . Linker
::tocLineEnd();
586 $this->toc
= Linker
::tocList( $this->toc
);
591 $context = new DerivativeContext( $this->getContext() );
592 $context->setTitle( $this->getPageTitle() ); // Remove subpage
593 $form = new EditWatchlistNormalHTMLForm( $fields, $context );
594 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
595 $form->setSubmitDestructive();
597 # 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
598 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
599 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
600 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
601 $form->setSubmitCallback( [ $this, 'submitNormal' ] );
607 * Build the label for a checkbox, with a link to the title, and various additional bits
609 * @param Title $title
612 private function buildRemoveLine( $title ) {
613 $link = Linker
::link( $title );
615 $tools['talk'] = Linker
::link(
616 $title->getTalkPage(),
617 $this->msg( 'talkpagelinktext' )->escaped()
620 if ( $title->exists() ) {
621 $tools['history'] = Linker
::linkKnown(
623 $this->msg( 'history_short' )->escaped(),
625 [ 'action' => 'history' ]
629 if ( $title->getNamespace() == NS_USER
&& !$title->isSubpage() ) {
630 $tools['contributions'] = Linker
::linkKnown(
631 SpecialPage
::getTitleFor( 'Contributions', $title->getText() ),
632 $this->msg( 'contributions' )->escaped()
637 'WatchlistEditorBuildRemoveLine',
638 [ &$tools, $title, $title->isRedirect(), $this->getSkin(), &$link ]
641 if ( $title->isRedirect() ) {
642 // Linker already makes class mw-redirect, so this is redundant
643 $link = '<span class="watchlistredir">' . $link . '</span>';
647 $this->msg( 'parentheses' )->rawParams( $this->getLanguage()->pipeList( $tools ) )->escaped();
651 * Get a form for editing the watchlist in "raw" mode
655 protected function getRawForm() {
656 $titles = implode( $this->getWatchlist(), "\n" );
659 'type' => 'textarea',
660 'label-message' => 'watchlistedit-raw-titles',
661 'default' => $titles,
664 $context = new DerivativeContext( $this->getContext() );
665 $context->setTitle( $this->getPageTitle( 'raw' ) ); // Reset subpage
666 $form = new HTMLForm( $fields, $context );
667 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
668 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
669 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
670 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
671 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
672 $form->setSubmitCallback( [ $this, 'submitRaw' ] );
678 * Get a form for clearing the watchlist
682 protected function getClearForm() {
683 $context = new DerivativeContext( $this->getContext() );
684 $context->setTitle( $this->getPageTitle( 'clear' ) ); // Reset subpage
685 $form = new HTMLForm( [], $context );
686 $form->setSubmitTextMsg( 'watchlistedit-clear-submit' );
687 # Used message keys: 'accesskey-watchlistedit-clear-submit', 'tooltip-watchlistedit-clear-submit'
688 $form->setSubmitTooltip( 'watchlistedit-clear-submit' );
689 $form->setWrapperLegendMsg( 'watchlistedit-clear-legend' );
690 $form->addHeaderText( $this->msg( 'watchlistedit-clear-explain' )->parse() );
691 $form->setSubmitCallback( [ $this, 'submitClear' ] );
692 $form->setSubmitDestructive();
698 * Determine whether we are editing the watchlist, and if so, what
699 * kind of editing operation
701 * @param WebRequest $request
705 public static function getMode( $request, $par ) {
706 $mode = strtolower( $request->getVal( 'action', $par ) );
710 case self
::EDIT_CLEAR
:
711 return self
::EDIT_CLEAR
;
714 return self
::EDIT_RAW
;
716 case self
::EDIT_NORMAL
:
717 return self
::EDIT_NORMAL
;
724 * Build a set of links for convenient navigation
725 * between watchlist viewing and editing modes
727 * @param null $unused
730 public static function buildTools( $unused ) {
735 'view' => [ 'Watchlist', false ],
736 'edit' => [ 'EditWatchlist', false ],
737 'raw' => [ 'EditWatchlist', 'raw' ],
738 'clear' => [ 'EditWatchlist', 'clear' ],
741 foreach ( $modes as $mode => $arr ) {
742 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
743 $tools[] = Linker
::linkKnown(
744 SpecialPage
::getTitleFor( $arr[0], $arr[1] ),
745 wfMessage( "watchlisttools-{$mode}" )->escaped()
749 return Html
::rawElement(
751 [ 'class' => 'mw-watchlist-toollinks' ],
752 wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $tools ) )->escaped()
758 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
760 class EditWatchlistNormalHTMLForm
extends HTMLForm
{
761 public function getLegend( $namespace ) {
762 $namespace = substr( $namespace, 2 );
764 return $namespace == NS_MAIN
765 ?
$this->msg( 'blanknamespace' )->escaped()
766 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
769 public function getBody() {
770 return $this->displaySection( $this->mFieldTree
, '', 'editwatchlist-' );
774 class EditWatchlistCheckboxSeriesField
extends HTMLMultiSelectField
{
776 * HTMLMultiSelectField throws validation errors if we get input data
777 * that doesn't match the data set in the form setup. This causes
778 * problems if something gets removed from the watchlist while the
779 * form is open (bug 32126), but we know that invalid items will
780 * be harmless so we can override it here.
782 * @param string $value The value the field was submitted with
783 * @param array $alldata The data collected from the form
784 * @return bool|string Bool true on success, or String error to display.
786 function validate( $value, $alldata ) {
787 // Need to call into grandparent to be a good citizen. :)
788 return HTMLFormField
::validate( $value, $alldata );