(bug 28936, bug 5280) Broken or invalid titles can't be removed from watchlist. Now...
[lhc/web/wiklou.git] / includes / specials / SpecialEditWatchlist.php
1 <?php
2 /**
3 * @defgroup Watchlist Users watchlist handling
4 */
5
6 /**
7 * Provides the UI through which users can perform editing
8 * operations on their watchlist
9 *
10 * @ingroup Watchlist
11 * @author Rob Church <robchur@gmail.com>
12 */
13 class SpecialEditWatchlist extends UnlistedSpecialPage {
14
15 /**
16 * Editing modes
17 */
18 const EDIT_CLEAR = 1;
19 const EDIT_RAW = 2;
20 const EDIT_NORMAL = 3;
21
22 protected $successMessage;
23
24 protected $toc;
25
26 private $badItems = array();
27
28 public function __construct(){
29 parent::__construct( 'EditWatchlist' );
30 }
31
32 /**
33 * Main execution point
34 *
35 * @param $mode int
36 */
37 public function execute( $mode ) {
38 $this->setHeaders();
39
40 $out = $this->getOutput();
41
42 # Anons don't get a watchlist
43 if( $this->getUser()->isAnon() ) {
44 $out->setPageTitle( $this->msg( 'watchnologin' ) );
45 $llink = Linker::linkKnown(
46 SpecialPage::getTitleFor( 'Userlogin' ),
47 $this->msg( 'loginreqlink' )->escaped(),
48 array(),
49 array( 'returnto' => $this->getTitle()->getPrefixedText() )
50 );
51 $out->addHTML( $this->msg( 'watchlistanontext' )->rawParams( $llink )->parse() );
52 return;
53 }
54
55 $this->checkPermissions();
56
57 $this->outputHeader();
58
59 $out->addSubtitle( $this->msg( 'watchlistfor2', $this->getUser()->getName()
60 )->rawParams( SpecialEditWatchlist::buildTools( null ) ) );
61
62 # B/C: $mode used to be waaay down the parameter list, and the first parameter
63 # was $wgUser
64 if( $mode instanceof User ){
65 $args = func_get_args();
66 if( count( $args >= 4 ) ){
67 $mode = $args[3];
68 }
69 }
70 $mode = self::getMode( $this->getRequest(), $mode );
71
72 switch( $mode ) {
73 case self::EDIT_CLEAR:
74 // The "Clear" link scared people too much.
75 // Pass on to the raw editor, from which it's very easy to clear.
76
77 case self::EDIT_RAW:
78 $out->setPageTitle( $this->msg( 'watchlistedit-raw-title' ) );
79 $form = $this->getRawForm();
80 if( $form->show() ){
81 $out->addHTML( $this->successMessage );
82 $out->returnToMain();
83 }
84 break;
85
86 case self::EDIT_NORMAL:
87 default:
88 $out->setPageTitle( $this->msg( 'watchlistedit-normal-title' ) );
89 $form = $this->getNormalForm();
90 if( $form->show() ){
91 $out->addHTML( $this->successMessage );
92 $out->returnToMain();
93 } elseif ( $this->toc !== false ) {
94 $out->prependHTML( $this->toc );
95 }
96 break;
97 }
98 }
99
100 /**
101 * Extract a list of titles from a blob of text, returning
102 * (prefixed) strings; unwatchable titles are ignored
103 *
104 * @param $list String
105 * @return array
106 */
107 private function extractTitles( $list ) {
108 $titles = array();
109 $list = explode( "\n", trim( $list ) );
110 if( !is_array( $list ) ) {
111 return array();
112 }
113 foreach( $list as $text ) {
114 $text = trim( $text );
115 if( strlen( $text ) > 0 ) {
116 $title = Title::newFromText( $text );
117 if( $title instanceof Title && $title->isWatchable() ) {
118 $titles[] = $title->getPrefixedText();
119 }
120 }
121 }
122 return array_unique( $titles );
123 }
124
125 public function submitRaw( $data ){
126 $wanted = $this->extractTitles( $data['Titles'] );
127 $current = $this->getWatchlist();
128
129 if( count( $wanted ) > 0 ) {
130 $toWatch = array_diff( $wanted, $current );
131 $toUnwatch = array_diff( $current, $wanted );
132 $this->watchTitles( $toWatch );
133 $this->unwatchTitles( $toUnwatch );
134 $this->getUser()->invalidateCache();
135
136 if( count( $toWatch ) > 0 || count( $toUnwatch ) > 0 ){
137 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
138 } else {
139 return false;
140 }
141
142 if( count( $toWatch ) > 0 ) {
143 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-added'
144 )->numParams( count( $toWatch ) )->parse();
145 $this->showTitles( $toWatch, $this->successMessage );
146 }
147
148 if( count( $toUnwatch ) > 0 ) {
149 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed'
150 )->numParams( count( $toUnwatch ) )->parse();
151 $this->showTitles( $toUnwatch, $this->successMessage );
152 }
153 } else {
154 $this->clearWatchlist();
155 $this->getUser()->invalidateCache();
156
157 if( count( $current ) > 0 ){
158 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
159 } else {
160 return false;
161 }
162
163 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed'
164 )->numParams( count( $current ) )->parse();
165 $this->showTitles( $current, $this->successMessage );
166 }
167 return true;
168 }
169
170 /**
171 * Print out a list of linked titles
172 *
173 * $titles can be an array of strings or Title objects; the former
174 * is preferred, since Titles are very memory-heavy
175 *
176 * @param $titles array of strings, or Title objects
177 * @param $output String
178 */
179 private function showTitles( $titles, &$output ) {
180 $talk = $this->msg( 'talkpagelinktext' )->escaped();
181 // Do a batch existence check
182 $batch = new LinkBatch();
183 foreach( $titles as $title ) {
184 if( !$title instanceof Title ) {
185 $title = Title::newFromText( $title );
186 }
187 if( $title instanceof Title ) {
188 $batch->addObj( $title );
189 $batch->addObj( $title->getTalkPage() );
190 }
191 }
192 $batch->execute();
193 // Print out the list
194 $output .= "<ul>\n";
195 foreach( $titles as $title ) {
196 if( !$title instanceof Title ) {
197 $title = Title::newFromText( $title );
198 }
199 if( $title instanceof Title ) {
200 $output .= "<li>"
201 . Linker::link( $title )
202 . ' (' . Linker::link( $title->getTalkPage(), $talk )
203 . ")</li>\n";
204 }
205 }
206 $output .= "</ul>\n";
207 }
208
209 /**
210 * Prepare a list of titles on a user's watchlist (excluding talk pages)
211 * and return an array of (prefixed) strings
212 *
213 * @return array
214 */
215 private function getWatchlist() {
216 $list = array();
217 $dbr = wfGetDB( DB_MASTER );
218 $res = $dbr->select(
219 'watchlist',
220 '*',
221 array(
222 'wl_user' => $this->getUser()->getId(),
223 ),
224 __METHOD__
225 );
226 if( $res->numRows() > 0 ) {
227 foreach ( $res as $row ) {
228 $title = Title::makeTitleSafe( $row->wl_namespace, $row->wl_title );
229 if ( $this->checkTitle( $title, $row->wl_namespace, $row->wl_title )
230 && !$title->isTalkPage()
231 ) {
232 $list[] = $title->getPrefixedText();
233 }
234 }
235 $res->free();
236 }
237 $this->cleanupWatchlist();
238 return $list;
239 }
240
241 /**
242 * Get a list of titles on a user's watchlist, excluding talk pages,
243 * and return as a two-dimensional array with namespace and title.
244 *
245 * @return array
246 */
247 private function getWatchlistInfo() {
248 $titles = array();
249 $dbr = wfGetDB( DB_MASTER );
250
251 $res = $dbr->select(
252 array( 'watchlist' ),
253 array( 'wl_namespace', 'wl_title' ),
254 array( 'wl_user' => $this->getUser()->getId() ),
255 __METHOD__,
256 array( 'ORDER BY' => 'wl_namespace, wl_title' )
257 );
258
259 $lb = new LinkBatch();
260 foreach ( $res as $row ) {
261 $lb->add( $row->wl_namespace, $row->wl_title );
262 if ( !MWNamespace::isTalk( $row->wl_namespace ) ) {
263 $titles[$row->wl_namespace][$row->wl_title] = 1;
264 }
265 }
266
267 $lb->execute();
268 return $titles;
269 }
270
271 /**
272 * Validates watchlist entry
273 *
274 * @param Title $title
275 * @param int $namespace
276 * @param String $dbKey
277 * @return bool: Whether this item is valid
278 */
279 private function checkTitle( $title, $namespace, $dbKey ) {
280 if ( $title
281 && ( $title->isExternal()
282 || $title->getNamespace() < 0
283 )
284 ) {
285 $title = false; // unrecoverable
286 }
287 if ( !$title
288 || $title->getNamespace() != $namespace
289 || $title->getDBkey() != $dbKey
290 ) {
291 $this->badItems[] = array( $title, $namespace, $dbKey );
292 }
293 return (bool)$title;
294 }
295
296 /**
297 * Attempts to clean up broken items
298 */
299 private function cleanupWatchlist() {
300 if ( count( $this->badItems ) ) {
301 $dbw = wfGetDB( DB_MASTER );
302 }
303 foreach ( $this->badItems as $row ) {
304 list( $title, $namespace, $dbKey ) = $row;
305 wfDebug( "User {$this->getUser()} has broken watchlist item ns($namespace):$dbKey, "
306 . ( $title ? 'cleaning up' : 'deleting' ) . ".\n"
307 );
308
309 $dbw->delete( 'watchlist',
310 array(
311 'wl_user' => $this->getUser()->getId(),
312 'wl_namespace' => $namespace,
313 'wl_title' => $dbKey,
314 ),
315 __METHOD__
316 );
317
318 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
319 if ( $title ) {
320 $this->getUser()->addWatch( $title );
321 }
322 }
323 }
324
325 /**
326 * Remove all titles from a user's watchlist
327 */
328 private function clearWatchlist() {
329 $dbw = wfGetDB( DB_MASTER );
330 $dbw->delete(
331 'watchlist',
332 array( 'wl_user' => $this->getUser()->getId() ),
333 __METHOD__
334 );
335 }
336
337 /**
338 * Add a list of titles to a user's watchlist
339 *
340 * $titles can be an array of strings or Title objects; the former
341 * is preferred, since Titles are very memory-heavy
342 *
343 * @param $titles Array of strings, or Title objects
344 */
345 private function watchTitles( $titles ) {
346 $dbw = wfGetDB( DB_MASTER );
347 $rows = array();
348 foreach( $titles as $title ) {
349 if( !$title instanceof Title ) {
350 $title = Title::newFromText( $title );
351 }
352 if( $title instanceof Title ) {
353 $rows[] = array(
354 'wl_user' => $this->getUser()->getId(),
355 'wl_namespace' => ( $title->getNamespace() & ~1 ),
356 'wl_title' => $title->getDBkey(),
357 'wl_notificationtimestamp' => null,
358 );
359 $rows[] = array(
360 'wl_user' => $this->getUser()->getId(),
361 'wl_namespace' => ( $title->getNamespace() | 1 ),
362 'wl_title' => $title->getDBkey(),
363 'wl_notificationtimestamp' => null,
364 );
365 }
366 }
367 $dbw->insert( 'watchlist', $rows, __METHOD__, 'IGNORE' );
368 }
369
370 /**
371 * Remove a list of titles from a user's watchlist
372 *
373 * $titles can be an array of strings or Title objects; the former
374 * is preferred, since Titles are very memory-heavy
375 *
376 * @param $titles Array of strings, or Title objects
377 */
378 private function unwatchTitles( $titles ) {
379 $dbw = wfGetDB( DB_MASTER );
380 foreach( $titles as $title ) {
381 if( !$title instanceof Title ) {
382 $title = Title::newFromText( $title );
383 }
384 if( $title instanceof Title ) {
385 $dbw->delete(
386 'watchlist',
387 array(
388 'wl_user' => $this->getUser()->getId(),
389 'wl_namespace' => ( $title->getNamespace() & ~1 ),
390 'wl_title' => $title->getDBkey(),
391 ),
392 __METHOD__
393 );
394 $dbw->delete(
395 'watchlist',
396 array(
397 'wl_user' => $this->getUser()->getId(),
398 'wl_namespace' => ( $title->getNamespace() | 1 ),
399 'wl_title' => $title->getDBkey(),
400 ),
401 __METHOD__
402 );
403 $page = WikiPage::factory( $title );
404 wfRunHooks( 'UnwatchArticleComplete', array( $this->getUser(), &$page ) );
405 }
406 }
407 }
408
409 public function submitNormal( $data ) {
410 $removed = array();
411
412 foreach( $data as $titles ) {
413 $this->unwatchTitles( $titles );
414 $removed += $titles;
415 }
416
417 if( count( $removed ) > 0 ) {
418 $this->successMessage = $this->msg( 'watchlistedit-normal-done'
419 )->numParams( count( $removed ) )->parse();
420 $this->showTitles( $removed, $this->successMessage );
421 return true;
422 } else {
423 return false;
424 }
425 }
426
427 /**
428 * Get the standard watchlist editing form
429 *
430 * @return HTMLForm
431 */
432 protected function getNormalForm(){
433 global $wgContLang;
434
435 $fields = array();
436 $count = 0;
437
438 foreach( $this->getWatchlistInfo() as $namespace => $pages ){
439 if ( $namespace >= 0 ) {
440 $fields['TitlesNs'.$namespace] = array(
441 'class' => 'EditWatchlistCheckboxSeriesField',
442 'options' => array(),
443 'section' => "ns$namespace",
444 );
445 }
446
447 foreach( array_keys( $pages ) as $dbkey ){
448 $title = Title::makeTitleSafe( $namespace, $dbkey );
449 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
450 $text = $this->buildRemoveLine( $title );
451 $fields['TitlesNs'.$namespace]['options'][$text] = $title->getEscapedText();
452 $count++;
453 }
454 }
455 }
456 $this->cleanupWatchlist();
457
458 if ( count( $fields ) > 1 && $count > 30 ) {
459 $this->toc = Linker::tocIndent();
460 $tocLength = 0;
461 foreach( $fields as $key => $data ) {
462
463 # strip out the 'ns' prefix from the section name:
464 $ns = substr( $data['section'], 2 );
465
466 $nsText = ($ns == NS_MAIN)
467 ? $this->msg( 'blanknamespace' )->escaped()
468 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
469 $this->toc .= Linker::tocLine( "editwatchlist-{$data['section']}", $nsText,
470 $this->getLanguage()->formatNum( ++$tocLength ), 1 ) . Linker::tocLineEnd();
471 }
472 $this->toc = Linker::tocList( $this->toc );
473 } else {
474 $this->toc = false;
475 }
476
477 $form = new EditWatchlistNormalHTMLForm( $fields, $this->getContext() );
478 $form->setTitle( $this->getTitle() );
479 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
480 # Used message keys: 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
481 $form->setSubmitTooltip('watchlistedit-normal-submit');
482 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
483 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
484 $form->setSubmitCallback( array( $this, 'submitNormal' ) );
485 return $form;
486 }
487
488 /**
489 * Build the label for a checkbox, with a link to the title, and various additional bits
490 *
491 * @param $title Title
492 * @return string
493 */
494 private function buildRemoveLine( $title ) {
495 $link = Linker::link( $title );
496 if( $title->isRedirect() ) {
497 // Linker already makes class mw-redirect, so this is redundant
498 $link = '<span class="watchlistredir">' . $link . '</span>';
499 }
500 $tools[] = Linker::link( $title->getTalkPage(), $this->msg( 'talkpagelinktext' )->escaped() );
501 if( $title->exists() ) {
502 $tools[] = Linker::linkKnown(
503 $title,
504 $this->msg( 'history_short' )->escaped(),
505 array(),
506 array( 'action' => 'history' )
507 );
508 }
509 if( $title->getNamespace() == NS_USER && !$title->isSubpage() ) {
510 $tools[] = Linker::linkKnown(
511 SpecialPage::getTitleFor( 'Contributions', $title->getText() ),
512 $this->msg( 'contributions' )->escaped()
513 );
514 }
515
516 wfRunHooks( 'WatchlistEditorBuildRemoveLine', array( &$tools, $title, $title->isRedirect(), $this->getSkin() ) );
517
518 return $link . " (" . $this->getLanguage()->pipeList( $tools ) . ")";
519 }
520
521 /**
522 * Get a form for editing the watchlist in "raw" mode
523 *
524 * @return HTMLForm
525 */
526 protected function getRawForm(){
527 $titles = implode( $this->getWatchlist(), "\n" );
528 $fields = array(
529 'Titles' => array(
530 'type' => 'textarea',
531 'label-message' => 'watchlistedit-raw-titles',
532 'default' => $titles,
533 ),
534 );
535 $form = new HTMLForm( $fields, $this->getContext() );
536 $form->setTitle( $this->getTitle( 'raw' ) );
537 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
538 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
539 $form->setSubmitTooltip('watchlistedit-raw-submit');
540 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
541 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
542 $form->setSubmitCallback( array( $this, 'submitRaw' ) );
543 return $form;
544 }
545
546 /**
547 * Determine whether we are editing the watchlist, and if so, what
548 * kind of editing operation
549 *
550 * @param $request WebRequest
551 * @param $par mixed
552 * @return int
553 */
554 public static function getMode( $request, $par ) {
555 $mode = strtolower( $request->getVal( 'action', $par ) );
556 switch( $mode ) {
557 case 'clear':
558 case self::EDIT_CLEAR:
559 return self::EDIT_CLEAR;
560
561 case 'raw':
562 case self::EDIT_RAW:
563 return self::EDIT_RAW;
564
565 case 'edit':
566 case self::EDIT_NORMAL:
567 return self::EDIT_NORMAL;
568
569 default:
570 return false;
571 }
572 }
573
574 /**
575 * Build a set of links for convenient navigation
576 * between watchlist viewing and editing modes
577 *
578 * @param $unused
579 * @return string
580 */
581 public static function buildTools( $unused ) {
582 global $wgLang;
583
584 $tools = array();
585 $modes = array(
586 'view' => array( 'Watchlist', false ),
587 'edit' => array( 'EditWatchlist', false ),
588 'raw' => array( 'EditWatchlist', 'raw' ),
589 );
590 foreach( $modes as $mode => $arr ) {
591 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
592 $tools[] = Linker::linkKnown(
593 SpecialPage::getTitleFor( $arr[0], $arr[1] ),
594 wfMsgHtml( "watchlisttools-{$mode}" )
595 );
596 }
597 return Html::rawElement( 'span',
598 array( 'class' => 'mw-watchlist-toollinks' ),
599 wfMsg( 'parentheses', $wgLang->pipeList( $tools ) ) );
600 }
601 }
602
603 # B/C since 1.18
604 class WatchlistEditor extends SpecialEditWatchlist {}
605
606 /**
607 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
608 */
609 class EditWatchlistNormalHTMLForm extends HTMLForm {
610 public function getLegend( $namespace ){
611 $namespace = substr( $namespace, 2 );
612 return $namespace == NS_MAIN
613 ? $this->msg( 'blanknamespace' )->escaped()
614 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
615 }
616 public function getBody() {
617 return $this->displaySection( $this->mFieldTree, '', 'editwatchlist-' );
618 }
619 }
620
621 class EditWatchlistCheckboxSeriesField extends HTMLMultiSelectField {
622 /**
623 * HTMLMultiSelectField throws validation errors if we get input data
624 * that doesn't match the data set in the form setup. This causes
625 * problems if something gets removed from the watchlist while the
626 * form is open (bug 32126), but we know that invalid items will
627 * be harmless so we can override it here.
628 *
629 * @param $value String the value the field was submitted with
630 * @param $alldata Array the data collected from the form
631 * @return Mixed Bool true on success, or String error to display.
632 */
633 function validate( $value, $alldata ) {
634 // Need to call into grandparent to be a good citizen. :)
635 return HTMLFormField::validate( $value, $alldata );
636 }
637 }