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