Merge "Make it show email as required if you choose to email a random password."
[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
40 */
41 const EDIT_CLEAR = 1;
42 const EDIT_RAW = 2;
43 const EDIT_NORMAL = 3;
44
45 protected $successMessage;
46
47 protected $toc;
48
49 private $badItems = array();
50
51 public function __construct() {
52 parent::__construct( 'EditWatchlist', 'editmywatchlist' );
53 }
54
55 /**
56 * Main execution point
57 *
58 * @param $mode int
59 */
60 public function execute( $mode ) {
61 $this->setHeaders();
62
63 $out = $this->getOutput();
64
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() )
73 );
74 $out->addHTML( $this->msg( 'watchlistanontext' )->rawParams( $llink )->parse() );
75
76 return;
77 }
78
79 $this->checkPermissions();
80 $this->checkReadOnly();
81
82 $this->outputHeader();
83
84 $out->addSubtitle( $this->msg( 'watchlistfor2', $this->getUser()->getName() )
85 ->rawParams( SpecialEditWatchlist::buildTools( null ) ) );
86
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];
93 }
94 }
95 $mode = self::getMode( $this->getRequest(), $mode );
96
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.
101
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' ) );
108 }
109 break;
110
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 );
120 }
121 break;
122 }
123 }
124
125 /**
126 * Extract a list of titles from a blob of text, returning
127 * (prefixed) strings; unwatchable titles are ignored
128 *
129 * @param $list String
130 * @return array
131 */
132 private function extractTitles( $list ) {
133 $list = explode( "\n", trim( $list ) );
134 if ( !is_array( $list ) ) {
135 return array();
136 }
137
138 $titles = array();
139
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;
146 }
147 }
148 }
149
150 GenderCache::singleton()->doTitlesArray( $titles );
151
152 $list = array();
153 /** @var Title $title */
154 foreach ( $titles as $title ) {
155 $list[] = $title->getPrefixedText();
156 }
157
158 return array_unique( $list );
159 }
160
161 public function submitRaw( $data ) {
162 $wanted = $this->extractTitles( $data['Titles'] );
163 $current = $this->getWatchlist();
164
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();
171
172 if ( count( $toWatch ) > 0 || count( $toUnwatch ) > 0 ) {
173 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
174 } else {
175 return false;
176 }
177
178 if ( count( $toWatch ) > 0 ) {
179 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-added'
180 )->numParams( count( $toWatch ) )->parse();
181 $this->showTitles( $toWatch, $this->successMessage );
182 }
183
184 if ( count( $toUnwatch ) > 0 ) {
185 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed'
186 )->numParams( count( $toUnwatch ) )->parse();
187 $this->showTitles( $toUnwatch, $this->successMessage );
188 }
189 } else {
190 $this->clearWatchlist();
191 $this->getUser()->invalidateCache();
192
193 if ( count( $current ) > 0 ) {
194 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
195 } else {
196 return false;
197 }
198
199 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed' )
200 ->numParams( count( $current ) )->parse();
201 $this->showTitles( $current, $this->successMessage );
202 }
203
204 return true;
205 }
206
207 /**
208 * Print out a list of linked titles
209 *
210 * $titles can be an array of strings or Title objects; the former
211 * is preferred, since Titles are very memory-heavy
212 *
213 * @param array $titles of strings, or Title objects
214 * @param $output String
215 */
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 );
223 }
224
225 if ( $title instanceof Title ) {
226 $batch->addObj( $title );
227 $batch->addObj( $title->getTalkPage() );
228 }
229 }
230
231 $batch->execute();
232
233 // Print out the list
234 $output .= "<ul>\n";
235
236 foreach ( $titles as $title ) {
237 if ( !$title instanceof Title ) {
238 $title = Title::newFromText( $title );
239 }
240
241 if ( $title instanceof Title ) {
242 $output .= "<li>"
243 . Linker::link( $title )
244 . ' (' . Linker::link( $title->getTalkPage(), $talk )
245 . ")</li>\n";
246 }
247 }
248
249 $output .= "</ul>\n";
250 }
251
252 /**
253 * Prepare a list of titles on a user's watchlist (excluding talk pages)
254 * and return an array of (prefixed) strings
255 *
256 * @return array
257 */
258 private function getWatchlist() {
259 $list = array();
260 $dbr = wfGetDB( DB_MASTER );
261
262 $res = $dbr->select(
263 'watchlist',
264 array(
265 'wl_namespace', 'wl_title'
266 ), array(
267 'wl_user' => $this->getUser()->getId(),
268 ),
269 __METHOD__
270 );
271
272 if ( $res->numRows() > 0 ) {
273 $titles = array();
274 foreach ( $res as $row ) {
275 $title = Title::makeTitleSafe( $row->wl_namespace, $row->wl_title );
276
277 if ( $this->checkTitle( $title, $row->wl_namespace, $row->wl_title )
278 && !$title->isTalkPage()
279 ) {
280 $titles[] = $title;
281 }
282 }
283 $res->free();
284
285 GenderCache::singleton()->doTitlesArray( $titles );
286
287 foreach ( $titles as $title ) {
288 $list[] = $title->getPrefixedText();
289 }
290 }
291
292 $this->cleanupWatchlist();
293
294 return $list;
295 }
296
297 /**
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.
300 *
301 * @return array
302 */
303 private function getWatchlistInfo() {
304 $titles = array();
305 $dbr = wfGetDB( DB_MASTER );
306
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' ) )
313 );
314
315 $lb = new LinkBatch();
316
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;
321 }
322 }
323
324 $lb->execute();
325
326 return $titles;
327 }
328
329 /**
330 * Validates watchlist entry
331 *
332 * @param Title $title
333 * @param int $namespace
334 * @param string $dbKey
335 * @return bool: Whether this item is valid
336 */
337 private function checkTitle( $title, $namespace, $dbKey ) {
338 if ( $title
339 && ( $title->isExternal()
340 || $title->getNamespace() < 0
341 )
342 ) {
343 $title = false; // unrecoverable
344 }
345
346 if ( !$title
347 || $title->getNamespace() != $namespace
348 || $title->getDBkey() != $dbKey
349 ) {
350 $this->badItems[] = array( $title, $namespace, $dbKey );
351 }
352
353 return (bool)$title;
354 }
355
356 /**
357 * Attempts to clean up broken items
358 */
359 private function cleanupWatchlist() {
360 if ( !count( $this->badItems ) ) {
361 return; //nothing to do
362 }
363
364 $dbw = wfGetDB( DB_MASTER );
365 $user = $this->getUser();
366
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" );
371
372 $dbw->delete( 'watchlist',
373 array(
374 'wl_user' => $user->getId(),
375 'wl_namespace' => $namespace,
376 'wl_title' => $dbKey,
377 ),
378 __METHOD__
379 );
380
381 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
382 if ( $title ) {
383 $user->addWatch( $title );
384 }
385 }
386 }
387
388 /**
389 * Remove all titles from a user's watchlist
390 */
391 private function clearWatchlist() {
392 $dbw = wfGetDB( DB_MASTER );
393 $dbw->delete(
394 'watchlist',
395 array( 'wl_user' => $this->getUser()->getId() ),
396 __METHOD__
397 );
398 }
399
400 /**
401 * Add a list of titles to a user's watchlist
402 *
403 * $titles can be an array of strings or Title objects; the former
404 * is preferred, since Titles are very memory-heavy
405 *
406 * @param array $titles of strings, or Title objects
407 */
408 private function watchTitles( $titles ) {
409 $dbw = wfGetDB( DB_MASTER );
410 $rows = array();
411
412 foreach ( $titles as $title ) {
413 if ( !$title instanceof Title ) {
414 $title = Title::newFromText( $title );
415 }
416
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,
423 );
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,
429 );
430 }
431 }
432
433 $dbw->insert( 'watchlist', $rows, __METHOD__, 'IGNORE' );
434 }
435
436 /**
437 * Remove a list of titles from a user's watchlist
438 *
439 * $titles can be an array of strings or Title objects; the former
440 * is preferred, since Titles are very memory-heavy
441 *
442 * @param array $titles of strings, or Title objects
443 */
444 private function unwatchTitles( $titles ) {
445 $dbw = wfGetDB( DB_MASTER );
446
447 foreach ( $titles as $title ) {
448 if ( !$title instanceof Title ) {
449 $title = Title::newFromText( $title );
450 }
451
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(),
459 ),
460 __METHOD__
461 );
462
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(),
469 ),
470 __METHOD__
471 );
472
473 $page = WikiPage::factory( $title );
474 wfRunHooks( 'UnwatchArticleComplete', array( $this->getUser(), &$page ) );
475 }
476 }
477 }
478
479 public function submitNormal( $data ) {
480 $removed = array();
481
482 foreach ( $data as $titles ) {
483 $this->unwatchTitles( $titles );
484 $removed = array_merge( $removed, $titles );
485 }
486
487 if ( count( $removed ) > 0 ) {
488 $this->successMessage = $this->msg( 'watchlistedit-normal-done'
489 )->numParams( count( $removed ) )->parse();
490 $this->showTitles( $removed, $this->successMessage );
491
492 return true;
493 } else {
494 return false;
495 }
496 }
497
498 /**
499 * Get the standard watchlist editing form
500 *
501 * @return HTMLForm
502 */
503 protected function getNormalForm() {
504 global $wgContLang;
505
506 $fields = array();
507 $count = 0;
508
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",
515 );
516 }
517
518 foreach ( array_keys( $pages ) as $dbkey ) {
519 $title = Title::makeTitleSafe( $namespace, $dbkey );
520
521 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
522 $text = $this->buildRemoveLine( $title );
523 $fields['TitlesNs' . $namespace]['options'][$text] = $title->getPrefixedText();
524 $count++;
525 }
526 }
527 }
528 $this->cleanupWatchlist();
529
530 if ( count( $fields ) > 1 && $count > 30 ) {
531 $this->toc = Linker::tocIndent();
532 $tocLength = 0;
533
534 foreach ( $fields as $data ) {
535 # strip out the 'ns' prefix from the section name:
536 $ns = substr( $data['section'], 2 );
537
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();
543 }
544
545 $this->toc = Linker::tocList( $this->toc );
546 } else {
547 $this->toc = false;
548 }
549
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' ) );
558
559 return $form;
560 }
561
562 /**
563 * Build the label for a checkbox, with a link to the title, and various additional bits
564 *
565 * @param $title Title
566 * @return string
567 */
568 private function buildRemoveLine( $title ) {
569 $link = Linker::link( $title );
570
571 if ( $title->isRedirect() ) {
572 // Linker already makes class mw-redirect, so this is redundant
573 $link = '<span class="watchlistredir">' . $link . '</span>';
574 }
575
576 $tools[] = Linker::link( $title->getTalkPage(), $this->msg( 'talkpagelinktext' )->escaped() );
577
578 if ( $title->exists() ) {
579 $tools[] = Linker::linkKnown(
580 $title,
581 $this->msg( 'history_short' )->escaped(),
582 array(),
583 array( 'action' => 'history' )
584 );
585 }
586
587 if ( $title->getNamespace() == NS_USER && !$title->isSubpage() ) {
588 $tools[] = Linker::linkKnown(
589 SpecialPage::getTitleFor( 'Contributions', $title->getText() ),
590 $this->msg( 'contributions' )->escaped()
591 );
592 }
593
594 wfRunHooks( 'WatchlistEditorBuildRemoveLine', array( &$tools, $title, $title->isRedirect(), $this->getSkin() ) );
595
596 return $link . " (" . $this->getLanguage()->pipeList( $tools ) . ")";
597 }
598
599 /**
600 * Get a form for editing the watchlist in "raw" mode
601 *
602 * @return HTMLForm
603 */
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,
611 ),
612 );
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' ) );
621
622 return $form;
623 }
624
625 /**
626 * Determine whether we are editing the watchlist, and if so, what
627 * kind of editing operation
628 *
629 * @param $request WebRequest
630 * @param $par mixed
631 * @return int
632 */
633 public static function getMode( $request, $par ) {
634 $mode = strtolower( $request->getVal( 'action', $par ) );
635
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;
648 }
649 }
650
651 /**
652 * Build a set of links for convenient navigation
653 * between watchlist viewing and editing modes
654 *
655 * @param $unused
656 * @return string
657 */
658 public static function buildTools( $unused ) {
659 global $wgLang;
660
661 $tools = array();
662 $modes = array(
663 'view' => array( 'Watchlist', false ),
664 'edit' => array( 'EditWatchlist', false ),
665 'raw' => array( 'EditWatchlist', 'raw' ),
666 );
667
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()
673 );
674 }
675
676 return Html::rawElement(
677 'span',
678 array( 'class' => 'mw-watchlist-toollinks' ),
679 wfMessage( 'parentheses', $wgLang->pipeList( $tools ) )->text()
680 );
681 }
682 }
683
684 # B/C since 1.18
685 class WatchlistEditor extends SpecialEditWatchlist {
686 }
687
688 /**
689 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
690 */
691 class EditWatchlistNormalHTMLForm extends HTMLForm {
692 public function getLegend( $namespace ) {
693 $namespace = substr( $namespace, 2 );
694
695 return $namespace == NS_MAIN
696 ? $this->msg( 'blanknamespace' )->escaped()
697 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
698 }
699
700 public function getBody() {
701 return $this->displaySection( $this->mFieldTree, '', 'editwatchlist-' );
702 }
703 }
704
705 class EditWatchlistCheckboxSeriesField extends HTMLMultiSelectField {
706 /**
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.
712 *
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.
716 */
717 function validate( $value, $alldata ) {
718 // Need to call into grandparent to be a good citizen. :)
719 return HTMLFormField::validate( $value, $alldata );
720 }
721 }