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