Merge "Rename Image namespace to File for 'be' locale"
[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 $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 $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;
144 }
145 }
146 }
147
148 GenderCache::singleton()->doTitlesArray( $titles );
149
150 $list = array();
151 foreach( $titles as $title ) {
152 $list[] = $title->getPrefixedText();
153 }
154 return array_unique( $list );
155 }
156
157 public function submitRaw( $data ) {
158 $wanted = $this->extractTitles( $data['Titles'] );
159 $current = $this->getWatchlist();
160
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();
167
168 if( count( $toWatch ) > 0 || count( $toUnwatch ) > 0 ) {
169 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
170 } else {
171 return false;
172 }
173
174 if( count( $toWatch ) > 0 ) {
175 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-added'
176 )->numParams( count( $toWatch ) )->parse();
177 $this->showTitles( $toWatch, $this->successMessage );
178 }
179
180 if( count( $toUnwatch ) > 0 ) {
181 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed'
182 )->numParams( count( $toUnwatch ) )->parse();
183 $this->showTitles( $toUnwatch, $this->successMessage );
184 }
185 } else {
186 $this->clearWatchlist();
187 $this->getUser()->invalidateCache();
188
189 if( count( $current ) > 0 ) {
190 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
191 } else {
192 return false;
193 }
194
195 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed'
196 )->numParams( count( $current ) )->parse();
197 $this->showTitles( $current, $this->successMessage );
198 }
199 return true;
200 }
201
202 /**
203 * Print out a list of linked titles
204 *
205 * $titles can be an array of strings or Title objects; the former
206 * is preferred, since Titles are very memory-heavy
207 *
208 * @param $titles array of strings, or Title objects
209 * @param $output String
210 */
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 );
218 }
219 if( $title instanceof Title ) {
220 $batch->addObj( $title );
221 $batch->addObj( $title->getTalkPage() );
222 }
223 }
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 );
230 }
231 if( $title instanceof Title ) {
232 $output .= "<li>"
233 . Linker::link( $title )
234 . ' (' . Linker::link( $title->getTalkPage(), $talk )
235 . ")</li>\n";
236 }
237 }
238 $output .= "</ul>\n";
239 }
240
241 /**
242 * Prepare a list of titles on a user's watchlist (excluding talk pages)
243 * and return an array of (prefixed) strings
244 *
245 * @return array
246 */
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(),
256 ),
257 __METHOD__
258 );
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()
265 ) {
266 $titles[] = $title;
267 }
268 }
269 $res->free();
270
271 GenderCache::singleton()->doTitlesArray( $titles );
272
273 foreach( $titles as $title ) {
274 $list[] = $title->getPrefixedText();
275 }
276 }
277 $this->cleanupWatchlist();
278 return $list;
279 }
280
281 /**
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.
284 *
285 * @return array
286 */
287 private function getWatchlistInfo() {
288 $titles = array();
289 $dbr = wfGetDB( DB_MASTER );
290
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' ) )
297 );
298
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;
304 }
305 }
306
307 $lb->execute();
308 return $titles;
309 }
310
311 /**
312 * Validates watchlist entry
313 *
314 * @param Title $title
315 * @param int $namespace
316 * @param String $dbKey
317 * @return bool: Whether this item is valid
318 */
319 private function checkTitle( $title, $namespace, $dbKey ) {
320 if ( $title
321 && ( $title->isExternal()
322 || $title->getNamespace() < 0
323 )
324 ) {
325 $title = false; // unrecoverable
326 }
327 if ( !$title
328 || $title->getNamespace() != $namespace
329 || $title->getDBkey() != $dbKey
330 ) {
331 $this->badItems[] = array( $title, $namespace, $dbKey );
332 }
333 return (bool)$title;
334 }
335
336 /**
337 * Attempts to clean up broken items
338 */
339 private function cleanupWatchlist() {
340 if( !count( $this->badItems ) ) {
341 return; //nothing to do
342 }
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"
349 );
350
351 $dbw->delete( 'watchlist',
352 array(
353 'wl_user' => $user->getId(),
354 'wl_namespace' => $namespace,
355 'wl_title' => $dbKey,
356 ),
357 __METHOD__
358 );
359
360 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
361 if ( $title ) {
362 $user->addWatch( $title );
363 }
364 }
365 }
366
367 /**
368 * Remove all titles from a user's watchlist
369 */
370 private function clearWatchlist() {
371 $dbw = wfGetDB( DB_MASTER );
372 $dbw->delete(
373 'watchlist',
374 array( 'wl_user' => $this->getUser()->getId() ),
375 __METHOD__
376 );
377 }
378
379 /**
380 * Add a list of titles to a user's watchlist
381 *
382 * $titles can be an array of strings or Title objects; the former
383 * is preferred, since Titles are very memory-heavy
384 *
385 * @param $titles Array of strings, or Title objects
386 */
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 );
393 }
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,
400 );
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,
406 );
407 }
408 }
409 $dbw->insert( 'watchlist', $rows, __METHOD__, 'IGNORE' );
410 }
411
412 /**
413 * Remove a list of titles from a user's watchlist
414 *
415 * $titles can be an array of strings or Title objects; the former
416 * is preferred, since Titles are very memory-heavy
417 *
418 * @param $titles Array of strings, or Title objects
419 */
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 );
425 }
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(),
433 ),
434 __METHOD__
435 );
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(),
442 ),
443 __METHOD__
444 );
445 $page = WikiPage::factory( $title );
446 wfRunHooks( 'UnwatchArticleComplete', array( $this->getUser(), &$page ) );
447 }
448 }
449 }
450
451 public function submitNormal( $data ) {
452 $removed = array();
453
454 foreach( $data as $titles ) {
455 $this->unwatchTitles( $titles );
456 $removed = array_merge( $removed, $titles );
457 }
458
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;
466 }
467 }
468
469 /**
470 * Get the standard watchlist editing form
471 *
472 * @return HTMLForm
473 */
474 protected function getNormalForm() {
475 global $wgContLang;
476
477 $fields = array();
478 $count = 0;
479
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",
486 );
487 }
488
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++;
495 }
496 }
497 }
498 $this->cleanupWatchlist();
499
500 if ( count( $fields ) > 1 && $count > 30 ) {
501 $this->toc = Linker::tocIndent();
502 $tocLength = 0;
503 foreach( $fields as $data ) {
504
505 # strip out the 'ns' prefix from the section name:
506 $ns = substr( $data['section'], 2 );
507
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();
513 }
514 $this->toc = Linker::tocList( $this->toc );
515 } else {
516 $this->toc = false;
517 }
518
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;
528 }
529
530 /**
531 * Build the label for a checkbox, with a link to the title, and various additional bits
532 *
533 * @param $title Title
534 * @return string
535 */
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>';
541 }
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' )
549 );
550 }
551 if( $title->getNamespace() == NS_USER && !$title->isSubpage() ) {
552 $tools[] = Linker::linkKnown(
553 SpecialPage::getTitleFor( 'Contributions', $title->getText() ),
554 $this->msg( 'contributions' )->escaped()
555 );
556 }
557
558 wfRunHooks( 'WatchlistEditorBuildRemoveLine', array( &$tools, $title, $title->isRedirect(), $this->getSkin() ) );
559
560 return $link . " (" . $this->getLanguage()->pipeList( $tools ) . ")";
561 }
562
563 /**
564 * Get a form for editing the watchlist in "raw" mode
565 *
566 * @return HTMLForm
567 */
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,
575 ),
576 );
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;
586 }
587
588 /**
589 * Determine whether we are editing the watchlist, and if so, what
590 * kind of editing operation
591 *
592 * @param $request WebRequest
593 * @param $par mixed
594 * @return int
595 */
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;
602
603 case 'raw':
604 case self::EDIT_RAW:
605 return self::EDIT_RAW;
606
607 case 'edit':
608 case self::EDIT_NORMAL:
609 return self::EDIT_NORMAL;
610
611 default:
612 return false;
613 }
614 }
615
616 /**
617 * Build a set of links for convenient navigation
618 * between watchlist viewing and editing modes
619 *
620 * @param $unused
621 * @return string
622 */
623 public static function buildTools( $unused ) {
624 global $wgLang;
625
626 $tools = array();
627 $modes = array(
628 'view' => array( 'Watchlist', false ),
629 'edit' => array( 'EditWatchlist', false ),
630 'raw' => array( 'EditWatchlist', 'raw' ),
631 );
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()
637 );
638 }
639 return Html::rawElement( 'span',
640 array( 'class' => 'mw-watchlist-toollinks' ),
641 wfMessage( 'parentheses', $wgLang->pipeList( $tools ) )->text() );
642 }
643 }
644
645 # B/C since 1.18
646 class WatchlistEditor extends SpecialEditWatchlist {}
647
648 /**
649 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
650 */
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 ) );
657 }
658 public function getBody() {
659 return $this->displaySection( $this->mFieldTree, '', 'editwatchlist-' );
660 }
661 }
662
663 class EditWatchlistCheckboxSeriesField extends HTMLMultiSelectField {
664 /**
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.
670 *
671 * @param $value String the value the field was submitted with
672 * @param $alldata Array the data collected from the form
673 * @return Mixed Bool true on success, or String error to display.
674 */
675 function validate( $value, $alldata ) {
676 // Need to call into grandparent to be a good citizen. :)
677 return HTMLFormField::validate( $value, $alldata );
678 }
679 }