Merge "Whitelist the <wbr> element."
[mediawiki.git] / includes / specials / SpecialEditWatchlist.php
blobb6005de4e51aed89fd763706cde3b425d37d6082
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 $form = new EditWatchlistNormalHTMLForm( $fields, $this->getContext() );
551 $form->setTitle( $this->getTitle() );
552 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
553 # Used message keys: 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
554 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
555 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
556 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
557 $form->setSubmitCallback( array( $this, 'submitNormal' ) );
559 return $form;
563 * Build the label for a checkbox, with a link to the title, and various additional bits
565 * @param $title Title
566 * @return string
568 private function buildRemoveLine( $title ) {
569 $link = Linker::link( $title );
571 if ( $title->isRedirect() ) {
572 // Linker already makes class mw-redirect, so this is redundant
573 $link = '<span class="watchlistredir">' . $link . '</span>';
576 $tools[] = Linker::link( $title->getTalkPage(), $this->msg( 'talkpagelinktext' )->escaped() );
578 if ( $title->exists() ) {
579 $tools[] = Linker::linkKnown(
580 $title,
581 $this->msg( 'history_short' )->escaped(),
582 array(),
583 array( 'action' => 'history' )
587 if ( $title->getNamespace() == NS_USER && !$title->isSubpage() ) {
588 $tools[] = Linker::linkKnown(
589 SpecialPage::getTitleFor( 'Contributions', $title->getText() ),
590 $this->msg( 'contributions' )->escaped()
594 wfRunHooks( 'WatchlistEditorBuildRemoveLine', array( &$tools, $title, $title->isRedirect(), $this->getSkin() ) );
596 return $link . " (" . $this->getLanguage()->pipeList( $tools ) . ")";
600 * Get a form for editing the watchlist in "raw" mode
602 * @return HTMLForm
604 protected function getRawForm() {
605 $titles = implode( $this->getWatchlist(), "\n" );
606 $fields = array(
607 'Titles' => array(
608 'type' => 'textarea',
609 'label-message' => 'watchlistedit-raw-titles',
610 'default' => $titles,
613 $form = new HTMLForm( $fields, $this->getContext() );
614 $form->setTitle( $this->getTitle( 'raw' ) );
615 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
616 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
617 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
618 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
619 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
620 $form->setSubmitCallback( array( $this, 'submitRaw' ) );
622 return $form;
626 * Determine whether we are editing the watchlist, and if so, what
627 * kind of editing operation
629 * @param $request WebRequest
630 * @param $par mixed
631 * @return int
633 public static function getMode( $request, $par ) {
634 $mode = strtolower( $request->getVal( 'action', $par ) );
636 switch ( $mode ) {
637 case 'clear':
638 case self::EDIT_CLEAR:
639 return self::EDIT_CLEAR;
640 case 'raw':
641 case self::EDIT_RAW:
642 return self::EDIT_RAW;
643 case 'edit':
644 case self::EDIT_NORMAL:
645 return self::EDIT_NORMAL;
646 default:
647 return false;
652 * Build a set of links for convenient navigation
653 * between watchlist viewing and editing modes
655 * @param $unused
656 * @return string
658 public static function buildTools( $unused ) {
659 global $wgLang;
661 $tools = array();
662 $modes = array(
663 'view' => array( 'Watchlist', false ),
664 'edit' => array( 'EditWatchlist', false ),
665 'raw' => array( 'EditWatchlist', 'raw' ),
668 foreach ( $modes as $mode => $arr ) {
669 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
670 $tools[] = Linker::linkKnown(
671 SpecialPage::getTitleFor( $arr[0], $arr[1] ),
672 wfMessage( "watchlisttools-{$mode}" )->escaped()
676 return Html::rawElement(
677 'span',
678 array( 'class' => 'mw-watchlist-toollinks' ),
679 wfMessage( 'parentheses', $wgLang->pipeList( $tools ) )->text()
684 # B/C since 1.18
685 class WatchlistEditor extends SpecialEditWatchlist {
689 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
691 class EditWatchlistNormalHTMLForm extends HTMLForm {
692 public function getLegend( $namespace ) {
693 $namespace = substr( $namespace, 2 );
695 return $namespace == NS_MAIN
696 ? $this->msg( 'blanknamespace' )->escaped()
697 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
700 public function getBody() {
701 return $this->displaySection( $this->mFieldTree, '', 'editwatchlist-' );
705 class EditWatchlistCheckboxSeriesField extends HTMLMultiSelectField {
707 * HTMLMultiSelectField throws validation errors if we get input data
708 * that doesn't match the data set in the form setup. This causes
709 * problems if something gets removed from the watchlist while the
710 * form is open (bug 32126), but we know that invalid items will
711 * be harmless so we can override it here.
713 * @param string $value the value the field was submitted with
714 * @param array $alldata the data collected from the form
715 * @return Mixed Bool true on success, or String error to display.
717 function validate( $value, $alldata ) {
718 // Need to call into grandparent to be a good citizen. :)
719 return HTMLFormField::validate( $value, $alldata );