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