Merge "Avoid fatal in ContentHandler::getUndoContent by null content"
[mediawiki.git] / includes / specials / SpecialEditWatchlist.php
blob501552e91ff64ccf4f0f236e4e0651707e82d5d7
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
41 const EDIT_CLEAR = 1;
42 const EDIT_RAW = 2;
43 const EDIT_NORMAL = 3;
45 protected $successMessage;
47 protected $toc;
49 private $badItems = array();
51 public function __construct() {
52 parent::__construct( 'EditWatchlist', 'editmywatchlist' );
55 /**
56 * Main execution point
58 * @param $mode int
60 public function execute( $mode ) {
61 $this->setHeaders();
63 $out = $this->getOutput();
65 # Anons don't get a watchlist
66 if ( $this->getUser()->isAnon() ) {
67 $out->setPageTitle( $this->msg( 'watchnologin' ) );
68 $llink = Linker::linkKnown(
69 SpecialPage::getTitleFor( 'Userlogin' ),
70 $this->msg( 'loginreqlink' )->escaped(),
71 array(),
72 array( 'returnto' => $this->getTitle()->getPrefixedText() )
74 $out->addHTML( $this->msg( 'watchlistanontext' )->rawParams( $llink )->parse() );
76 return;
79 $this->checkPermissions();
80 $this->checkReadOnly();
82 $this->outputHeader();
84 $out->addSubtitle( $this->msg( 'watchlistfor2', $this->getUser()->getName() )
85 ->rawParams( SpecialEditWatchlist::buildTools( null ) ) );
87 # B/C: $mode used to be waaay down the parameter list, and the first parameter
88 # was $wgUser
89 if ( $mode instanceof User ) {
90 $args = func_get_args();
91 if ( count( $args ) >= 4 ) {
92 $mode = $args[3];
95 $mode = self::getMode( $this->getRequest(), $mode );
97 switch ( $mode ) {
98 case self::EDIT_CLEAR:
99 // The "Clear" link scared people too much.
100 // Pass on to the raw editor, from which it's very easy to clear.
102 case self::EDIT_RAW:
103 $out->setPageTitle( $this->msg( 'watchlistedit-raw-title' ) );
104 $form = $this->getRawForm();
105 if ( $form->show() ) {
106 $out->addHTML( $this->successMessage );
107 $out->addReturnTo( SpecialPage::getTitleFor( 'Watchlist' ) );
109 break;
111 case self::EDIT_NORMAL:
112 default:
113 $out->setPageTitle( $this->msg( 'watchlistedit-normal-title' ) );
114 $form = $this->getNormalForm();
115 if ( $form->show() ) {
116 $out->addHTML( $this->successMessage );
117 $out->addReturnTo( SpecialPage::getTitleFor( 'Watchlist' ) );
118 } elseif ( $this->toc !== false ) {
119 $out->prependHTML( $this->toc );
121 break;
126 * Extract a list of titles from a blob of text, returning
127 * (prefixed) strings; unwatchable titles are ignored
129 * @param $list String
130 * @return array
132 private function extractTitles( $list ) {
133 $list = explode( "\n", trim( $list ) );
134 if ( !is_array( $list ) ) {
135 return array();
138 $titles = array();
140 foreach ( $list as $text ) {
141 $text = trim( $text );
142 if ( strlen( $text ) > 0 ) {
143 $title = Title::newFromText( $text );
144 if ( $title instanceof Title && $title->isWatchable() ) {
145 $titles[] = $title;
150 GenderCache::singleton()->doTitlesArray( $titles );
152 $list = array();
153 /** @var Title $title */
154 foreach ( $titles as $title ) {
155 $list[] = $title->getPrefixedText();
158 return array_unique( $list );
161 public function submitRaw( $data ) {
162 $wanted = $this->extractTitles( $data['Titles'] );
163 $current = $this->getWatchlist();
165 if ( count( $wanted ) > 0 ) {
166 $toWatch = array_diff( $wanted, $current );
167 $toUnwatch = array_diff( $current, $wanted );
168 $this->watchTitles( $toWatch );
169 $this->unwatchTitles( $toUnwatch );
170 $this->getUser()->invalidateCache();
172 if ( count( $toWatch ) > 0 || count( $toUnwatch ) > 0 ) {
173 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
174 } else {
175 return false;
178 if ( count( $toWatch ) > 0 ) {
179 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-added'
180 )->numParams( count( $toWatch ) )->parse();
181 $this->showTitles( $toWatch, $this->successMessage );
184 if ( count( $toUnwatch ) > 0 ) {
185 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed'
186 )->numParams( count( $toUnwatch ) )->parse();
187 $this->showTitles( $toUnwatch, $this->successMessage );
189 } else {
190 $this->clearWatchlist();
191 $this->getUser()->invalidateCache();
193 if ( count( $current ) > 0 ) {
194 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
195 } else {
196 return false;
199 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed' )
200 ->numParams( count( $current ) )->parse();
201 $this->showTitles( $current, $this->successMessage );
204 return true;
208 * Print out a list of linked titles
210 * $titles can be an array of strings or Title objects; the former
211 * is preferred, since Titles are very memory-heavy
213 * @param array $titles of strings, or Title objects
214 * @param $output String
216 private function showTitles( $titles, &$output ) {
217 $talk = $this->msg( 'talkpagelinktext' )->escaped();
218 // Do a batch existence check
219 $batch = new LinkBatch();
220 foreach ( $titles as $title ) {
221 if ( !$title instanceof Title ) {
222 $title = Title::newFromText( $title );
225 if ( $title instanceof Title ) {
226 $batch->addObj( $title );
227 $batch->addObj( $title->getTalkPage() );
231 $batch->execute();
233 // Print out the list
234 $output .= "<ul>\n";
236 foreach ( $titles as $title ) {
237 if ( !$title instanceof Title ) {
238 $title = Title::newFromText( $title );
241 if ( $title instanceof Title ) {
242 $output .= "<li>"
243 . Linker::link( $title )
244 . ' (' . Linker::link( $title->getTalkPage(), $talk )
245 . ")</li>\n";
249 $output .= "</ul>\n";
253 * Prepare a list of titles on a user's watchlist (excluding talk pages)
254 * and return an array of (prefixed) strings
256 * @return array
258 private function getWatchlist() {
259 $list = array();
260 $dbr = wfGetDB( DB_MASTER );
262 $res = $dbr->select(
263 'watchlist',
264 array(
265 'wl_namespace', 'wl_title'
266 ), array(
267 'wl_user' => $this->getUser()->getId(),
269 __METHOD__
272 if ( $res->numRows() > 0 ) {
273 $titles = array();
274 foreach ( $res as $row ) {
275 $title = Title::makeTitleSafe( $row->wl_namespace, $row->wl_title );
277 if ( $this->checkTitle( $title, $row->wl_namespace, $row->wl_title )
278 && !$title->isTalkPage()
280 $titles[] = $title;
283 $res->free();
285 GenderCache::singleton()->doTitlesArray( $titles );
287 foreach ( $titles as $title ) {
288 $list[] = $title->getPrefixedText();
292 $this->cleanupWatchlist();
294 return $list;
298 * Get a list of titles on a user's watchlist, excluding talk pages,
299 * and return as a two-dimensional array with namespace and title.
301 * @return array
303 private function getWatchlistInfo() {
304 $titles = array();
305 $dbr = wfGetDB( DB_MASTER );
307 $res = $dbr->select(
308 array( 'watchlist' ),
309 array( 'wl_namespace', 'wl_title' ),
310 array( 'wl_user' => $this->getUser()->getId() ),
311 __METHOD__,
312 array( 'ORDER BY' => array( 'wl_namespace', 'wl_title' ) )
315 $lb = new LinkBatch();
317 foreach ( $res as $row ) {
318 $lb->add( $row->wl_namespace, $row->wl_title );
319 if ( !MWNamespace::isTalk( $row->wl_namespace ) ) {
320 $titles[$row->wl_namespace][$row->wl_title] = 1;
324 $lb->execute();
326 return $titles;
330 * Validates watchlist entry
332 * @param Title $title
333 * @param int $namespace
334 * @param string $dbKey
335 * @return bool: Whether this item is valid
337 private function checkTitle( $title, $namespace, $dbKey ) {
338 if ( $title
339 && ( $title->isExternal()
340 || $title->getNamespace() < 0
343 $title = false; // unrecoverable
346 if ( !$title
347 || $title->getNamespace() != $namespace
348 || $title->getDBkey() != $dbKey
350 $this->badItems[] = array( $title, $namespace, $dbKey );
353 return (bool)$title;
357 * Attempts to clean up broken items
359 private function cleanupWatchlist() {
360 if ( !count( $this->badItems ) ) {
361 return; //nothing to do
364 $dbw = wfGetDB( DB_MASTER );
365 $user = $this->getUser();
367 foreach ( $this->badItems as $row ) {
368 list( $title, $namespace, $dbKey ) = $row;
369 $action = $title ? 'cleaning up' : 'deleting';
370 wfDebug( "User {$user->getName()} has broken watchlist item ns($namespace):$dbKey, $action.\n" );
372 $dbw->delete( 'watchlist',
373 array(
374 'wl_user' => $user->getId(),
375 'wl_namespace' => $namespace,
376 'wl_title' => $dbKey,
378 __METHOD__
381 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
382 if ( $title ) {
383 $user->addWatch( $title );
389 * Remove all titles from a user's watchlist
391 private function clearWatchlist() {
392 $dbw = wfGetDB( DB_MASTER );
393 $dbw->delete(
394 'watchlist',
395 array( 'wl_user' => $this->getUser()->getId() ),
396 __METHOD__
401 * Add a list of titles to a user's watchlist
403 * $titles can be an array of strings or Title objects; the former
404 * is preferred, since Titles are very memory-heavy
406 * @param array $titles of strings, or Title objects
408 private function watchTitles( $titles ) {
409 $dbw = wfGetDB( DB_MASTER );
410 $rows = array();
412 foreach ( $titles as $title ) {
413 if ( !$title instanceof Title ) {
414 $title = Title::newFromText( $title );
417 if ( $title instanceof Title ) {
418 $rows[] = array(
419 'wl_user' => $this->getUser()->getId(),
420 'wl_namespace' => MWNamespace::getSubject( $title->getNamespace() ),
421 'wl_title' => $title->getDBkey(),
422 'wl_notificationtimestamp' => null,
424 $rows[] = array(
425 'wl_user' => $this->getUser()->getId(),
426 'wl_namespace' => MWNamespace::getTalk( $title->getNamespace() ),
427 'wl_title' => $title->getDBkey(),
428 'wl_notificationtimestamp' => null,
433 $dbw->insert( 'watchlist', $rows, __METHOD__, 'IGNORE' );
437 * Remove a list of titles from a user's watchlist
439 * $titles can be an array of strings or Title objects; the former
440 * is preferred, since Titles are very memory-heavy
442 * @param array $titles of strings, or Title objects
444 private function unwatchTitles( $titles ) {
445 $dbw = wfGetDB( DB_MASTER );
447 foreach ( $titles as $title ) {
448 if ( !$title instanceof Title ) {
449 $title = Title::newFromText( $title );
452 if ( $title instanceof Title ) {
453 $dbw->delete(
454 'watchlist',
455 array(
456 'wl_user' => $this->getUser()->getId(),
457 'wl_namespace' => MWNamespace::getSubject( $title->getNamespace() ),
458 'wl_title' => $title->getDBkey(),
460 __METHOD__
463 $dbw->delete(
464 'watchlist',
465 array(
466 'wl_user' => $this->getUser()->getId(),
467 'wl_namespace' => MWNamespace::getTalk( $title->getNamespace() ),
468 'wl_title' => $title->getDBkey(),
470 __METHOD__
473 $page = WikiPage::factory( $title );
474 wfRunHooks( 'UnwatchArticleComplete', array( $this->getUser(), &$page ) );
479 public function submitNormal( $data ) {
480 $removed = array();
482 foreach ( $data as $titles ) {
483 $this->unwatchTitles( $titles );
484 $removed = array_merge( $removed, $titles );
487 if ( count( $removed ) > 0 ) {
488 $this->successMessage = $this->msg( 'watchlistedit-normal-done'
489 )->numParams( count( $removed ) )->parse();
490 $this->showTitles( $removed, $this->successMessage );
492 return true;
493 } else {
494 return false;
499 * Get the standard watchlist editing form
501 * @return HTMLForm
503 protected function getNormalForm() {
504 global $wgContLang;
506 $fields = array();
507 $count = 0;
509 foreach ( $this->getWatchlistInfo() as $namespace => $pages ) {
510 if ( $namespace >= 0 ) {
511 $fields['TitlesNs' . $namespace] = array(
512 'class' => 'EditWatchlistCheckboxSeriesField',
513 'options' => array(),
514 'section' => "ns$namespace",
518 foreach ( array_keys( $pages ) as $dbkey ) {
519 $title = Title::makeTitleSafe( $namespace, $dbkey );
521 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
522 $text = $this->buildRemoveLine( $title );
523 $fields['TitlesNs' . $namespace]['options'][$text] = $title->getPrefixedText();
524 $count++;
528 $this->cleanupWatchlist();
530 if ( count( $fields ) > 1 && $count > 30 ) {
531 $this->toc = Linker::tocIndent();
532 $tocLength = 0;
534 foreach ( $fields as $data ) {
535 # strip out the 'ns' prefix from the section name:
536 $ns = substr( $data['section'], 2 );
538 $nsText = ( $ns == NS_MAIN )
539 ? $this->msg( 'blanknamespace' )->escaped()
540 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
541 $this->toc .= Linker::tocLine( "editwatchlist-{$data['section']}", $nsText,
542 $this->getLanguage()->formatNum( ++$tocLength ), 1 ) . Linker::tocLineEnd();
545 $this->toc = Linker::tocList( $this->toc );
546 } else {
547 $this->toc = false;
550 $context = new DerivativeContext( $this->getContext() );
551 $context->setTitle( $this->getTitle() ); // Remove subpage
552 $form = new EditWatchlistNormalHTMLForm( $fields, $context );
553 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
554 # Used message keys: 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
555 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
556 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
557 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
558 $form->setSubmitCallback( array( $this, 'submitNormal' ) );
560 return $form;
564 * Build the label for a checkbox, with a link to the title, and various additional bits
566 * @param $title Title
567 * @return string
569 private function buildRemoveLine( $title ) {
570 $link = Linker::link( $title );
572 if ( $title->isRedirect() ) {
573 // Linker already makes class mw-redirect, so this is redundant
574 $link = '<span class="watchlistredir">' . $link . '</span>';
577 $tools[] = Linker::link( $title->getTalkPage(), $this->msg( 'talkpagelinktext' )->escaped() );
579 if ( $title->exists() ) {
580 $tools[] = Linker::linkKnown(
581 $title,
582 $this->msg( 'history_short' )->escaped(),
583 array(),
584 array( 'action' => 'history' )
588 if ( $title->getNamespace() == NS_USER && !$title->isSubpage() ) {
589 $tools[] = Linker::linkKnown(
590 SpecialPage::getTitleFor( 'Contributions', $title->getText() ),
591 $this->msg( 'contributions' )->escaped()
595 wfRunHooks( 'WatchlistEditorBuildRemoveLine', array( &$tools, $title, $title->isRedirect(), $this->getSkin() ) );
597 return $link . " (" . $this->getLanguage()->pipeList( $tools ) . ")";
601 * Get a form for editing the watchlist in "raw" mode
603 * @return HTMLForm
605 protected function getRawForm() {
606 $titles = implode( $this->getWatchlist(), "\n" );
607 $fields = array(
608 'Titles' => array(
609 'type' => 'textarea',
610 'label-message' => 'watchlistedit-raw-titles',
611 'default' => $titles,
614 $context = new DerivativeContext( $this->getContext() );
615 $context->setTitle( $this->getTitle( 'raw' ) ); // Reset subpage
616 $form = new HTMLForm( $fields, $context );
617 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
618 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
619 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
620 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
621 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
622 $form->setSubmitCallback( array( $this, 'submitRaw' ) );
624 return $form;
628 * Determine whether we are editing the watchlist, and if so, what
629 * kind of editing operation
631 * @param $request WebRequest
632 * @param $par mixed
633 * @return int
635 public static function getMode( $request, $par ) {
636 $mode = strtolower( $request->getVal( 'action', $par ) );
638 switch ( $mode ) {
639 case 'clear':
640 case self::EDIT_CLEAR:
641 return self::EDIT_CLEAR;
642 case 'raw':
643 case self::EDIT_RAW:
644 return self::EDIT_RAW;
645 case 'edit':
646 case self::EDIT_NORMAL:
647 return self::EDIT_NORMAL;
648 default:
649 return false;
654 * Build a set of links for convenient navigation
655 * between watchlist viewing and editing modes
657 * @param $unused
658 * @return string
660 public static function buildTools( $unused ) {
661 global $wgLang;
663 $tools = array();
664 $modes = array(
665 'view' => array( 'Watchlist', false ),
666 'edit' => array( 'EditWatchlist', false ),
667 'raw' => array( 'EditWatchlist', 'raw' ),
670 foreach ( $modes as $mode => $arr ) {
671 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
672 $tools[] = Linker::linkKnown(
673 SpecialPage::getTitleFor( $arr[0], $arr[1] ),
674 wfMessage( "watchlisttools-{$mode}" )->escaped()
678 return Html::rawElement(
679 'span',
680 array( 'class' => 'mw-watchlist-toollinks' ),
681 wfMessage( 'parentheses', $wgLang->pipeList( $tools ) )->text()
686 # B/C since 1.18
687 class WatchlistEditor extends SpecialEditWatchlist {
691 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
693 class EditWatchlistNormalHTMLForm extends HTMLForm {
694 public function getLegend( $namespace ) {
695 $namespace = substr( $namespace, 2 );
697 return $namespace == NS_MAIN
698 ? $this->msg( 'blanknamespace' )->escaped()
699 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
702 public function getBody() {
703 return $this->displaySection( $this->mFieldTree, '', 'editwatchlist-' );
707 class EditWatchlistCheckboxSeriesField extends HTMLMultiSelectField {
709 * HTMLMultiSelectField throws validation errors if we get input data
710 * that doesn't match the data set in the form setup. This causes
711 * problems if something gets removed from the watchlist while the
712 * form is open (bug 32126), but we know that invalid items will
713 * be harmless so we can override it here.
715 * @param string $value the value the field was submitted with
716 * @param array $alldata the data collected from the form
717 * @return Mixed Bool true on success, or String error to display.
719 function validate( $value, $alldata ) {
720 // Need to call into grandparent to be a good citizen. :)
721 return HTMLFormField::validate( $value, $alldata );