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