Implement extension registration from an extension.json file
[mediawiki.git] / includes / specials / SpecialEditWatchlist.php
blobffe7892e8b7f45598fa899bd2bb6059840679959
1 <?php
2 /**
3 * @defgroup Watchlist Users watchlist handling
4 */
6 /**
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
24 * @file
25 * @ingroup SpecialPage
26 * @ingroup Watchlist
29 /**
30 * Provides the UI through which users can perform editing
31 * operations on their watchlist
33 * @ingroup SpecialPage
34 * @ingroup Watchlist
35 * @author Rob Church <robchur@gmail.com>
37 class SpecialEditWatchlist extends UnlistedSpecialPage {
38 /**
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.
42 const EDIT_CLEAR = 1;
43 const EDIT_RAW = 2;
44 const EDIT_NORMAL = 3;
46 protected $successMessage;
48 protected $toc;
50 private $badItems = array();
52 public function __construct() {
53 parent::__construct( 'EditWatchlist', 'editmywatchlist' );
56 /**
57 * Main execution point
59 * @param int $mode
61 public function execute( $mode ) {
62 $this->setHeaders();
64 # Anons don't get a watchlist
65 $this->requireLogin( 'watchlistanontext' );
67 $out = $this->getOutput();
69 $this->checkPermissions();
70 $this->checkReadOnly();
72 $this->outputHeader();
73 $this->outputSubtitle();
75 # B/C: $mode used to be waaay down the parameter list, and the first parameter
76 # was $wgUser
77 if ( $mode instanceof User ) {
78 $args = func_get_args();
79 if ( count( $args ) >= 4 ) {
80 $mode = $args[3];
83 $mode = self::getMode( $this->getRequest(), $mode );
85 switch ( $mode ) {
86 case self::EDIT_RAW:
87 $out->setPageTitle( $this->msg( 'watchlistedit-raw-title' ) );
88 $form = $this->getRawForm();
89 if ( $form->show() ) {
90 $out->addHTML( $this->successMessage );
91 $out->addReturnTo( SpecialPage::getTitleFor( 'Watchlist' ) );
93 break;
94 case self::EDIT_CLEAR:
95 $out->setPageTitle( $this->msg( 'watchlistedit-clear-title' ) );
96 $form = $this->getClearForm();
97 if ( $form->show() ) {
98 $out->addHTML( $this->successMessage );
99 $out->addReturnTo( SpecialPage::getTitleFor( 'Watchlist' ) );
101 break;
103 case self::EDIT_NORMAL:
104 default:
105 $this->executeViewEditWatchlist();
106 break;
111 * Renders a subheader on the watchlist page.
113 protected function outputSubtitle() {
114 $out = $this->getOutput();
115 $out->addSubtitle( $this->msg( 'watchlistfor2', $this->getUser()->getName() )
116 ->rawParams( SpecialEditWatchlist::buildTools( null ) ) );
120 * Executes an edit mode for the watchlist view, from which you can manage your watchlist
123 protected function executeViewEditWatchlist() {
124 $out = $this->getOutput();
125 $out->setPageTitle( $this->msg( 'watchlistedit-normal-title' ) );
126 $form = $this->getNormalForm();
127 if ( $form->show() ) {
128 $out->addHTML( $this->successMessage );
129 $out->addReturnTo( SpecialPage::getTitleFor( 'Watchlist' ) );
130 } elseif ( $this->toc !== false ) {
131 $out->prependHTML( $this->toc );
132 $out->addModules( 'mediawiki.toc' );
137 * Return an array of subpages that this special page will accept.
139 * @see also SpecialWatchlist::getSubpagesForPrefixSearch
140 * @return string[] subpages
142 public function getSubpagesForPrefixSearch() {
143 // SpecialWatchlist uses SpecialEditWatchlist::getMode, so new types should be added
144 // here and there - no 'edit' here, because that the default for this page
145 return array(
146 'clear',
147 'raw',
152 * Extract a list of titles from a blob of text, returning
153 * (prefixed) strings; unwatchable titles are ignored
155 * @param string $list
156 * @return array
158 private function extractTitles( $list ) {
159 $list = explode( "\n", trim( $list ) );
160 if ( !is_array( $list ) ) {
161 return array();
164 $titles = array();
166 foreach ( $list as $text ) {
167 $text = trim( $text );
168 if ( strlen( $text ) > 0 ) {
169 $title = Title::newFromText( $text );
170 if ( $title instanceof Title && $title->isWatchable() ) {
171 $titles[] = $title;
176 GenderCache::singleton()->doTitlesArray( $titles );
178 $list = array();
179 /** @var Title $title */
180 foreach ( $titles as $title ) {
181 $list[] = $title->getPrefixedText();
184 return array_unique( $list );
187 public function submitRaw( $data ) {
188 $wanted = $this->extractTitles( $data['Titles'] );
189 $current = $this->getWatchlist();
191 if ( count( $wanted ) > 0 ) {
192 $toWatch = array_diff( $wanted, $current );
193 $toUnwatch = array_diff( $current, $wanted );
194 $this->watchTitles( $toWatch );
195 $this->unwatchTitles( $toUnwatch );
196 $this->getUser()->invalidateCache();
198 if ( count( $toWatch ) > 0 || count( $toUnwatch ) > 0 ) {
199 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
200 } else {
201 return false;
204 if ( count( $toWatch ) > 0 ) {
205 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-added' )
206 ->numParams( count( $toWatch ) )->parse();
207 $this->showTitles( $toWatch, $this->successMessage );
210 if ( count( $toUnwatch ) > 0 ) {
211 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed' )
212 ->numParams( count( $toUnwatch ) )->parse();
213 $this->showTitles( $toUnwatch, $this->successMessage );
215 } else {
216 $this->clearWatchlist();
217 $this->getUser()->invalidateCache();
219 if ( count( $current ) > 0 ) {
220 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
221 } else {
222 return false;
225 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed' )
226 ->numParams( count( $current ) )->parse();
227 $this->showTitles( $current, $this->successMessage );
230 return true;
233 public function submitClear( $data ) {
234 $current = $this->getWatchlist();
235 $this->clearWatchlist();
236 $this->getUser()->invalidateCache();
237 $this->successMessage = $this->msg( 'watchlistedit-clear-done' )->parse();
238 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-clear-removed' )
239 ->numParams( count( $current ) )->parse();
240 $this->showTitles( $current, $this->successMessage );
242 return true;
246 * Print out a list of linked titles
248 * $titles can be an array of strings or Title objects; the former
249 * is preferred, since Titles are very memory-heavy
251 * @param array $titles Array of strings, or Title objects
252 * @param string $output
254 private function showTitles( $titles, &$output ) {
255 $talk = $this->msg( 'talkpagelinktext' )->escaped();
256 // Do a batch existence check
257 $batch = new LinkBatch();
258 if ( count( $titles ) >= 100 ) {
259 $output = $this->msg( 'watchlistedit-too-many' )->parse();
260 return;
262 foreach ( $titles as $title ) {
263 if ( !$title instanceof Title ) {
264 $title = Title::newFromText( $title );
267 if ( $title instanceof Title ) {
268 $batch->addObj( $title );
269 $batch->addObj( $title->getTalkPage() );
273 $batch->execute();
275 // Print out the list
276 $output .= "<ul>\n";
278 foreach ( $titles as $title ) {
279 if ( !$title instanceof Title ) {
280 $title = Title::newFromText( $title );
283 if ( $title instanceof Title ) {
284 $output .= "<li>"
285 . Linker::link( $title )
286 . ' (' . Linker::link( $title->getTalkPage(), $talk )
287 . ")</li>\n";
291 $output .= "</ul>\n";
295 * Prepare a list of titles on a user's watchlist (excluding talk pages)
296 * and return an array of (prefixed) strings
298 * @return array
300 private function getWatchlist() {
301 $list = array();
302 $dbr = wfGetDB( DB_MASTER );
304 $res = $dbr->select(
305 'watchlist',
306 array(
307 'wl_namespace', 'wl_title'
308 ), array(
309 'wl_user' => $this->getUser()->getId(),
311 __METHOD__
314 if ( $res->numRows() > 0 ) {
315 $titles = array();
316 foreach ( $res as $row ) {
317 $title = Title::makeTitleSafe( $row->wl_namespace, $row->wl_title );
319 if ( $this->checkTitle( $title, $row->wl_namespace, $row->wl_title )
320 && !$title->isTalkPage()
322 $titles[] = $title;
325 $res->free();
327 GenderCache::singleton()->doTitlesArray( $titles );
329 foreach ( $titles as $title ) {
330 $list[] = $title->getPrefixedText();
334 $this->cleanupWatchlist();
336 return $list;
340 * Get a list of titles on a user's watchlist, excluding talk pages,
341 * and return as a two-dimensional array with namespace and title.
343 * @return array
345 protected function getWatchlistInfo() {
346 $titles = array();
347 $dbr = wfGetDB( DB_MASTER );
349 $res = $dbr->select(
350 array( 'watchlist' ),
351 array( 'wl_namespace', 'wl_title' ),
352 array( 'wl_user' => $this->getUser()->getId() ),
353 __METHOD__,
354 array( 'ORDER BY' => array( 'wl_namespace', 'wl_title' ) )
357 $lb = new LinkBatch();
359 foreach ( $res as $row ) {
360 $lb->add( $row->wl_namespace, $row->wl_title );
361 if ( !MWNamespace::isTalk( $row->wl_namespace ) ) {
362 $titles[$row->wl_namespace][$row->wl_title] = 1;
366 $lb->execute();
368 return $titles;
372 * Validates watchlist entry
374 * @param Title $title
375 * @param int $namespace
376 * @param string $dbKey
377 * @return bool Whether this item is valid
379 private function checkTitle( $title, $namespace, $dbKey ) {
380 if ( $title
381 && ( $title->isExternal()
382 || $title->getNamespace() < 0
385 $title = false; // unrecoverable
388 if ( !$title
389 || $title->getNamespace() != $namespace
390 || $title->getDBkey() != $dbKey
392 $this->badItems[] = array( $title, $namespace, $dbKey );
395 return (bool)$title;
399 * Attempts to clean up broken items
401 private function cleanupWatchlist() {
402 if ( !count( $this->badItems ) ) {
403 return; //nothing to do
406 $dbw = wfGetDB( DB_MASTER );
407 $user = $this->getUser();
409 foreach ( $this->badItems as $row ) {
410 list( $title, $namespace, $dbKey ) = $row;
411 $action = $title ? 'cleaning up' : 'deleting';
412 wfDebug( "User {$user->getName()} has broken watchlist item ns($namespace):$dbKey, $action.\n" );
414 $dbw->delete( 'watchlist',
415 array(
416 'wl_user' => $user->getId(),
417 'wl_namespace' => $namespace,
418 'wl_title' => $dbKey,
420 __METHOD__
423 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
424 if ( $title ) {
425 $user->addWatch( $title );
431 * Remove all titles from a user's watchlist
433 private function clearWatchlist() {
434 $dbw = wfGetDB( DB_MASTER );
435 $dbw->delete(
436 'watchlist',
437 array( 'wl_user' => $this->getUser()->getId() ),
438 __METHOD__
443 * Add a list of titles to a user's watchlist
445 * $titles can be an array of strings or Title objects; the former
446 * is preferred, since Titles are very memory-heavy
448 * @param array $titles Array of strings, or Title objects
450 private function watchTitles( $titles ) {
451 $dbw = wfGetDB( DB_MASTER );
452 $rows = array();
454 foreach ( $titles as $title ) {
455 if ( !$title instanceof Title ) {
456 $title = Title::newFromText( $title );
459 if ( $title instanceof Title ) {
460 $rows[] = array(
461 'wl_user' => $this->getUser()->getId(),
462 'wl_namespace' => MWNamespace::getSubject( $title->getNamespace() ),
463 'wl_title' => $title->getDBkey(),
464 'wl_notificationtimestamp' => null,
466 $rows[] = array(
467 'wl_user' => $this->getUser()->getId(),
468 'wl_namespace' => MWNamespace::getTalk( $title->getNamespace() ),
469 'wl_title' => $title->getDBkey(),
470 'wl_notificationtimestamp' => null,
475 $dbw->insert( 'watchlist', $rows, __METHOD__, 'IGNORE' );
479 * Remove a list of titles from a user's watchlist
481 * $titles can be an array of strings or Title objects; the former
482 * is preferred, since Titles are very memory-heavy
484 * @param array $titles Array of strings, or Title objects
486 private function unwatchTitles( $titles ) {
487 $dbw = wfGetDB( DB_MASTER );
489 foreach ( $titles as $title ) {
490 if ( !$title instanceof Title ) {
491 $title = Title::newFromText( $title );
494 if ( $title instanceof Title ) {
495 $dbw->delete(
496 'watchlist',
497 array(
498 'wl_user' => $this->getUser()->getId(),
499 'wl_namespace' => MWNamespace::getSubject( $title->getNamespace() ),
500 'wl_title' => $title->getDBkey(),
502 __METHOD__
505 $dbw->delete(
506 'watchlist',
507 array(
508 'wl_user' => $this->getUser()->getId(),
509 'wl_namespace' => MWNamespace::getTalk( $title->getNamespace() ),
510 'wl_title' => $title->getDBkey(),
512 __METHOD__
515 $page = WikiPage::factory( $title );
516 Hooks::run( 'UnwatchArticleComplete', array( $this->getUser(), &$page ) );
521 public function submitNormal( $data ) {
522 $removed = array();
524 foreach ( $data as $titles ) {
525 $this->unwatchTitles( $titles );
526 $removed = array_merge( $removed, $titles );
529 if ( count( $removed ) > 0 ) {
530 $this->successMessage = $this->msg( 'watchlistedit-normal-done'
531 )->numParams( count( $removed ) )->parse();
532 $this->showTitles( $removed, $this->successMessage );
534 return true;
535 } else {
536 return false;
541 * Get the standard watchlist editing form
543 * @return HTMLForm
545 protected function getNormalForm() {
546 global $wgContLang;
548 $fields = array();
549 $count = 0;
551 // Allow subscribers to manipulate the list of watched pages (or use it
552 // to preload lots of details at once)
553 $watchlistInfo = $this->getWatchlistInfo();
554 Hooks::run(
555 'WatchlistEditorBeforeFormRender',
556 array( &$watchlistInfo )
559 foreach ( $watchlistInfo as $namespace => $pages ) {
560 $options = array();
562 foreach ( array_keys( $pages ) as $dbkey ) {
563 $title = Title::makeTitleSafe( $namespace, $dbkey );
565 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
566 $text = $this->buildRemoveLine( $title );
567 $options[$text] = $title->getPrefixedText();
568 $count++;
572 // checkTitle can filter some options out, avoid empty sections
573 if ( count( $options ) > 0 ) {
574 $fields['TitlesNs' . $namespace] = array(
575 'class' => 'EditWatchlistCheckboxSeriesField',
576 'options' => $options,
577 'section' => "ns$namespace",
581 $this->cleanupWatchlist();
583 if ( count( $fields ) > 1 && $count > 30 ) {
584 $this->toc = Linker::tocIndent();
585 $tocLength = 0;
587 foreach ( $fields as $data ) {
588 # strip out the 'ns' prefix from the section name:
589 $ns = substr( $data['section'], 2 );
591 $nsText = ( $ns == NS_MAIN )
592 ? $this->msg( 'blanknamespace' )->escaped()
593 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
594 $this->toc .= Linker::tocLine( "editwatchlist-{$data['section']}", $nsText,
595 $this->getLanguage()->formatNum( ++$tocLength ), 1 ) . Linker::tocLineEnd();
598 $this->toc = Linker::tocList( $this->toc );
599 } else {
600 $this->toc = false;
603 $context = new DerivativeContext( $this->getContext() );
604 $context->setTitle( $this->getPageTitle() ); // Remove subpage
605 $form = new EditWatchlistNormalHTMLForm( $fields, $context );
606 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
607 $form->setSubmitDestructive();
608 # Used message keys:
609 # 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
610 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
611 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
612 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
613 $form->setSubmitCallback( array( $this, 'submitNormal' ) );
615 return $form;
619 * Build the label for a checkbox, with a link to the title, and various additional bits
621 * @param Title $title
622 * @return string
624 private function buildRemoveLine( $title ) {
625 $link = Linker::link( $title );
627 $tools['talk'] = Linker::link(
628 $title->getTalkPage(),
629 $this->msg( 'talkpagelinktext' )->escaped()
632 if ( $title->exists() ) {
633 $tools['history'] = Linker::linkKnown(
634 $title,
635 $this->msg( 'history_short' )->escaped(),
636 array(),
637 array( 'action' => 'history' )
641 if ( $title->getNamespace() == NS_USER && !$title->isSubpage() ) {
642 $tools['contributions'] = Linker::linkKnown(
643 SpecialPage::getTitleFor( 'Contributions', $title->getText() ),
644 $this->msg( 'contributions' )->escaped()
648 Hooks::run(
649 'WatchlistEditorBuildRemoveLine',
650 array( &$tools, $title, $title->isRedirect(), $this->getSkin(), &$link )
653 if ( $title->isRedirect() ) {
654 // Linker already makes class mw-redirect, so this is redundant
655 $link = '<span class="watchlistredir">' . $link . '</span>';
658 return $link . " (" . $this->getLanguage()->pipeList( $tools ) . ")";
662 * Get a form for editing the watchlist in "raw" mode
664 * @return HTMLForm
666 protected function getRawForm() {
667 $titles = implode( $this->getWatchlist(), "\n" );
668 $fields = array(
669 'Titles' => array(
670 'type' => 'textarea',
671 'label-message' => 'watchlistedit-raw-titles',
672 'default' => $titles,
675 $context = new DerivativeContext( $this->getContext() );
676 $context->setTitle( $this->getPageTitle( 'raw' ) ); // Reset subpage
677 $form = new HTMLForm( $fields, $context );
678 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
679 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
680 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
681 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
682 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
683 $form->setSubmitCallback( array( $this, 'submitRaw' ) );
685 return $form;
689 * Get a form for clearing the watchlist
691 * @return HTMLForm
693 protected function getClearForm() {
694 $context = new DerivativeContext( $this->getContext() );
695 $context->setTitle( $this->getPageTitle( 'clear' ) ); // Reset subpage
696 $form = new HTMLForm( array(), $context );
697 $form->setSubmitTextMsg( 'watchlistedit-clear-submit' );
698 # Used message keys: 'accesskey-watchlistedit-clear-submit', 'tooltip-watchlistedit-clear-submit'
699 $form->setSubmitTooltip( 'watchlistedit-clear-submit' );
700 $form->setWrapperLegendMsg( 'watchlistedit-clear-legend' );
701 $form->addHeaderText( $this->msg( 'watchlistedit-clear-explain' )->parse() );
702 $form->setSubmitCallback( array( $this, 'submitClear' ) );
703 $form->setSubmitDestructive();
705 return $form;
709 * Determine whether we are editing the watchlist, and if so, what
710 * kind of editing operation
712 * @param WebRequest $request
713 * @param string $par
714 * @return int
716 public static function getMode( $request, $par ) {
717 $mode = strtolower( $request->getVal( 'action', $par ) );
719 switch ( $mode ) {
720 case 'clear':
721 case self::EDIT_CLEAR:
722 return self::EDIT_CLEAR;
723 case 'raw':
724 case self::EDIT_RAW:
725 return self::EDIT_RAW;
726 case 'edit':
727 case self::EDIT_NORMAL:
728 return self::EDIT_NORMAL;
729 default:
730 return false;
735 * Build a set of links for convenient navigation
736 * between watchlist viewing and editing modes
738 * @param null $unused
739 * @return string
741 public static function buildTools( $unused ) {
742 global $wgLang;
744 $tools = array();
745 $modes = array(
746 'view' => array( 'Watchlist', false ),
747 'edit' => array( 'EditWatchlist', false ),
748 'raw' => array( 'EditWatchlist', 'raw' ),
749 'clear' => array( 'EditWatchlist', 'clear' ),
752 foreach ( $modes as $mode => $arr ) {
753 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
754 $tools[] = Linker::linkKnown(
755 SpecialPage::getTitleFor( $arr[0], $arr[1] ),
756 wfMessage( "watchlisttools-{$mode}" )->escaped()
760 return Html::rawElement(
761 'span',
762 array( 'class' => 'mw-watchlist-toollinks' ),
763 wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $tools ) )->escaped()
769 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
771 class EditWatchlistNormalHTMLForm extends HTMLForm {
772 public function getLegend( $namespace ) {
773 $namespace = substr( $namespace, 2 );
775 return $namespace == NS_MAIN
776 ? $this->msg( 'blanknamespace' )->escaped()
777 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
780 public function getBody() {
781 return $this->displaySection( $this->mFieldTree, '', 'editwatchlist-' );
785 class EditWatchlistCheckboxSeriesField extends HTMLMultiSelectField {
787 * HTMLMultiSelectField throws validation errors if we get input data
788 * that doesn't match the data set in the form setup. This causes
789 * problems if something gets removed from the watchlist while the
790 * form is open (bug 32126), but we know that invalid items will
791 * be harmless so we can override it here.
793 * @param string $value The value the field was submitted with
794 * @param array $alldata The data collected from the form
795 * @return bool|string Bool true on success, or String error to display.
797 function validate( $value, $alldata ) {
798 // Need to call into grandparent to be a good citizen. :)
799 return HTMLFormField::validate( $value, $alldata );