Remove useless comments from search output
[mediawiki.git] / includes / specials / SpecialEditWatchlist.php
blob0c860a5b9df0865d866b5deef0dce1d8e885446d
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();
74 $out->addSubtitle( $this->msg( 'watchlistfor2', $this->getUser()->getName() )
75 ->rawParams( SpecialEditWatchlist::buildTools( null ) ) );
77 # B/C: $mode used to be waaay down the parameter list, and the first parameter
78 # was $wgUser
79 if ( $mode instanceof User ) {
80 $args = func_get_args();
81 if ( count( $args ) >= 4 ) {
82 $mode = $args[3];
85 $mode = self::getMode( $this->getRequest(), $mode );
87 switch ( $mode ) {
88 case self::EDIT_RAW:
89 $out->setPageTitle( $this->msg( 'watchlistedit-raw-title' ) );
90 $form = $this->getRawForm();
91 if ( $form->show() ) {
92 $out->addHTML( $this->successMessage );
93 $out->addReturnTo( SpecialPage::getTitleFor( 'Watchlist' ) );
95 break;
97 case self::EDIT_NORMAL:
98 default:
99 $out->setPageTitle( $this->msg( 'watchlistedit-normal-title' ) );
100 $form = $this->getNormalForm();
101 if ( $form->show() ) {
102 $out->addHTML( $this->successMessage );
103 $out->addReturnTo( SpecialPage::getTitleFor( 'Watchlist' ) );
104 } elseif ( $this->toc !== false ) {
105 $out->prependHTML( $this->toc );
106 $out->addModules( 'mediawiki.toc' );
108 break;
113 * Extract a list of titles from a blob of text, returning
114 * (prefixed) strings; unwatchable titles are ignored
116 * @param string $list
117 * @return array
119 private function extractTitles( $list ) {
120 $list = explode( "\n", trim( $list ) );
121 if ( !is_array( $list ) ) {
122 return array();
125 $titles = array();
127 foreach ( $list as $text ) {
128 $text = trim( $text );
129 if ( strlen( $text ) > 0 ) {
130 $title = Title::newFromText( $text );
131 if ( $title instanceof Title && $title->isWatchable() ) {
132 $titles[] = $title;
137 GenderCache::singleton()->doTitlesArray( $titles );
139 $list = array();
140 /** @var Title $title */
141 foreach ( $titles as $title ) {
142 $list[] = $title->getPrefixedText();
145 return array_unique( $list );
148 public function submitRaw( $data ) {
149 $wanted = $this->extractTitles( $data['Titles'] );
150 $current = $this->getWatchlist();
152 if ( count( $wanted ) > 0 ) {
153 $toWatch = array_diff( $wanted, $current );
154 $toUnwatch = array_diff( $current, $wanted );
155 $this->watchTitles( $toWatch );
156 $this->unwatchTitles( $toUnwatch );
157 $this->getUser()->invalidateCache();
159 if ( count( $toWatch ) > 0 || count( $toUnwatch ) > 0 ) {
160 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
161 } else {
162 return false;
165 if ( count( $toWatch ) > 0 ) {
166 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-added' )
167 ->numParams( count( $toWatch ) )->parse();
168 $this->showTitles( $toWatch, $this->successMessage );
171 if ( count( $toUnwatch ) > 0 ) {
172 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed' )
173 ->numParams( count( $toUnwatch ) )->parse();
174 $this->showTitles( $toUnwatch, $this->successMessage );
176 } else {
177 $this->clearWatchlist();
178 $this->getUser()->invalidateCache();
180 if ( count( $current ) > 0 ) {
181 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
182 } else {
183 return false;
186 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed' )
187 ->numParams( count( $current ) )->parse();
188 $this->showTitles( $current, $this->successMessage );
191 return true;
195 * Print out a list of linked titles
197 * $titles can be an array of strings or Title objects; the former
198 * is preferred, since Titles are very memory-heavy
200 * @param array $titles Array of strings, or Title objects
201 * @param string $output
203 private function showTitles( $titles, &$output ) {
204 $talk = $this->msg( 'talkpagelinktext' )->escaped();
205 // Do a batch existence check
206 $batch = new LinkBatch();
207 foreach ( $titles as $title ) {
208 if ( !$title instanceof Title ) {
209 $title = Title::newFromText( $title );
212 if ( $title instanceof Title ) {
213 $batch->addObj( $title );
214 $batch->addObj( $title->getTalkPage() );
218 $batch->execute();
220 // Print out the list
221 $output .= "<ul>\n";
223 foreach ( $titles as $title ) {
224 if ( !$title instanceof Title ) {
225 $title = Title::newFromText( $title );
228 if ( $title instanceof Title ) {
229 $output .= "<li>"
230 . Linker::link( $title )
231 . ' (' . Linker::link( $title->getTalkPage(), $talk )
232 . ")</li>\n";
236 $output .= "</ul>\n";
240 * Prepare a list of titles on a user's watchlist (excluding talk pages)
241 * and return an array of (prefixed) strings
243 * @return array
245 private function getWatchlist() {
246 $list = array();
247 $dbr = wfGetDB( DB_MASTER );
249 $res = $dbr->select(
250 'watchlist',
251 array(
252 'wl_namespace', 'wl_title'
253 ), array(
254 'wl_user' => $this->getUser()->getId(),
256 __METHOD__
259 if ( $res->numRows() > 0 ) {
260 $titles = array();
261 foreach ( $res as $row ) {
262 $title = Title::makeTitleSafe( $row->wl_namespace, $row->wl_title );
264 if ( $this->checkTitle( $title, $row->wl_namespace, $row->wl_title )
265 && !$title->isTalkPage()
267 $titles[] = $title;
270 $res->free();
272 GenderCache::singleton()->doTitlesArray( $titles );
274 foreach ( $titles as $title ) {
275 $list[] = $title->getPrefixedText();
279 $this->cleanupWatchlist();
281 return $list;
285 * Get a list of titles on a user's watchlist, excluding talk pages,
286 * and return as a two-dimensional array with namespace and title.
288 * @return array
290 private function getWatchlistInfo() {
291 $titles = array();
292 $dbr = wfGetDB( DB_MASTER );
294 $res = $dbr->select(
295 array( 'watchlist' ),
296 array( 'wl_namespace', 'wl_title' ),
297 array( 'wl_user' => $this->getUser()->getId() ),
298 __METHOD__,
299 array( 'ORDER BY' => array( 'wl_namespace', 'wl_title' ) )
302 $lb = new LinkBatch();
304 foreach ( $res as $row ) {
305 $lb->add( $row->wl_namespace, $row->wl_title );
306 if ( !MWNamespace::isTalk( $row->wl_namespace ) ) {
307 $titles[$row->wl_namespace][$row->wl_title] = 1;
311 $lb->execute();
313 return $titles;
317 * Validates watchlist entry
319 * @param Title $title
320 * @param int $namespace
321 * @param string $dbKey
322 * @return bool Whether this item is valid
324 private function checkTitle( $title, $namespace, $dbKey ) {
325 if ( $title
326 && ( $title->isExternal()
327 || $title->getNamespace() < 0
330 $title = false; // unrecoverable
333 if ( !$title
334 || $title->getNamespace() != $namespace
335 || $title->getDBkey() != $dbKey
337 $this->badItems[] = array( $title, $namespace, $dbKey );
340 return (bool)$title;
344 * Attempts to clean up broken items
346 private function cleanupWatchlist() {
347 if ( !count( $this->badItems ) ) {
348 return; //nothing to do
351 $dbw = wfGetDB( DB_MASTER );
352 $user = $this->getUser();
354 foreach ( $this->badItems as $row ) {
355 list( $title, $namespace, $dbKey ) = $row;
356 $action = $title ? 'cleaning up' : 'deleting';
357 wfDebug( "User {$user->getName()} has broken watchlist item ns($namespace):$dbKey, $action.\n" );
359 $dbw->delete( 'watchlist',
360 array(
361 'wl_user' => $user->getId(),
362 'wl_namespace' => $namespace,
363 'wl_title' => $dbKey,
365 __METHOD__
368 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
369 if ( $title ) {
370 $user->addWatch( $title );
376 * Remove all titles from a user's watchlist
378 private function clearWatchlist() {
379 $dbw = wfGetDB( DB_MASTER );
380 $dbw->delete(
381 'watchlist',
382 array( 'wl_user' => $this->getUser()->getId() ),
383 __METHOD__
388 * Add a list of titles to a user's watchlist
390 * $titles can be an array of strings or Title objects; the former
391 * is preferred, since Titles are very memory-heavy
393 * @param array $titles Array of strings, or Title objects
395 private function watchTitles( $titles ) {
396 $dbw = wfGetDB( DB_MASTER );
397 $rows = array();
399 foreach ( $titles as $title ) {
400 if ( !$title instanceof Title ) {
401 $title = Title::newFromText( $title );
404 if ( $title instanceof Title ) {
405 $rows[] = array(
406 'wl_user' => $this->getUser()->getId(),
407 'wl_namespace' => MWNamespace::getSubject( $title->getNamespace() ),
408 'wl_title' => $title->getDBkey(),
409 'wl_notificationtimestamp' => null,
411 $rows[] = array(
412 'wl_user' => $this->getUser()->getId(),
413 'wl_namespace' => MWNamespace::getTalk( $title->getNamespace() ),
414 'wl_title' => $title->getDBkey(),
415 'wl_notificationtimestamp' => null,
420 $dbw->insert( 'watchlist', $rows, __METHOD__, 'IGNORE' );
424 * Remove a list of titles from a user's watchlist
426 * $titles can be an array of strings or Title objects; the former
427 * is preferred, since Titles are very memory-heavy
429 * @param array $titles Array of strings, or Title objects
431 private function unwatchTitles( $titles ) {
432 $dbw = wfGetDB( DB_MASTER );
434 foreach ( $titles as $title ) {
435 if ( !$title instanceof Title ) {
436 $title = Title::newFromText( $title );
439 if ( $title instanceof Title ) {
440 $dbw->delete(
441 'watchlist',
442 array(
443 'wl_user' => $this->getUser()->getId(),
444 'wl_namespace' => MWNamespace::getSubject( $title->getNamespace() ),
445 'wl_title' => $title->getDBkey(),
447 __METHOD__
450 $dbw->delete(
451 'watchlist',
452 array(
453 'wl_user' => $this->getUser()->getId(),
454 'wl_namespace' => MWNamespace::getTalk( $title->getNamespace() ),
455 'wl_title' => $title->getDBkey(),
457 __METHOD__
460 $page = WikiPage::factory( $title );
461 wfRunHooks( 'UnwatchArticleComplete', array( $this->getUser(), &$page ) );
466 public function submitNormal( $data ) {
467 $removed = array();
469 foreach ( $data as $titles ) {
470 $this->unwatchTitles( $titles );
471 $removed = array_merge( $removed, $titles );
474 if ( count( $removed ) > 0 ) {
475 $this->successMessage = $this->msg( 'watchlistedit-normal-done'
476 )->numParams( count( $removed ) )->parse();
477 $this->showTitles( $removed, $this->successMessage );
479 return true;
480 } else {
481 return false;
486 * Get the standard watchlist editing form
488 * @return HTMLForm
490 protected function getNormalForm() {
491 global $wgContLang;
493 $fields = array();
494 $count = 0;
496 foreach ( $this->getWatchlistInfo() as $namespace => $pages ) {
497 if ( $namespace >= 0 ) {
498 $fields['TitlesNs' . $namespace] = array(
499 'class' => 'EditWatchlistCheckboxSeriesField',
500 'options' => array(),
501 'section' => "ns$namespace",
505 foreach ( array_keys( $pages ) as $dbkey ) {
506 $title = Title::makeTitleSafe( $namespace, $dbkey );
508 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
509 $text = $this->buildRemoveLine( $title );
510 $fields['TitlesNs' . $namespace]['options'][$text] = $title->getPrefixedText();
511 $count++;
515 $this->cleanupWatchlist();
517 if ( count( $fields ) > 1 && $count > 30 ) {
518 $this->toc = Linker::tocIndent();
519 $tocLength = 0;
521 foreach ( $fields as $data ) {
522 # strip out the 'ns' prefix from the section name:
523 $ns = substr( $data['section'], 2 );
525 $nsText = ( $ns == NS_MAIN )
526 ? $this->msg( 'blanknamespace' )->escaped()
527 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
528 $this->toc .= Linker::tocLine( "editwatchlist-{$data['section']}", $nsText,
529 $this->getLanguage()->formatNum( ++$tocLength ), 1 ) . Linker::tocLineEnd();
532 $this->toc = Linker::tocList( $this->toc );
533 } else {
534 $this->toc = false;
537 $context = new DerivativeContext( $this->getContext() );
538 $context->setTitle( $this->getPageTitle() ); // Remove subpage
539 $form = new EditWatchlistNormalHTMLForm( $fields, $context );
540 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
541 # Used message keys: 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
542 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
543 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
544 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
545 $form->setSubmitCallback( array( $this, 'submitNormal' ) );
547 return $form;
551 * Build the label for a checkbox, with a link to the title, and various additional bits
553 * @param Title $title
554 * @return string
556 private function buildRemoveLine( $title ) {
557 $link = Linker::link( $title );
559 if ( $title->isRedirect() ) {
560 // Linker already makes class mw-redirect, so this is redundant
561 $link = '<span class="watchlistredir">' . $link . '</span>';
564 $tools[] = Linker::link( $title->getTalkPage(), $this->msg( 'talkpagelinktext' )->escaped() );
566 if ( $title->exists() ) {
567 $tools[] = Linker::linkKnown(
568 $title,
569 $this->msg( 'history_short' )->escaped(),
570 array(),
571 array( 'action' => 'history' )
575 if ( $title->getNamespace() == NS_USER && !$title->isSubpage() ) {
576 $tools[] = Linker::linkKnown(
577 SpecialPage::getTitleFor( 'Contributions', $title->getText() ),
578 $this->msg( 'contributions' )->escaped()
582 wfRunHooks( 'WatchlistEditorBuildRemoveLine', array( &$tools, $title, $title->isRedirect(), $this->getSkin() ) );
584 return $link . " (" . $this->getLanguage()->pipeList( $tools ) . ")";
588 * Get a form for editing the watchlist in "raw" mode
590 * @return HTMLForm
592 protected function getRawForm() {
593 $titles = implode( $this->getWatchlist(), "\n" );
594 $fields = array(
595 'Titles' => array(
596 'type' => 'textarea',
597 'label-message' => 'watchlistedit-raw-titles',
598 'default' => $titles,
601 $context = new DerivativeContext( $this->getContext() );
602 $context->setTitle( $this->getPageTitle( 'raw' ) ); // Reset subpage
603 $form = new HTMLForm( $fields, $context );
604 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
605 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
606 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
607 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
608 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
609 $form->setSubmitCallback( array( $this, 'submitRaw' ) );
611 return $form;
615 * Determine whether we are editing the watchlist, and if so, what
616 * kind of editing operation
618 * @param WebRequest $request
619 * @param string $par
620 * @return int
622 public static function getMode( $request, $par ) {
623 $mode = strtolower( $request->getVal( 'action', $par ) );
625 switch ( $mode ) {
626 case 'clear':
627 case self::EDIT_CLEAR:
628 case 'raw':
629 case self::EDIT_RAW:
630 return self::EDIT_RAW;
631 case 'edit':
632 case self::EDIT_NORMAL:
633 return self::EDIT_NORMAL;
634 default:
635 return false;
640 * Build a set of links for convenient navigation
641 * between watchlist viewing and editing modes
643 * @param null $unused
644 * @return string
646 public static function buildTools( $unused ) {
647 global $wgLang;
649 $tools = array();
650 $modes = array(
651 'view' => array( 'Watchlist', false ),
652 'edit' => array( 'EditWatchlist', false ),
653 'raw' => array( 'EditWatchlist', 'raw' ),
656 foreach ( $modes as $mode => $arr ) {
657 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
658 $tools[] = Linker::linkKnown(
659 SpecialPage::getTitleFor( $arr[0], $arr[1] ),
660 wfMessage( "watchlisttools-{$mode}" )->escaped()
664 return Html::rawElement(
665 'span',
666 array( 'class' => 'mw-watchlist-toollinks' ),
667 wfMessage( 'parentheses', $wgLang->pipeList( $tools ) )->text()
672 # B/C since 1.18
673 class WatchlistEditor extends SpecialEditWatchlist {
677 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
679 class EditWatchlistNormalHTMLForm extends HTMLForm {
680 public function getLegend( $namespace ) {
681 $namespace = substr( $namespace, 2 );
683 return $namespace == NS_MAIN
684 ? $this->msg( 'blanknamespace' )->escaped()
685 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
688 public function getBody() {
689 return $this->displaySection( $this->mFieldTree, '', 'editwatchlist-' );
693 class EditWatchlistCheckboxSeriesField extends HTMLMultiSelectField {
695 * HTMLMultiSelectField throws validation errors if we get input data
696 * that doesn't match the data set in the form setup. This causes
697 * problems if something gets removed from the watchlist while the
698 * form is open (bug 32126), but we know that invalid items will
699 * be harmless so we can override it here.
701 * @param string $value the value the field was submitted with
702 * @param array $alldata the data collected from the form
703 * @return bool|string Bool true on success, or String error to display.
705 function validate( $value, $alldata ) {
706 // Need to call into grandparent to be a good citizen. :)
707 return HTMLFormField::validate( $value, $alldata );