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
30 * Provides the UI through which users can perform editing
31 * operations on their watchlist
33 * @ingroup SpecialPage
35 * @author Rob Church <robchur@gmail.com>
37 class SpecialEditWatchlist
extends UnlistedSpecialPage
{
39 * Editing modes. EDIT_CLEAR is no longer used; the "Clear" link scared people
40 * too much. Now it's passed on to the raw editor, from which it's very easy to clear.
44 const EDIT_NORMAL
= 3;
46 protected $successMessage;
50 private $badItems = [];
57 public function __construct() {
58 parent
::__construct( 'EditWatchlist', 'editmywatchlist' );
62 * Initialize any services we'll need (unless it has already been provided via a setter).
63 * This allows for dependency injection even though we don't control object creation.
65 private function initServices() {
66 if ( !$this->titleParser
) {
67 $lang = $this->getContext()->getLanguage();
68 $this->titleParser
= new MediaWikiTitleCodec( $lang, GenderCache
::singleton() );
72 public function doesWrites() {
77 * Main execution point
81 public function execute( $mode ) {
82 $this->initServices();
85 # Anons don't get a watchlist
86 $this->requireLogin( 'watchlistanontext' );
88 $out = $this->getOutput();
90 $this->checkPermissions();
91 $this->checkReadOnly();
93 $this->outputHeader();
94 $this->outputSubtitle();
95 $out->addModuleStyles( 'mediawiki.special' );
97 # B/C: $mode used to be waaay down the parameter list, and the first parameter
99 if ( $mode instanceof User
) {
100 $args = func_get_args();
101 if ( count( $args ) >= 4 ) {
105 $mode = self
::getMode( $this->getRequest(), $mode );
109 $out->setPageTitle( $this->msg( 'watchlistedit-raw-title' ) );
110 $form = $this->getRawForm();
111 if ( $form->show() ) {
112 $out->addHTML( $this->successMessage
);
113 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
116 case self
::EDIT_CLEAR
:
117 $out->setPageTitle( $this->msg( 'watchlistedit-clear-title' ) );
118 $form = $this->getClearForm();
119 if ( $form->show() ) {
120 $out->addHTML( $this->successMessage
);
121 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
125 case self
::EDIT_NORMAL
:
127 $this->executeViewEditWatchlist();
133 * Renders a subheader on the watchlist page.
135 protected function outputSubtitle() {
136 $out = $this->getOutput();
137 $out->addSubtitle( $this->msg( 'watchlistfor2', $this->getUser()->getName() )
138 ->rawParams( SpecialEditWatchlist
::buildTools( null ) ) );
142 * Executes an edit mode for the watchlist view, from which you can manage your watchlist
145 protected function executeViewEditWatchlist() {
146 $out = $this->getOutput();
147 $out->setPageTitle( $this->msg( 'watchlistedit-normal-title' ) );
148 $form = $this->getNormalForm();
149 if ( $form->show() ) {
150 $out->addHTML( $this->successMessage
);
151 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
152 } elseif ( $this->toc
!== false ) {
153 $out->prependHTML( $this->toc
);
154 $out->addModules( 'mediawiki.toc' );
159 * Return an array of subpages that this special page will accept.
161 * @see also SpecialWatchlist::getSubpagesForPrefixSearch
162 * @return string[] subpages
164 public function getSubpagesForPrefixSearch() {
165 // SpecialWatchlist uses SpecialEditWatchlist::getMode, so new types should be added
166 // here and there - no 'edit' here, because that the default for this page
174 * Extract a list of titles from a blob of text, returning
175 * (prefixed) strings; unwatchable titles are ignored
177 * @param string $list
180 private function extractTitles( $list ) {
181 $list = explode( "\n", trim( $list ) );
182 if ( !is_array( $list ) ) {
188 foreach ( $list as $text ) {
189 $text = trim( $text );
190 if ( strlen( $text ) > 0 ) {
191 $title = Title
::newFromText( $text );
192 if ( $title instanceof Title
&& $title->isWatchable() ) {
198 GenderCache
::singleton()->doTitlesArray( $titles );
201 /** @var Title $title */
202 foreach ( $titles as $title ) {
203 $list[] = $title->getPrefixedText();
206 return array_unique( $list );
209 public function submitRaw( $data ) {
210 $wanted = $this->extractTitles( $data['Titles'] );
211 $current = $this->getWatchlist();
213 if ( count( $wanted ) > 0 ) {
214 $toWatch = array_diff( $wanted, $current );
215 $toUnwatch = array_diff( $current, $wanted );
216 $this->watchTitles( $toWatch );
217 $this->unwatchTitles( $toUnwatch );
218 $this->getUser()->invalidateCache();
220 if ( count( $toWatch ) > 0 ||
count( $toUnwatch ) > 0 ) {
221 $this->successMessage
= $this->msg( 'watchlistedit-raw-done' )->parse();
226 if ( count( $toWatch ) > 0 ) {
227 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-added' )
228 ->numParams( count( $toWatch ) )->parse();
229 $this->showTitles( $toWatch, $this->successMessage
);
232 if ( count( $toUnwatch ) > 0 ) {
233 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-removed' )
234 ->numParams( count( $toUnwatch ) )->parse();
235 $this->showTitles( $toUnwatch, $this->successMessage
);
238 $this->clearWatchlist();
239 $this->getUser()->invalidateCache();
241 if ( count( $current ) > 0 ) {
242 $this->successMessage
= $this->msg( 'watchlistedit-raw-done' )->parse();
247 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-removed' )
248 ->numParams( count( $current ) )->parse();
249 $this->showTitles( $current, $this->successMessage
);
255 public function submitClear( $data ) {
256 $current = $this->getWatchlist();
257 $this->clearWatchlist();
258 $this->getUser()->invalidateCache();
259 $this->successMessage
= $this->msg( 'watchlistedit-clear-done' )->parse();
260 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-clear-removed' )
261 ->numParams( count( $current ) )->parse();
262 $this->showTitles( $current, $this->successMessage
);
268 * Print out a list of linked titles
270 * $titles can be an array of strings or Title objects; the former
271 * is preferred, since Titles are very memory-heavy
273 * @param array $titles Array of strings, or Title objects
274 * @param string $output
276 private function showTitles( $titles, &$output ) {
277 $talk = $this->msg( 'talkpagelinktext' )->escaped();
278 // Do a batch existence check
279 $batch = new LinkBatch();
280 if ( count( $titles ) >= 100 ) {
281 $output = $this->msg( 'watchlistedit-too-many' )->parse();
284 foreach ( $titles as $title ) {
285 if ( !$title instanceof Title
) {
286 $title = Title
::newFromText( $title );
289 if ( $title instanceof Title
) {
290 $batch->addObj( $title );
291 $batch->addObj( $title->getTalkPage() );
297 // Print out the list
300 foreach ( $titles as $title ) {
301 if ( !$title instanceof Title
) {
302 $title = Title
::newFromText( $title );
305 if ( $title instanceof Title
) {
307 Linker
::link( $title ) . ' ' .
308 $this->msg( 'parentheses' )->rawParams(
309 Linker
::link( $title->getTalkPage(), $talk )
315 $output .= "</ul>\n";
319 * Prepare a list of titles on a user's watchlist (excluding talk pages)
320 * and return an array of (prefixed) strings
324 private function getWatchlist() {
327 $watchedItems = WatchedItemStore
::getDefaultInstance()->getWatchedItemsForUser(
329 [ 'forWrite' => $this->getRequest()->wasPosted() ]
332 if ( $watchedItems ) {
333 /** @var Title[] $titles */
335 foreach ( $watchedItems as $watchedItem ) {
336 $namespace = $watchedItem->getLinkTarget()->getNamespace();
337 $dbKey = $watchedItem->getLinkTarget()->getDBkey();
338 $title = Title
::makeTitleSafe( $namespace, $dbKey );
340 if ( $this->checkTitle( $title, $namespace, $dbKey )
341 && !$title->isTalkPage()
347 GenderCache
::singleton()->doTitlesArray( $titles );
349 foreach ( $titles as $title ) {
350 $list[] = $title->getPrefixedText();
354 $this->cleanupWatchlist();
360 * Get a list of titles on a user's watchlist, excluding talk pages,
361 * and return as a two-dimensional array with namespace and title.
365 protected function getWatchlistInfo() {
368 $watchedItems = WatchedItemStore
::getDefaultInstance()
369 ->getWatchedItemsForUser( $this->getUser(), [ 'sort' => WatchedItemStore
::SORT_ASC
] );
371 $lb = new LinkBatch();
373 foreach ( $watchedItems as $watchedItem ) {
374 $namespace = $watchedItem->getLinkTarget()->getNamespace();
375 $dbKey = $watchedItem->getLinkTarget()->getDBkey();
376 $lb->add( $namespace, $dbKey );
377 if ( !MWNamespace
::isTalk( $namespace ) ) {
378 $titles[$namespace][$dbKey] = 1;
388 * Validates watchlist entry
390 * @param Title $title
391 * @param int $namespace
392 * @param string $dbKey
393 * @return bool Whether this item is valid
395 private function checkTitle( $title, $namespace, $dbKey ) {
397 && ( $title->isExternal()
398 ||
$title->getNamespace() < 0
401 $title = false; // unrecoverable
405 ||
$title->getNamespace() != $namespace
406 ||
$title->getDBkey() != $dbKey
408 $this->badItems
[] = [ $title, $namespace, $dbKey ];
415 * Attempts to clean up broken items
417 private function cleanupWatchlist() {
418 if ( !count( $this->badItems
) ) {
419 return; // nothing to do
422 $user = $this->getUser();
423 $store = WatchedItemStore
::getDefaultInstance();
425 foreach ( $this->badItems
as $row ) {
426 list( $title, $namespace, $dbKey ) = $row;
427 $action = $title ?
'cleaning up' : 'deleting';
428 wfDebug( "User {$user->getName()} has broken watchlist item ns($namespace):$dbKey, $action.\n" );
430 $store->removeWatch( $user, new TitleValue( (int)$namespace, $dbKey ) );
432 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
434 $user->addWatch( $title );
440 * Remove all titles from a user's watchlist
442 private function clearWatchlist() {
443 $dbw = wfGetDB( DB_MASTER
);
446 [ 'wl_user' => $this->getUser()->getId() ],
452 * Add a list of targets to a user's watchlist
454 * @param string[]|LinkTarget[] $targets
456 private function watchTitles( $targets ) {
457 $expandedTargets = [];
458 foreach ( $targets as $target ) {
459 if ( !$target instanceof LinkTarget
) {
461 $target = $this->titleParser
->parseTitle( $target, NS_MAIN
);
463 catch ( MalformedTitleException
$e ) {
468 $ns = $target->getNamespace();
469 $dbKey = $target->getDBkey();
470 $expandedTargets[] = new TitleValue( MWNamespace
::getSubject( $ns ), $dbKey );
471 $expandedTargets[] = new TitleValue( MWNamespace
::getTalk( $ns ), $dbKey );
474 WatchedItemStore
::getDefaultInstance()->addWatchBatchForUser(
481 * Remove a list of titles from a user's watchlist
483 * $titles can be an array of strings or Title objects; the former
484 * is preferred, since Titles are very memory-heavy
486 * @param array $titles Array of strings, or Title objects
488 private function unwatchTitles( $titles ) {
489 $store = WatchedItemStore
::getDefaultInstance();
491 foreach ( $titles as $title ) {
492 if ( !$title instanceof Title
) {
493 $title = Title
::newFromText( $title );
496 if ( $title instanceof Title
) {
497 $store->removeWatch( $this->getUser(), $title->getSubjectPage() );
498 $store->removeWatch( $this->getUser(), $title->getTalkPage() );
500 $page = WikiPage
::factory( $title );
501 Hooks
::run( 'UnwatchArticleComplete', [ $this->getUser(), &$page ] );
506 public function submitNormal( $data ) {
509 foreach ( $data as $titles ) {
510 $this->unwatchTitles( $titles );
511 $removed = array_merge( $removed, $titles );
514 if ( count( $removed ) > 0 ) {
515 $this->successMessage
= $this->msg( 'watchlistedit-normal-done'
516 )->numParams( count( $removed ) )->parse();
517 $this->showTitles( $removed, $this->successMessage
);
526 * Get the standard watchlist editing form
530 protected function getNormalForm() {
536 // Allow subscribers to manipulate the list of watched pages (or use it
537 // to preload lots of details at once)
538 $watchlistInfo = $this->getWatchlistInfo();
540 'WatchlistEditorBeforeFormRender',
544 foreach ( $watchlistInfo as $namespace => $pages ) {
547 foreach ( array_keys( $pages ) as $dbkey ) {
548 $title = Title
::makeTitleSafe( $namespace, $dbkey );
550 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
551 $text = $this->buildRemoveLine( $title );
552 $options[$text] = $title->getPrefixedText();
557 // checkTitle can filter some options out, avoid empty sections
558 if ( count( $options ) > 0 ) {
559 $fields['TitlesNs' . $namespace] = [
560 'class' => 'EditWatchlistCheckboxSeriesField',
561 'options' => $options,
562 'section' => "ns$namespace",
566 $this->cleanupWatchlist();
568 if ( count( $fields ) > 1 && $count > 30 ) {
569 $this->toc
= Linker
::tocIndent();
572 foreach ( $fields as $data ) {
573 # strip out the 'ns' prefix from the section name:
574 $ns = substr( $data['section'], 2 );
576 $nsText = ( $ns == NS_MAIN
)
577 ?
$this->msg( 'blanknamespace' )->escaped()
578 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
579 $this->toc
.= Linker
::tocLine( "editwatchlist-{$data['section']}", $nsText,
580 $this->getLanguage()->formatNum( ++
$tocLength ), 1 ) . Linker
::tocLineEnd();
583 $this->toc
= Linker
::tocList( $this->toc
);
588 $context = new DerivativeContext( $this->getContext() );
589 $context->setTitle( $this->getPageTitle() ); // Remove subpage
590 $form = new EditWatchlistNormalHTMLForm( $fields, $context );
591 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
592 $form->setSubmitDestructive();
594 # 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
595 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
596 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
597 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
598 $form->setSubmitCallback( [ $this, 'submitNormal' ] );
604 * Build the label for a checkbox, with a link to the title, and various additional bits
606 * @param Title $title
609 private function buildRemoveLine( $title ) {
610 $link = Linker
::link( $title );
612 $tools['talk'] = Linker
::link(
613 $title->getTalkPage(),
614 $this->msg( 'talkpagelinktext' )->escaped()
617 if ( $title->exists() ) {
618 $tools['history'] = Linker
::linkKnown(
620 $this->msg( 'history_short' )->escaped(),
622 [ 'action' => 'history' ]
626 if ( $title->getNamespace() == NS_USER
&& !$title->isSubpage() ) {
627 $tools['contributions'] = Linker
::linkKnown(
628 SpecialPage
::getTitleFor( 'Contributions', $title->getText() ),
629 $this->msg( 'contributions' )->escaped()
634 'WatchlistEditorBuildRemoveLine',
635 [ &$tools, $title, $title->isRedirect(), $this->getSkin(), &$link ]
638 if ( $title->isRedirect() ) {
639 // Linker already makes class mw-redirect, so this is redundant
640 $link = '<span class="watchlistredir">' . $link . '</span>';
644 $this->msg( 'parentheses' )->rawParams( $this->getLanguage()->pipeList( $tools ) )->escaped();
648 * Get a form for editing the watchlist in "raw" mode
652 protected function getRawForm() {
653 $titles = implode( $this->getWatchlist(), "\n" );
656 'type' => 'textarea',
657 'label-message' => 'watchlistedit-raw-titles',
658 'default' => $titles,
661 $context = new DerivativeContext( $this->getContext() );
662 $context->setTitle( $this->getPageTitle( 'raw' ) ); // Reset subpage
663 $form = new HTMLForm( $fields, $context );
664 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
665 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
666 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
667 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
668 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
669 $form->setSubmitCallback( [ $this, 'submitRaw' ] );
675 * Get a form for clearing the watchlist
679 protected function getClearForm() {
680 $context = new DerivativeContext( $this->getContext() );
681 $context->setTitle( $this->getPageTitle( 'clear' ) ); // Reset subpage
682 $form = new HTMLForm( [], $context );
683 $form->setSubmitTextMsg( 'watchlistedit-clear-submit' );
684 # Used message keys: 'accesskey-watchlistedit-clear-submit', 'tooltip-watchlistedit-clear-submit'
685 $form->setSubmitTooltip( 'watchlistedit-clear-submit' );
686 $form->setWrapperLegendMsg( 'watchlistedit-clear-legend' );
687 $form->addHeaderText( $this->msg( 'watchlistedit-clear-explain' )->parse() );
688 $form->setSubmitCallback( [ $this, 'submitClear' ] );
689 $form->setSubmitDestructive();
695 * Determine whether we are editing the watchlist, and if so, what
696 * kind of editing operation
698 * @param WebRequest $request
702 public static function getMode( $request, $par ) {
703 $mode = strtolower( $request->getVal( 'action', $par ) );
707 case self
::EDIT_CLEAR
:
708 return self
::EDIT_CLEAR
;
711 return self
::EDIT_RAW
;
713 case self
::EDIT_NORMAL
:
714 return self
::EDIT_NORMAL
;
721 * Build a set of links for convenient navigation
722 * between watchlist viewing and editing modes
724 * @param null $unused
727 public static function buildTools( $unused ) {
732 'view' => [ 'Watchlist', false ],
733 'edit' => [ 'EditWatchlist', false ],
734 'raw' => [ 'EditWatchlist', 'raw' ],
735 'clear' => [ 'EditWatchlist', 'clear' ],
738 foreach ( $modes as $mode => $arr ) {
739 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
740 $tools[] = Linker
::linkKnown(
741 SpecialPage
::getTitleFor( $arr[0], $arr[1] ),
742 wfMessage( "watchlisttools-{$mode}" )->escaped()
746 return Html
::rawElement(
748 [ 'class' => 'mw-watchlist-toollinks' ],
749 wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $tools ) )->escaped()
755 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
757 class EditWatchlistNormalHTMLForm
extends HTMLForm
{
758 public function getLegend( $namespace ) {
759 $namespace = substr( $namespace, 2 );
761 return $namespace == NS_MAIN
762 ?
$this->msg( 'blanknamespace' )->escaped()
763 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
766 public function getBody() {
767 return $this->displaySection( $this->mFieldTree
, '', 'editwatchlist-' );
771 class EditWatchlistCheckboxSeriesField
extends HTMLMultiSelectField
{
773 * HTMLMultiSelectField throws validation errors if we get input data
774 * that doesn't match the data set in the form setup. This causes
775 * problems if something gets removed from the watchlist while the
776 * form is open (bug 32126), but we know that invalid items will
777 * be harmless so we can override it here.
779 * @param string $value The value the field was submitted with
780 * @param array $alldata The data collected from the form
781 * @return bool|string Bool true on success, or String error to display.
783 function validate( $value, $alldata ) {
784 // Need to call into grandparent to be a good citizen. :)
785 return HTMLFormField
::validate( $value, $alldata );