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