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 = [];
52 public function __construct() {
53 parent
::__construct( 'EditWatchlist', 'editmywatchlist' );
56 public function doesWrites() {
61 * Main execution point
65 public function execute( $mode ) {
68 # Anons don't get a watchlist
69 $this->requireLogin( 'watchlistanontext' );
71 $out = $this->getOutput();
73 $this->checkPermissions();
74 $this->checkReadOnly();
76 $this->outputHeader();
77 $this->outputSubtitle();
78 $out->addModuleStyles( 'mediawiki.special' );
80 # B/C: $mode used to be waaay down the parameter list, and the first parameter
82 if ( $mode instanceof User
) {
83 $args = func_get_args();
84 if ( count( $args ) >= 4 ) {
88 $mode = self
::getMode( $this->getRequest(), $mode );
92 $out->setPageTitle( $this->msg( 'watchlistedit-raw-title' ) );
93 $form = $this->getRawForm();
94 if ( $form->show() ) {
95 $out->addHTML( $this->successMessage
);
96 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
99 case self
::EDIT_CLEAR
:
100 $out->setPageTitle( $this->msg( 'watchlistedit-clear-title' ) );
101 $form = $this->getClearForm();
102 if ( $form->show() ) {
103 $out->addHTML( $this->successMessage
);
104 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
108 case self
::EDIT_NORMAL
:
110 $this->executeViewEditWatchlist();
116 * Renders a subheader on the watchlist page.
118 protected function outputSubtitle() {
119 $out = $this->getOutput();
120 $out->addSubtitle( $this->msg( 'watchlistfor2', $this->getUser()->getName() )
121 ->rawParams( SpecialEditWatchlist
::buildTools( null ) ) );
125 * Executes an edit mode for the watchlist view, from which you can manage your watchlist
128 protected function executeViewEditWatchlist() {
129 $out = $this->getOutput();
130 $out->setPageTitle( $this->msg( 'watchlistedit-normal-title' ) );
131 $form = $this->getNormalForm();
132 if ( $form->show() ) {
133 $out->addHTML( $this->successMessage
);
134 $out->addReturnTo( SpecialPage
::getTitleFor( 'Watchlist' ) );
135 } elseif ( $this->toc
!== false ) {
136 $out->prependHTML( $this->toc
);
137 $out->addModules( 'mediawiki.toc' );
142 * Return an array of subpages that this special page will accept.
144 * @see also SpecialWatchlist::getSubpagesForPrefixSearch
145 * @return string[] subpages
147 public function getSubpagesForPrefixSearch() {
148 // SpecialWatchlist uses SpecialEditWatchlist::getMode, so new types should be added
149 // here and there - no 'edit' here, because that the default for this page
157 * Extract a list of titles from a blob of text, returning
158 * (prefixed) strings; unwatchable titles are ignored
160 * @param string $list
163 private function extractTitles( $list ) {
164 $list = explode( "\n", trim( $list ) );
165 if ( !is_array( $list ) ) {
171 foreach ( $list as $text ) {
172 $text = trim( $text );
173 if ( strlen( $text ) > 0 ) {
174 $title = Title
::newFromText( $text );
175 if ( $title instanceof Title
&& $title->isWatchable() ) {
181 GenderCache
::singleton()->doTitlesArray( $titles );
184 /** @var Title $title */
185 foreach ( $titles as $title ) {
186 $list[] = $title->getPrefixedText();
189 return array_unique( $list );
192 public function submitRaw( $data ) {
193 $wanted = $this->extractTitles( $data['Titles'] );
194 $current = $this->getWatchlist();
196 if ( count( $wanted ) > 0 ) {
197 $toWatch = array_diff( $wanted, $current );
198 $toUnwatch = array_diff( $current, $wanted );
199 $this->watchTitles( $toWatch );
200 $this->unwatchTitles( $toUnwatch );
201 $this->getUser()->invalidateCache();
203 if ( count( $toWatch ) > 0 ||
count( $toUnwatch ) > 0 ) {
204 $this->successMessage
= $this->msg( 'watchlistedit-raw-done' )->parse();
209 if ( count( $toWatch ) > 0 ) {
210 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-added' )
211 ->numParams( count( $toWatch ) )->parse();
212 $this->showTitles( $toWatch, $this->successMessage
);
215 if ( count( $toUnwatch ) > 0 ) {
216 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-removed' )
217 ->numParams( count( $toUnwatch ) )->parse();
218 $this->showTitles( $toUnwatch, $this->successMessage
);
221 $this->clearWatchlist();
222 $this->getUser()->invalidateCache();
224 if ( count( $current ) > 0 ) {
225 $this->successMessage
= $this->msg( 'watchlistedit-raw-done' )->parse();
230 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-raw-removed' )
231 ->numParams( count( $current ) )->parse();
232 $this->showTitles( $current, $this->successMessage
);
238 public function submitClear( $data ) {
239 $current = $this->getWatchlist();
240 $this->clearWatchlist();
241 $this->getUser()->invalidateCache();
242 $this->successMessage
= $this->msg( 'watchlistedit-clear-done' )->parse();
243 $this->successMessage
.= ' ' . $this->msg( 'watchlistedit-clear-removed' )
244 ->numParams( count( $current ) )->parse();
245 $this->showTitles( $current, $this->successMessage
);
251 * Print out a list of linked titles
253 * $titles can be an array of strings or Title objects; the former
254 * is preferred, since Titles are very memory-heavy
256 * @param array $titles Array of strings, or Title objects
257 * @param string $output
259 private function showTitles( $titles, &$output ) {
260 $talk = $this->msg( 'talkpagelinktext' )->escaped();
261 // Do a batch existence check
262 $batch = new LinkBatch();
263 if ( count( $titles ) >= 100 ) {
264 $output = $this->msg( 'watchlistedit-too-many' )->parse();
267 foreach ( $titles as $title ) {
268 if ( !$title instanceof Title
) {
269 $title = Title
::newFromText( $title );
272 if ( $title instanceof Title
) {
273 $batch->addObj( $title );
274 $batch->addObj( $title->getTalkPage() );
280 // Print out the list
283 foreach ( $titles as $title ) {
284 if ( !$title instanceof Title
) {
285 $title = Title
::newFromText( $title );
288 if ( $title instanceof Title
) {
290 Linker
::link( $title ) . ' ' .
291 $this->msg( 'parentheses' )->rawParams(
292 Linker
::link( $title->getTalkPage(), $talk )
298 $output .= "</ul>\n";
302 * Prepare a list of titles on a user's watchlist (excluding talk pages)
303 * and return an array of (prefixed) strings
307 private function getWatchlist() {
310 $index = $this->getRequest()->wasPosted() ? DB_MASTER
: DB_SLAVE
;
311 $dbr = wfGetDB( $index );
316 'wl_namespace', 'wl_title'
318 'wl_user' => $this->getUser()->getId(),
323 if ( $res->numRows() > 0 ) {
324 /** @var Title[] $titles */
326 foreach ( $res as $row ) {
327 $title = Title
::makeTitleSafe( $row->wl_namespace
, $row->wl_title
);
329 if ( $this->checkTitle( $title, $row->wl_namespace
, $row->wl_title
)
330 && !$title->isTalkPage()
337 GenderCache
::singleton()->doTitlesArray( $titles );
339 foreach ( $titles as $title ) {
340 $list[] = $title->getPrefixedText();
344 $this->cleanupWatchlist();
350 * Get a list of titles on a user's watchlist, excluding talk pages,
351 * and return as a two-dimensional array with namespace and title.
355 protected function getWatchlistInfo() {
357 $dbr = wfGetDB( DB_SLAVE
);
361 [ 'wl_namespace', 'wl_title' ],
362 [ 'wl_user' => $this->getUser()->getId() ],
364 [ 'ORDER BY' => [ 'wl_namespace', 'wl_title' ] ]
367 $lb = new LinkBatch();
369 foreach ( $res as $row ) {
370 $lb->add( $row->wl_namespace
, $row->wl_title
);
371 if ( !MWNamespace
::isTalk( $row->wl_namespace
) ) {
372 $titles[$row->wl_namespace
][$row->wl_title
] = 1;
382 * Validates watchlist entry
384 * @param Title $title
385 * @param int $namespace
386 * @param string $dbKey
387 * @return bool Whether this item is valid
389 private function checkTitle( $title, $namespace, $dbKey ) {
391 && ( $title->isExternal()
392 ||
$title->getNamespace() < 0
395 $title = false; // unrecoverable
399 ||
$title->getNamespace() != $namespace
400 ||
$title->getDBkey() != $dbKey
402 $this->badItems
[] = [ $title, $namespace, $dbKey ];
409 * Attempts to clean up broken items
411 private function cleanupWatchlist() {
412 if ( !count( $this->badItems
) ) {
413 return; // nothing to do
416 $user = $this->getUser();
417 $store = WatchedItemStore
::getDefaultInstance();
419 foreach ( $this->badItems
as $row ) {
420 list( $title, $namespace, $dbKey ) = $row;
421 $action = $title ?
'cleaning up' : 'deleting';
422 wfDebug( "User {$user->getName()} has broken watchlist item ns($namespace):$dbKey, $action.\n" );
424 $store->removeWatch( $user, new TitleValue( $namespace, $dbKey ) );
426 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
428 $user->addWatch( $title );
434 * Remove all titles from a user's watchlist
436 private function clearWatchlist() {
437 $dbw = wfGetDB( DB_MASTER
);
440 [ 'wl_user' => $this->getUser()->getId() ],
446 * Add a list of titles to a user's watchlist
448 * $titles can be an array of strings or Title objects; the former
449 * is preferred, since Titles are very memory-heavy
451 * @param array $titles Array of strings, or Title objects
453 private function watchTitles( $titles ) {
454 $dbw = wfGetDB( DB_MASTER
);
457 foreach ( $titles as $title ) {
458 if ( !$title instanceof Title
) {
459 $title = Title
::newFromText( $title );
462 if ( $title instanceof Title
) {
464 'wl_user' => $this->getUser()->getId(),
465 'wl_namespace' => MWNamespace
::getSubject( $title->getNamespace() ),
466 'wl_title' => $title->getDBkey(),
467 'wl_notificationtimestamp' => null,
470 'wl_user' => $this->getUser()->getId(),
471 'wl_namespace' => MWNamespace
::getTalk( $title->getNamespace() ),
472 'wl_title' => $title->getDBkey(),
473 'wl_notificationtimestamp' => null,
478 $dbw->insert( 'watchlist', $rows, __METHOD__
, 'IGNORE' );
482 * Remove a list of titles from a user's watchlist
484 * $titles can be an array of strings or Title objects; the former
485 * is preferred, since Titles are very memory-heavy
487 * @param array $titles Array of strings, or Title objects
489 private function unwatchTitles( $titles ) {
490 $store = WatchedItemStore
::getDefaultInstance();
492 foreach ( $titles as $title ) {
493 if ( !$title instanceof Title
) {
494 $title = Title
::newFromText( $title );
497 if ( $title instanceof Title
) {
498 $store->removeWatch( $this->getUser(), $title->getSubjectPage() );
499 $store->removeWatch( $this->getUser(), $title->getTalkPage() );
501 $page = WikiPage
::factory( $title );
502 Hooks
::run( 'UnwatchArticleComplete', [ $this->getUser(), &$page ] );
507 public function submitNormal( $data ) {
510 foreach ( $data as $titles ) {
511 $this->unwatchTitles( $titles );
512 $removed = array_merge( $removed, $titles );
515 if ( count( $removed ) > 0 ) {
516 $this->successMessage
= $this->msg( 'watchlistedit-normal-done'
517 )->numParams( count( $removed ) )->parse();
518 $this->showTitles( $removed, $this->successMessage
);
527 * Get the standard watchlist editing form
531 protected function getNormalForm() {
537 // Allow subscribers to manipulate the list of watched pages (or use it
538 // to preload lots of details at once)
539 $watchlistInfo = $this->getWatchlistInfo();
541 'WatchlistEditorBeforeFormRender',
545 foreach ( $watchlistInfo as $namespace => $pages ) {
548 foreach ( array_keys( $pages ) as $dbkey ) {
549 $title = Title
::makeTitleSafe( $namespace, $dbkey );
551 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
552 $text = $this->buildRemoveLine( $title );
553 $options[$text] = $title->getPrefixedText();
558 // checkTitle can filter some options out, avoid empty sections
559 if ( count( $options ) > 0 ) {
560 $fields['TitlesNs' . $namespace] = [
561 'class' => 'EditWatchlistCheckboxSeriesField',
562 'options' => $options,
563 'section' => "ns$namespace",
567 $this->cleanupWatchlist();
569 if ( count( $fields ) > 1 && $count > 30 ) {
570 $this->toc
= Linker
::tocIndent();
573 foreach ( $fields as $data ) {
574 # strip out the 'ns' prefix from the section name:
575 $ns = substr( $data['section'], 2 );
577 $nsText = ( $ns == NS_MAIN
)
578 ?
$this->msg( 'blanknamespace' )->escaped()
579 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
580 $this->toc
.= Linker
::tocLine( "editwatchlist-{$data['section']}", $nsText,
581 $this->getLanguage()->formatNum( ++
$tocLength ), 1 ) . Linker
::tocLineEnd();
584 $this->toc
= Linker
::tocList( $this->toc
);
589 $context = new DerivativeContext( $this->getContext() );
590 $context->setTitle( $this->getPageTitle() ); // Remove subpage
591 $form = new EditWatchlistNormalHTMLForm( $fields, $context );
592 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
593 $form->setSubmitDestructive();
595 # 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
596 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
597 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
598 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
599 $form->setSubmitCallback( [ $this, 'submitNormal' ] );
605 * Build the label for a checkbox, with a link to the title, and various additional bits
607 * @param Title $title
610 private function buildRemoveLine( $title ) {
611 $link = Linker
::link( $title );
613 $tools['talk'] = Linker
::link(
614 $title->getTalkPage(),
615 $this->msg( 'talkpagelinktext' )->escaped()
618 if ( $title->exists() ) {
619 $tools['history'] = Linker
::linkKnown(
621 $this->msg( 'history_short' )->escaped(),
623 [ 'action' => 'history' ]
627 if ( $title->getNamespace() == NS_USER
&& !$title->isSubpage() ) {
628 $tools['contributions'] = Linker
::linkKnown(
629 SpecialPage
::getTitleFor( 'Contributions', $title->getText() ),
630 $this->msg( 'contributions' )->escaped()
635 'WatchlistEditorBuildRemoveLine',
636 [ &$tools, $title, $title->isRedirect(), $this->getSkin(), &$link ]
639 if ( $title->isRedirect() ) {
640 // Linker already makes class mw-redirect, so this is redundant
641 $link = '<span class="watchlistredir">' . $link . '</span>';
645 $this->msg( 'parentheses' )->rawParams( $this->getLanguage()->pipeList( $tools ) )->escaped();
649 * Get a form for editing the watchlist in "raw" mode
653 protected function getRawForm() {
654 $titles = implode( $this->getWatchlist(), "\n" );
657 'type' => 'textarea',
658 'label-message' => 'watchlistedit-raw-titles',
659 'default' => $titles,
662 $context = new DerivativeContext( $this->getContext() );
663 $context->setTitle( $this->getPageTitle( 'raw' ) ); // Reset subpage
664 $form = new HTMLForm( $fields, $context );
665 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
666 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
667 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
668 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
669 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
670 $form->setSubmitCallback( [ $this, 'submitRaw' ] );
676 * Get a form for clearing the watchlist
680 protected function getClearForm() {
681 $context = new DerivativeContext( $this->getContext() );
682 $context->setTitle( $this->getPageTitle( 'clear' ) ); // Reset subpage
683 $form = new HTMLForm( [], $context );
684 $form->setSubmitTextMsg( 'watchlistedit-clear-submit' );
685 # Used message keys: 'accesskey-watchlistedit-clear-submit', 'tooltip-watchlistedit-clear-submit'
686 $form->setSubmitTooltip( 'watchlistedit-clear-submit' );
687 $form->setWrapperLegendMsg( 'watchlistedit-clear-legend' );
688 $form->addHeaderText( $this->msg( 'watchlistedit-clear-explain' )->parse() );
689 $form->setSubmitCallback( [ $this, 'submitClear' ] );
690 $form->setSubmitDestructive();
696 * Determine whether we are editing the watchlist, and if so, what
697 * kind of editing operation
699 * @param WebRequest $request
703 public static function getMode( $request, $par ) {
704 $mode = strtolower( $request->getVal( 'action', $par ) );
708 case self
::EDIT_CLEAR
:
709 return self
::EDIT_CLEAR
;
712 return self
::EDIT_RAW
;
714 case self
::EDIT_NORMAL
:
715 return self
::EDIT_NORMAL
;
722 * Build a set of links for convenient navigation
723 * between watchlist viewing and editing modes
725 * @param null $unused
728 public static function buildTools( $unused ) {
733 'view' => [ 'Watchlist', false ],
734 'edit' => [ 'EditWatchlist', false ],
735 'raw' => [ 'EditWatchlist', 'raw' ],
736 'clear' => [ 'EditWatchlist', 'clear' ],
739 foreach ( $modes as $mode => $arr ) {
740 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
741 $tools[] = Linker
::linkKnown(
742 SpecialPage
::getTitleFor( $arr[0], $arr[1] ),
743 wfMessage( "watchlisttools-{$mode}" )->escaped()
747 return Html
::rawElement(
749 [ 'class' => 'mw-watchlist-toollinks' ],
750 wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $tools ) )->escaped()
756 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
758 class EditWatchlistNormalHTMLForm
extends HTMLForm
{
759 public function getLegend( $namespace ) {
760 $namespace = substr( $namespace, 2 );
762 return $namespace == NS_MAIN
763 ?
$this->msg( 'blanknamespace' )->escaped()
764 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
767 public function getBody() {
768 return $this->displaySection( $this->mFieldTree
, '', 'editwatchlist-' );
772 class EditWatchlistCheckboxSeriesField
extends HTMLMultiSelectField
{
774 * HTMLMultiSelectField throws validation errors if we get input data
775 * that doesn't match the data set in the form setup. This causes
776 * problems if something gets removed from the watchlist while the
777 * form is open (bug 32126), but we know that invalid items will
778 * be harmless so we can override it here.
780 * @param string $value The value the field was submitted with
781 * @param array $alldata The data collected from the form
782 * @return bool|string Bool true on success, or String error to display.
784 function validate( $value, $alldata ) {
785 // Need to call into grandparent to be a good citizen. :)
786 return HTMLFormField
::validate( $value, $alldata );