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