Consistency tweak: Wrap variable names into <code></code>
[mediawiki.git] / includes / specials / SpecialEditWatchlist.php
blobad06d5f5b5e7cfdbd08a57c3cbdb569f1c097c22
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 {
39 /**
40 * Editing modes
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' );
56 /**
57 * Main execution point
59 * @param $mode int
61 public function execute( $mode ) {
62 $this->setHeaders();
64 $out = $this->getOutput();
66 # Anons don't get a watchlist
67 if( $this->getUser()->isAnon() ) {
68 $out->setPageTitle( $this->msg( 'watchnologin' ) );
69 $llink = Linker::linkKnown(
70 SpecialPage::getTitleFor( 'Userlogin' ),
71 $this->msg( 'loginreqlink' )->escaped(),
72 array(),
73 array( 'returnto' => $this->getTitle()->getPrefixedText() )
75 $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();
137 $titles = array();
138 foreach( $list as $text ) {
139 $text = trim( $text );
140 if( strlen( $text ) > 0 ) {
141 $title = Title::newFromText( $text );
142 if( $title instanceof Title && $title->isWatchable() ) {
143 $titles[] = $title;
148 GenderCache::singleton()->doTitlesArray( $titles );
150 $list = array();
151 foreach( $titles as $title ) {
152 $list[] = $title->getPrefixedText();
154 return array_unique( $list );
157 public function submitRaw( $data ) {
158 $wanted = $this->extractTitles( $data['Titles'] );
159 $current = $this->getWatchlist();
161 if( count( $wanted ) > 0 ) {
162 $toWatch = array_diff( $wanted, $current );
163 $toUnwatch = array_diff( $current, $wanted );
164 $this->watchTitles( $toWatch );
165 $this->unwatchTitles( $toUnwatch );
166 $this->getUser()->invalidateCache();
168 if( count( $toWatch ) > 0 || count( $toUnwatch ) > 0 ) {
169 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
170 } else {
171 return false;
174 if( count( $toWatch ) > 0 ) {
175 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-added'
176 )->numParams( count( $toWatch ) )->parse();
177 $this->showTitles( $toWatch, $this->successMessage );
180 if( count( $toUnwatch ) > 0 ) {
181 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed'
182 )->numParams( count( $toUnwatch ) )->parse();
183 $this->showTitles( $toUnwatch, $this->successMessage );
185 } else {
186 $this->clearWatchlist();
187 $this->getUser()->invalidateCache();
189 if( count( $current ) > 0 ) {
190 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
191 } else {
192 return false;
195 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed'
196 )->numParams( count( $current ) )->parse();
197 $this->showTitles( $current, $this->successMessage );
199 return true;
203 * Print out a list of linked titles
205 * $titles can be an array of strings or Title objects; the former
206 * is preferred, since Titles are very memory-heavy
208 * @param array $titles of strings, or Title objects
209 * @param $output String
211 private function showTitles( $titles, &$output ) {
212 $talk = $this->msg( 'talkpagelinktext' )->escaped();
213 // Do a batch existence check
214 $batch = new LinkBatch();
215 foreach( $titles as $title ) {
216 if( !$title instanceof Title ) {
217 $title = Title::newFromText( $title );
219 if( $title instanceof Title ) {
220 $batch->addObj( $title );
221 $batch->addObj( $title->getTalkPage() );
224 $batch->execute();
225 // Print out the list
226 $output .= "<ul>\n";
227 foreach( $titles as $title ) {
228 if( !$title instanceof Title ) {
229 $title = Title::newFromText( $title );
231 if( $title instanceof Title ) {
232 $output .= "<li>"
233 . Linker::link( $title )
234 . ' (' . Linker::link( $title->getTalkPage(), $talk )
235 . ")</li>\n";
238 $output .= "</ul>\n";
242 * Prepare a list of titles on a user's watchlist (excluding talk pages)
243 * and return an array of (prefixed) strings
245 * @return array
247 private function getWatchlist() {
248 $list = array();
249 $dbr = wfGetDB( DB_MASTER );
250 $res = $dbr->select(
251 'watchlist',
252 array(
253 'wl_namespace', 'wl_title'
254 ), array(
255 'wl_user' => $this->getUser()->getId(),
257 __METHOD__
259 if( $res->numRows() > 0 ) {
260 $titles = array();
261 foreach ( $res as $row ) {
262 $title = Title::makeTitleSafe( $row->wl_namespace, $row->wl_title );
263 if ( $this->checkTitle( $title, $row->wl_namespace, $row->wl_title )
264 && !$title->isTalkPage()
266 $titles[] = $title;
269 $res->free();
271 GenderCache::singleton()->doTitlesArray( $titles );
273 foreach( $titles as $title ) {
274 $list[] = $title->getPrefixedText();
277 $this->cleanupWatchlist();
278 return $list;
282 * Get a list of titles on a user's watchlist, excluding talk pages,
283 * and return as a two-dimensional array with namespace and title.
285 * @return array
287 private function getWatchlistInfo() {
288 $titles = array();
289 $dbr = wfGetDB( DB_MASTER );
291 $res = $dbr->select(
292 array( 'watchlist' ),
293 array( 'wl_namespace', 'wl_title' ),
294 array( 'wl_user' => $this->getUser()->getId() ),
295 __METHOD__,
296 array( 'ORDER BY' => array( 'wl_namespace', 'wl_title' ) )
299 $lb = new LinkBatch();
300 foreach ( $res as $row ) {
301 $lb->add( $row->wl_namespace, $row->wl_title );
302 if ( !MWNamespace::isTalk( $row->wl_namespace ) ) {
303 $titles[$row->wl_namespace][$row->wl_title] = 1;
307 $lb->execute();
308 return $titles;
312 * Validates watchlist entry
314 * @param Title $title
315 * @param int $namespace
316 * @param string $dbKey
317 * @return bool: Whether this item is valid
319 private function checkTitle( $title, $namespace, $dbKey ) {
320 if ( $title
321 && ( $title->isExternal()
322 || $title->getNamespace() < 0
325 $title = false; // unrecoverable
327 if ( !$title
328 || $title->getNamespace() != $namespace
329 || $title->getDBkey() != $dbKey
331 $this->badItems[] = array( $title, $namespace, $dbKey );
333 return (bool)$title;
337 * Attempts to clean up broken items
339 private function cleanupWatchlist() {
340 if( !count( $this->badItems ) ) {
341 return; //nothing to do
343 $dbw = wfGetDB( DB_MASTER );
344 $user = $this->getUser();
345 foreach ( $this->badItems as $row ) {
346 list( $title, $namespace, $dbKey ) = $row;
347 wfDebug( "User {$user->getName()} has broken watchlist item ns($namespace):$dbKey, "
348 . ( $title ? 'cleaning up' : 'deleting' ) . ".\n"
351 $dbw->delete( 'watchlist',
352 array(
353 'wl_user' => $user->getId(),
354 'wl_namespace' => $namespace,
355 'wl_title' => $dbKey,
357 __METHOD__
360 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
361 if ( $title ) {
362 $user->addWatch( $title );
368 * Remove all titles from a user's watchlist
370 private function clearWatchlist() {
371 $dbw = wfGetDB( DB_MASTER );
372 $dbw->delete(
373 'watchlist',
374 array( 'wl_user' => $this->getUser()->getId() ),
375 __METHOD__
380 * Add a list of titles to a user's watchlist
382 * $titles can be an array of strings or Title objects; the former
383 * is preferred, since Titles are very memory-heavy
385 * @param array $titles of strings, or Title objects
387 private function watchTitles( $titles ) {
388 $dbw = wfGetDB( DB_MASTER );
389 $rows = array();
390 foreach( $titles as $title ) {
391 if( !$title instanceof Title ) {
392 $title = Title::newFromText( $title );
394 if( $title instanceof Title ) {
395 $rows[] = array(
396 'wl_user' => $this->getUser()->getId(),
397 'wl_namespace' => MWNamespace::getSubject( $title->getNamespace() ),
398 'wl_title' => $title->getDBkey(),
399 'wl_notificationtimestamp' => null,
401 $rows[] = array(
402 'wl_user' => $this->getUser()->getId(),
403 'wl_namespace' => MWNamespace::getTalk( $title->getNamespace() ),
404 'wl_title' => $title->getDBkey(),
405 'wl_notificationtimestamp' => null,
409 $dbw->insert( 'watchlist', $rows, __METHOD__, 'IGNORE' );
413 * Remove a list of titles from a user's watchlist
415 * $titles can be an array of strings or Title objects; the former
416 * is preferred, since Titles are very memory-heavy
418 * @param array $titles of strings, or Title objects
420 private function unwatchTitles( $titles ) {
421 $dbw = wfGetDB( DB_MASTER );
422 foreach( $titles as $title ) {
423 if( !$title instanceof Title ) {
424 $title = Title::newFromText( $title );
426 if( $title instanceof Title ) {
427 $dbw->delete(
428 'watchlist',
429 array(
430 'wl_user' => $this->getUser()->getId(),
431 'wl_namespace' => MWNamespace::getSubject( $title->getNamespace() ),
432 'wl_title' => $title->getDBkey(),
434 __METHOD__
436 $dbw->delete(
437 'watchlist',
438 array(
439 'wl_user' => $this->getUser()->getId(),
440 'wl_namespace' => MWNamespace::getTalk( $title->getNamespace() ),
441 'wl_title' => $title->getDBkey(),
443 __METHOD__
445 $page = WikiPage::factory( $title );
446 wfRunHooks( 'UnwatchArticleComplete', array( $this->getUser(), &$page ) );
451 public function submitNormal( $data ) {
452 $removed = array();
454 foreach( $data as $titles ) {
455 $this->unwatchTitles( $titles );
456 $removed = array_merge( $removed, $titles );
459 if( count( $removed ) > 0 ) {
460 $this->successMessage = $this->msg( 'watchlistedit-normal-done'
461 )->numParams( count( $removed ) )->parse();
462 $this->showTitles( $removed, $this->successMessage );
463 return true;
464 } else {
465 return false;
470 * Get the standard watchlist editing form
472 * @return HTMLForm
474 protected function getNormalForm() {
475 global $wgContLang;
477 $fields = array();
478 $count = 0;
480 foreach( $this->getWatchlistInfo() as $namespace => $pages ) {
481 if ( $namespace >= 0 ) {
482 $fields['TitlesNs' . $namespace] = array(
483 'class' => 'EditWatchlistCheckboxSeriesField',
484 'options' => array(),
485 'section' => "ns$namespace",
489 foreach( array_keys( $pages ) as $dbkey ) {
490 $title = Title::makeTitleSafe( $namespace, $dbkey );
491 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
492 $text = $this->buildRemoveLine( $title );
493 $fields['TitlesNs' . $namespace]['options'][$text] = $title->getPrefixedText();
494 $count++;
498 $this->cleanupWatchlist();
500 if ( count( $fields ) > 1 && $count > 30 ) {
501 $this->toc = Linker::tocIndent();
502 $tocLength = 0;
503 foreach( $fields as $data ) {
505 # strip out the 'ns' prefix from the section name:
506 $ns = substr( $data['section'], 2 );
508 $nsText = ($ns == NS_MAIN)
509 ? $this->msg( 'blanknamespace' )->escaped()
510 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
511 $this->toc .= Linker::tocLine( "editwatchlist-{$data['section']}", $nsText,
512 $this->getLanguage()->formatNum( ++$tocLength ), 1 ) . Linker::tocLineEnd();
514 $this->toc = Linker::tocList( $this->toc );
515 } else {
516 $this->toc = false;
519 $form = new EditWatchlistNormalHTMLForm( $fields, $this->getContext() );
520 $form->setTitle( $this->getTitle() );
521 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
522 # Used message keys: 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
523 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
524 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
525 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
526 $form->setSubmitCallback( array( $this, 'submitNormal' ) );
527 return $form;
531 * Build the label for a checkbox, with a link to the title, and various additional bits
533 * @param $title Title
534 * @return string
536 private function buildRemoveLine( $title ) {
537 $link = Linker::link( $title );
538 if( $title->isRedirect() ) {
539 // Linker already makes class mw-redirect, so this is redundant
540 $link = '<span class="watchlistredir">' . $link . '</span>';
542 $tools[] = Linker::link( $title->getTalkPage(), $this->msg( 'talkpagelinktext' )->escaped() );
543 if( $title->exists() ) {
544 $tools[] = Linker::linkKnown(
545 $title,
546 $this->msg( 'history_short' )->escaped(),
547 array(),
548 array( 'action' => 'history' )
551 if( $title->getNamespace() == NS_USER && !$title->isSubpage() ) {
552 $tools[] = Linker::linkKnown(
553 SpecialPage::getTitleFor( 'Contributions', $title->getText() ),
554 $this->msg( 'contributions' )->escaped()
558 wfRunHooks( 'WatchlistEditorBuildRemoveLine', array( &$tools, $title, $title->isRedirect(), $this->getSkin() ) );
560 return $link . " (" . $this->getLanguage()->pipeList( $tools ) . ")";
564 * Get a form for editing the watchlist in "raw" mode
566 * @return HTMLForm
568 protected function getRawForm() {
569 $titles = implode( $this->getWatchlist(), "\n" );
570 $fields = array(
571 'Titles' => array(
572 'type' => 'textarea',
573 'label-message' => 'watchlistedit-raw-titles',
574 'default' => $titles,
577 $form = new HTMLForm( $fields, $this->getContext() );
578 $form->setTitle( $this->getTitle( 'raw' ) );
579 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
580 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
581 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
582 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
583 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
584 $form->setSubmitCallback( array( $this, 'submitRaw' ) );
585 return $form;
589 * Determine whether we are editing the watchlist, and if so, what
590 * kind of editing operation
592 * @param $request WebRequest
593 * @param $par mixed
594 * @return int
596 public static function getMode( $request, $par ) {
597 $mode = strtolower( $request->getVal( 'action', $par ) );
598 switch( $mode ) {
599 case 'clear':
600 case self::EDIT_CLEAR:
601 return self::EDIT_CLEAR;
603 case 'raw':
604 case self::EDIT_RAW:
605 return self::EDIT_RAW;
607 case 'edit':
608 case self::EDIT_NORMAL:
609 return self::EDIT_NORMAL;
611 default:
612 return false;
617 * Build a set of links for convenient navigation
618 * between watchlist viewing and editing modes
620 * @param $unused
621 * @return string
623 public static function buildTools( $unused ) {
624 global $wgLang;
626 $tools = array();
627 $modes = array(
628 'view' => array( 'Watchlist', false ),
629 'edit' => array( 'EditWatchlist', false ),
630 'raw' => array( 'EditWatchlist', 'raw' ),
632 foreach( $modes as $mode => $arr ) {
633 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
634 $tools[] = Linker::linkKnown(
635 SpecialPage::getTitleFor( $arr[0], $arr[1] ),
636 wfMessage( "watchlisttools-{$mode}" )->escaped()
639 return Html::rawElement( 'span',
640 array( 'class' => 'mw-watchlist-toollinks' ),
641 wfMessage( 'parentheses', $wgLang->pipeList( $tools ) )->text() );
645 # B/C since 1.18
646 class WatchlistEditor extends SpecialEditWatchlist {}
649 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
651 class EditWatchlistNormalHTMLForm extends HTMLForm {
652 public function getLegend( $namespace ) {
653 $namespace = substr( $namespace, 2 );
654 return $namespace == NS_MAIN
655 ? $this->msg( 'blanknamespace' )->escaped()
656 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
658 public function getBody() {
659 return $this->displaySection( $this->mFieldTree, '', 'editwatchlist-' );
663 class EditWatchlistCheckboxSeriesField extends HTMLMultiSelectField {
665 * HTMLMultiSelectField throws validation errors if we get input data
666 * that doesn't match the data set in the form setup. This causes
667 * problems if something gets removed from the watchlist while the
668 * form is open (bug 32126), but we know that invalid items will
669 * be harmless so we can override it here.
671 * @param string $value the value the field was submitted with
672 * @param array $alldata the data collected from the form
673 * @return Mixed Bool true on success, or String error to display.
675 function validate( $value, $alldata ) {
676 // Need to call into grandparent to be a good citizen. :)
677 return HTMLFormField::validate( $value, $alldata );