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