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