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