Import: Handle uploads with sha1 starting with 0 properly
[mediawiki.git] / includes / specials / SpecialEditWatchlist.php
blob952ae0e7adc4b05ac7e53055ccb5c26f32d9bb5e
1 <?php
2 /**
3 * @defgroup Watchlist Users watchlist handling
4 */
6 /**
7 * Implements Special:EditWatchlist
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.
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.
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
24 * @file
25 * @ingroup SpecialPage
26 * @ingroup Watchlist
29 /**
30 * Provides the UI through which users can perform editing
31 * operations on their watchlist
33 * @ingroup SpecialPage
34 * @ingroup Watchlist
35 * @author Rob Church <robchur@gmail.com>
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.
42 const EDIT_CLEAR = 1;
43 const EDIT_RAW = 2;
44 const EDIT_NORMAL = 3;
46 protected $successMessage;
48 protected $toc;
50 private $badItems = array();
52 public function __construct() {
53 parent::__construct( 'EditWatchlist', 'editmywatchlist' );
56 /**
57 * Main execution point
59 * @param int $mode
61 public function execute( $mode ) {
62 $this->setHeaders();
64 # Anons don't get a watchlist
65 $this->requireLogin( 'watchlistanontext' );
67 $out = $this->getOutput();
69 $this->checkPermissions();
70 $this->checkReadOnly();
72 $this->outputHeader();
73 $this->outputSubtitle();
74 $out->addModuleStyles( 'mediawiki.special' );
76 # B/C: $mode used to be waaay down the parameter list, and the first parameter
77 # was $wgUser
78 if ( $mode instanceof User ) {
79 $args = func_get_args();
80 if ( count( $args ) >= 4 ) {
81 $mode = $args[3];
84 $mode = self::getMode( $this->getRequest(), $mode );
86 switch ( $mode ) {
87 case self::EDIT_RAW:
88 $out->setPageTitle( $this->msg( 'watchlistedit-raw-title' ) );
89 $form = $this->getRawForm();
90 if ( $form->show() ) {
91 $out->addHTML( $this->successMessage );
92 $out->addReturnTo( SpecialPage::getTitleFor( 'Watchlist' ) );
94 break;
95 case self::EDIT_CLEAR:
96 $out->setPageTitle( $this->msg( 'watchlistedit-clear-title' ) );
97 $form = $this->getClearForm();
98 if ( $form->show() ) {
99 $out->addHTML( $this->successMessage );
100 $out->addReturnTo( SpecialPage::getTitleFor( 'Watchlist' ) );
102 break;
104 case self::EDIT_NORMAL:
105 default:
106 $this->executeViewEditWatchlist();
107 break;
112 * Renders a subheader on the watchlist page.
114 protected function outputSubtitle() {
115 $out = $this->getOutput();
116 $out->addSubtitle( $this->msg( 'watchlistfor2', $this->getUser()->getName() )
117 ->rawParams( SpecialEditWatchlist::buildTools( null ) ) );
121 * Executes an edit mode for the watchlist view, from which you can manage your watchlist
124 protected function executeViewEditWatchlist() {
125 $out = $this->getOutput();
126 $out->setPageTitle( $this->msg( 'watchlistedit-normal-title' ) );
127 $form = $this->getNormalForm();
128 if ( $form->show() ) {
129 $out->addHTML( $this->successMessage );
130 $out->addReturnTo( SpecialPage::getTitleFor( 'Watchlist' ) );
131 } elseif ( $this->toc !== false ) {
132 $out->prependHTML( $this->toc );
133 $out->addModules( 'mediawiki.toc' );
138 * Return an array of subpages that this special page will accept.
140 * @see also SpecialWatchlist::getSubpagesForPrefixSearch
141 * @return string[] subpages
143 public function getSubpagesForPrefixSearch() {
144 // SpecialWatchlist uses SpecialEditWatchlist::getMode, so new types should be added
145 // here and there - no 'edit' here, because that the default for this page
146 return array(
147 'clear',
148 'raw',
153 * Extract a list of titles from a blob of text, returning
154 * (prefixed) strings; unwatchable titles are ignored
156 * @param string $list
157 * @return array
159 private function extractTitles( $list ) {
160 $list = explode( "\n", trim( $list ) );
161 if ( !is_array( $list ) ) {
162 return array();
165 $titles = array();
167 foreach ( $list as $text ) {
168 $text = trim( $text );
169 if ( strlen( $text ) > 0 ) {
170 $title = Title::newFromText( $text );
171 if ( $title instanceof Title && $title->isWatchable() ) {
172 $titles[] = $title;
177 GenderCache::singleton()->doTitlesArray( $titles );
179 $list = array();
180 /** @var Title $title */
181 foreach ( $titles as $title ) {
182 $list[] = $title->getPrefixedText();
185 return array_unique( $list );
188 public function submitRaw( $data ) {
189 $wanted = $this->extractTitles( $data['Titles'] );
190 $current = $this->getWatchlist();
192 if ( count( $wanted ) > 0 ) {
193 $toWatch = array_diff( $wanted, $current );
194 $toUnwatch = array_diff( $current, $wanted );
195 $this->watchTitles( $toWatch );
196 $this->unwatchTitles( $toUnwatch );
197 $this->getUser()->invalidateCache();
199 if ( count( $toWatch ) > 0 || count( $toUnwatch ) > 0 ) {
200 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
201 } else {
202 return false;
205 if ( count( $toWatch ) > 0 ) {
206 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-added' )
207 ->numParams( count( $toWatch ) )->parse();
208 $this->showTitles( $toWatch, $this->successMessage );
211 if ( count( $toUnwatch ) > 0 ) {
212 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed' )
213 ->numParams( count( $toUnwatch ) )->parse();
214 $this->showTitles( $toUnwatch, $this->successMessage );
216 } else {
217 $this->clearWatchlist();
218 $this->getUser()->invalidateCache();
220 if ( count( $current ) > 0 ) {
221 $this->successMessage = $this->msg( 'watchlistedit-raw-done' )->parse();
222 } else {
223 return false;
226 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-raw-removed' )
227 ->numParams( count( $current ) )->parse();
228 $this->showTitles( $current, $this->successMessage );
231 return true;
234 public function submitClear( $data ) {
235 $current = $this->getWatchlist();
236 $this->clearWatchlist();
237 $this->getUser()->invalidateCache();
238 $this->successMessage = $this->msg( 'watchlistedit-clear-done' )->parse();
239 $this->successMessage .= ' ' . $this->msg( 'watchlistedit-clear-removed' )
240 ->numParams( count( $current ) )->parse();
241 $this->showTitles( $current, $this->successMessage );
243 return true;
247 * Print out a list of linked titles
249 * $titles can be an array of strings or Title objects; the former
250 * is preferred, since Titles are very memory-heavy
252 * @param array $titles Array of strings, or Title objects
253 * @param string $output
255 private function showTitles( $titles, &$output ) {
256 $talk = $this->msg( 'talkpagelinktext' )->escaped();
257 // Do a batch existence check
258 $batch = new LinkBatch();
259 if ( count( $titles ) >= 100 ) {
260 $output = $this->msg( 'watchlistedit-too-many' )->parse();
261 return;
263 foreach ( $titles as $title ) {
264 if ( !$title instanceof Title ) {
265 $title = Title::newFromText( $title );
268 if ( $title instanceof Title ) {
269 $batch->addObj( $title );
270 $batch->addObj( $title->getTalkPage() );
274 $batch->execute();
276 // Print out the list
277 $output .= "<ul>\n";
279 foreach ( $titles as $title ) {
280 if ( !$title instanceof Title ) {
281 $title = Title::newFromText( $title );
284 if ( $title instanceof Title ) {
285 $output .= '<li>' .
286 Linker::link( $title ) . ' ' .
287 $this->msg( 'parentheses' )->rawParams(
288 Linker::link( $title->getTalkPage(), $talk )
289 )->escaped() .
290 "</li>\n";
294 $output .= "</ul>\n";
298 * Prepare a list of titles on a user's watchlist (excluding talk pages)
299 * and return an array of (prefixed) strings
301 * @return array
303 private function getWatchlist() {
304 $list = array();
306 $index = $this->getRequest()->wasPosted() ? DB_MASTER : DB_SLAVE;
307 $dbr = wfGetDB( $index );
309 $res = $dbr->select(
310 'watchlist',
311 array(
312 'wl_namespace', 'wl_title'
313 ), array(
314 'wl_user' => $this->getUser()->getId(),
316 __METHOD__
319 if ( $res->numRows() > 0 ) {
320 /** @var Title[] $titles */
321 $titles = array();
322 foreach ( $res as $row ) {
323 $title = Title::makeTitleSafe( $row->wl_namespace, $row->wl_title );
325 if ( $this->checkTitle( $title, $row->wl_namespace, $row->wl_title )
326 && !$title->isTalkPage()
328 $titles[] = $title;
331 $res->free();
333 GenderCache::singleton()->doTitlesArray( $titles );
335 foreach ( $titles as $title ) {
336 $list[] = $title->getPrefixedText();
340 $this->cleanupWatchlist();
342 return $list;
346 * Get a list of titles on a user's watchlist, excluding talk pages,
347 * and return as a two-dimensional array with namespace and title.
349 * @return array
351 protected function getWatchlistInfo() {
352 $titles = array();
353 $dbr = wfGetDB( DB_SLAVE );
355 $res = $dbr->select(
356 array( 'watchlist' ),
357 array( 'wl_namespace', 'wl_title' ),
358 array( 'wl_user' => $this->getUser()->getId() ),
359 __METHOD__,
360 array( 'ORDER BY' => array( 'wl_namespace', 'wl_title' ) )
363 $lb = new LinkBatch();
365 foreach ( $res as $row ) {
366 $lb->add( $row->wl_namespace, $row->wl_title );
367 if ( !MWNamespace::isTalk( $row->wl_namespace ) ) {
368 $titles[$row->wl_namespace][$row->wl_title] = 1;
372 $lb->execute();
374 return $titles;
378 * Validates watchlist entry
380 * @param Title $title
381 * @param int $namespace
382 * @param string $dbKey
383 * @return bool Whether this item is valid
385 private function checkTitle( $title, $namespace, $dbKey ) {
386 if ( $title
387 && ( $title->isExternal()
388 || $title->getNamespace() < 0
391 $title = false; // unrecoverable
394 if ( !$title
395 || $title->getNamespace() != $namespace
396 || $title->getDBkey() != $dbKey
398 $this->badItems[] = array( $title, $namespace, $dbKey );
401 return (bool)$title;
405 * Attempts to clean up broken items
407 private function cleanupWatchlist() {
408 if ( !count( $this->badItems ) ) {
409 return; // nothing to do
412 $dbw = wfGetDB( DB_MASTER );
413 $user = $this->getUser();
415 foreach ( $this->badItems as $row ) {
416 list( $title, $namespace, $dbKey ) = $row;
417 $action = $title ? 'cleaning up' : 'deleting';
418 wfDebug( "User {$user->getName()} has broken watchlist item ns($namespace):$dbKey, $action.\n" );
420 $dbw->delete( 'watchlist',
421 array(
422 'wl_user' => $user->getId(),
423 'wl_namespace' => $namespace,
424 'wl_title' => $dbKey,
426 __METHOD__
429 // Can't just do an UPDATE instead of DELETE/INSERT due to unique index
430 if ( $title ) {
431 $user->addWatch( $title );
437 * Remove all titles from a user's watchlist
439 private function clearWatchlist() {
440 $dbw = wfGetDB( DB_MASTER );
441 $dbw->delete(
442 'watchlist',
443 array( 'wl_user' => $this->getUser()->getId() ),
444 __METHOD__
449 * Add a list of titles to a user's watchlist
451 * $titles can be an array of strings or Title objects; the former
452 * is preferred, since Titles are very memory-heavy
454 * @param array $titles Array of strings, or Title objects
456 private function watchTitles( $titles ) {
457 $dbw = wfGetDB( DB_MASTER );
458 $rows = array();
460 foreach ( $titles as $title ) {
461 if ( !$title instanceof Title ) {
462 $title = Title::newFromText( $title );
465 if ( $title instanceof Title ) {
466 $rows[] = array(
467 'wl_user' => $this->getUser()->getId(),
468 'wl_namespace' => MWNamespace::getSubject( $title->getNamespace() ),
469 'wl_title' => $title->getDBkey(),
470 'wl_notificationtimestamp' => null,
472 $rows[] = array(
473 'wl_user' => $this->getUser()->getId(),
474 'wl_namespace' => MWNamespace::getTalk( $title->getNamespace() ),
475 'wl_title' => $title->getDBkey(),
476 'wl_notificationtimestamp' => null,
481 $dbw->insert( 'watchlist', $rows, __METHOD__, 'IGNORE' );
485 * Remove a list of titles from a user's watchlist
487 * $titles can be an array of strings or Title objects; the former
488 * is preferred, since Titles are very memory-heavy
490 * @param array $titles Array of strings, or Title objects
492 private function unwatchTitles( $titles ) {
493 $dbw = wfGetDB( DB_MASTER );
495 foreach ( $titles as $title ) {
496 if ( !$title instanceof Title ) {
497 $title = Title::newFromText( $title );
500 if ( $title instanceof Title ) {
501 $dbw->delete(
502 'watchlist',
503 array(
504 'wl_user' => $this->getUser()->getId(),
505 'wl_namespace' => MWNamespace::getSubject( $title->getNamespace() ),
506 'wl_title' => $title->getDBkey(),
508 __METHOD__
511 $dbw->delete(
512 'watchlist',
513 array(
514 'wl_user' => $this->getUser()->getId(),
515 'wl_namespace' => MWNamespace::getTalk( $title->getNamespace() ),
516 'wl_title' => $title->getDBkey(),
518 __METHOD__
521 $page = WikiPage::factory( $title );
522 Hooks::run( 'UnwatchArticleComplete', array( $this->getUser(), &$page ) );
527 public function submitNormal( $data ) {
528 $removed = array();
530 foreach ( $data as $titles ) {
531 $this->unwatchTitles( $titles );
532 $removed = array_merge( $removed, $titles );
535 if ( count( $removed ) > 0 ) {
536 $this->successMessage = $this->msg( 'watchlistedit-normal-done'
537 )->numParams( count( $removed ) )->parse();
538 $this->showTitles( $removed, $this->successMessage );
540 return true;
541 } else {
542 return false;
547 * Get the standard watchlist editing form
549 * @return HTMLForm
551 protected function getNormalForm() {
552 global $wgContLang;
554 $fields = array();
555 $count = 0;
557 // Allow subscribers to manipulate the list of watched pages (or use it
558 // to preload lots of details at once)
559 $watchlistInfo = $this->getWatchlistInfo();
560 Hooks::run(
561 'WatchlistEditorBeforeFormRender',
562 array( &$watchlistInfo )
565 foreach ( $watchlistInfo as $namespace => $pages ) {
566 $options = array();
568 foreach ( array_keys( $pages ) as $dbkey ) {
569 $title = Title::makeTitleSafe( $namespace, $dbkey );
571 if ( $this->checkTitle( $title, $namespace, $dbkey ) ) {
572 $text = $this->buildRemoveLine( $title );
573 $options[$text] = $title->getPrefixedText();
574 $count++;
578 // checkTitle can filter some options out, avoid empty sections
579 if ( count( $options ) > 0 ) {
580 $fields['TitlesNs' . $namespace] = array(
581 'class' => 'EditWatchlistCheckboxSeriesField',
582 'options' => $options,
583 'section' => "ns$namespace",
587 $this->cleanupWatchlist();
589 if ( count( $fields ) > 1 && $count > 30 ) {
590 $this->toc = Linker::tocIndent();
591 $tocLength = 0;
593 foreach ( $fields as $data ) {
594 # strip out the 'ns' prefix from the section name:
595 $ns = substr( $data['section'], 2 );
597 $nsText = ( $ns == NS_MAIN )
598 ? $this->msg( 'blanknamespace' )->escaped()
599 : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) );
600 $this->toc .= Linker::tocLine( "editwatchlist-{$data['section']}", $nsText,
601 $this->getLanguage()->formatNum( ++$tocLength ), 1 ) . Linker::tocLineEnd();
604 $this->toc = Linker::tocList( $this->toc );
605 } else {
606 $this->toc = false;
609 $context = new DerivativeContext( $this->getContext() );
610 $context->setTitle( $this->getPageTitle() ); // Remove subpage
611 $form = new EditWatchlistNormalHTMLForm( $fields, $context );
612 $form->setSubmitTextMsg( 'watchlistedit-normal-submit' );
613 $form->setSubmitDestructive();
614 # Used message keys:
615 # 'accesskey-watchlistedit-normal-submit', 'tooltip-watchlistedit-normal-submit'
616 $form->setSubmitTooltip( 'watchlistedit-normal-submit' );
617 $form->setWrapperLegendMsg( 'watchlistedit-normal-legend' );
618 $form->addHeaderText( $this->msg( 'watchlistedit-normal-explain' )->parse() );
619 $form->setSubmitCallback( array( $this, 'submitNormal' ) );
621 return $form;
625 * Build the label for a checkbox, with a link to the title, and various additional bits
627 * @param Title $title
628 * @return string
630 private function buildRemoveLine( $title ) {
631 $link = Linker::link( $title );
633 $tools['talk'] = Linker::link(
634 $title->getTalkPage(),
635 $this->msg( 'talkpagelinktext' )->escaped()
638 if ( $title->exists() ) {
639 $tools['history'] = Linker::linkKnown(
640 $title,
641 $this->msg( 'history_short' )->escaped(),
642 array(),
643 array( 'action' => 'history' )
647 if ( $title->getNamespace() == NS_USER && !$title->isSubpage() ) {
648 $tools['contributions'] = Linker::linkKnown(
649 SpecialPage::getTitleFor( 'Contributions', $title->getText() ),
650 $this->msg( 'contributions' )->escaped()
654 Hooks::run(
655 'WatchlistEditorBuildRemoveLine',
656 array( &$tools, $title, $title->isRedirect(), $this->getSkin(), &$link )
659 if ( $title->isRedirect() ) {
660 // Linker already makes class mw-redirect, so this is redundant
661 $link = '<span class="watchlistredir">' . $link . '</span>';
664 return $link . ' ' .
665 $this->msg( 'parentheses' )->rawParams( $this->getLanguage()->pipeList( $tools ) )->escaped();
669 * Get a form for editing the watchlist in "raw" mode
671 * @return HTMLForm
673 protected function getRawForm() {
674 $titles = implode( $this->getWatchlist(), "\n" );
675 $fields = array(
676 'Titles' => array(
677 'type' => 'textarea',
678 'label-message' => 'watchlistedit-raw-titles',
679 'default' => $titles,
682 $context = new DerivativeContext( $this->getContext() );
683 $context->setTitle( $this->getPageTitle( 'raw' ) ); // Reset subpage
684 $form = new HTMLForm( $fields, $context );
685 $form->setSubmitTextMsg( 'watchlistedit-raw-submit' );
686 # Used message keys: 'accesskey-watchlistedit-raw-submit', 'tooltip-watchlistedit-raw-submit'
687 $form->setSubmitTooltip( 'watchlistedit-raw-submit' );
688 $form->setWrapperLegendMsg( 'watchlistedit-raw-legend' );
689 $form->addHeaderText( $this->msg( 'watchlistedit-raw-explain' )->parse() );
690 $form->setSubmitCallback( array( $this, 'submitRaw' ) );
692 return $form;
696 * Get a form for clearing the watchlist
698 * @return HTMLForm
700 protected function getClearForm() {
701 $context = new DerivativeContext( $this->getContext() );
702 $context->setTitle( $this->getPageTitle( 'clear' ) ); // Reset subpage
703 $form = new HTMLForm( array(), $context );
704 $form->setSubmitTextMsg( 'watchlistedit-clear-submit' );
705 # Used message keys: 'accesskey-watchlistedit-clear-submit', 'tooltip-watchlistedit-clear-submit'
706 $form->setSubmitTooltip( 'watchlistedit-clear-submit' );
707 $form->setWrapperLegendMsg( 'watchlistedit-clear-legend' );
708 $form->addHeaderText( $this->msg( 'watchlistedit-clear-explain' )->parse() );
709 $form->setSubmitCallback( array( $this, 'submitClear' ) );
710 $form->setSubmitDestructive();
712 return $form;
716 * Determine whether we are editing the watchlist, and if so, what
717 * kind of editing operation
719 * @param WebRequest $request
720 * @param string $par
721 * @return int
723 public static function getMode( $request, $par ) {
724 $mode = strtolower( $request->getVal( 'action', $par ) );
726 switch ( $mode ) {
727 case 'clear':
728 case self::EDIT_CLEAR:
729 return self::EDIT_CLEAR;
730 case 'raw':
731 case self::EDIT_RAW:
732 return self::EDIT_RAW;
733 case 'edit':
734 case self::EDIT_NORMAL:
735 return self::EDIT_NORMAL;
736 default:
737 return false;
742 * Build a set of links for convenient navigation
743 * between watchlist viewing and editing modes
745 * @param null $unused
746 * @return string
748 public static function buildTools( $unused ) {
749 global $wgLang;
751 $tools = array();
752 $modes = array(
753 'view' => array( 'Watchlist', false ),
754 'edit' => array( 'EditWatchlist', false ),
755 'raw' => array( 'EditWatchlist', 'raw' ),
756 'clear' => array( 'EditWatchlist', 'clear' ),
759 foreach ( $modes as $mode => $arr ) {
760 // can use messages 'watchlisttools-view', 'watchlisttools-edit', 'watchlisttools-raw'
761 $tools[] = Linker::linkKnown(
762 SpecialPage::getTitleFor( $arr[0], $arr[1] ),
763 wfMessage( "watchlisttools-{$mode}" )->escaped()
767 return Html::rawElement(
768 'span',
769 array( 'class' => 'mw-watchlist-toollinks' ),
770 wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $tools ) )->escaped()
776 * Extend HTMLForm purely so we can have a more sane way of getting the section headers
778 class EditWatchlistNormalHTMLForm extends HTMLForm {
779 public function getLegend( $namespace ) {
780 $namespace = substr( $namespace, 2 );
782 return $namespace == NS_MAIN
783 ? $this->msg( 'blanknamespace' )->escaped()
784 : htmlspecialchars( $this->getContext()->getLanguage()->getFormattedNsText( $namespace ) );
787 public function getBody() {
788 return $this->displaySection( $this->mFieldTree, '', 'editwatchlist-' );
792 class EditWatchlistCheckboxSeriesField extends HTMLMultiSelectField {
794 * HTMLMultiSelectField throws validation errors if we get input data
795 * that doesn't match the data set in the form setup. This causes
796 * problems if something gets removed from the watchlist while the
797 * form is open (bug 32126), but we know that invalid items will
798 * be harmless so we can override it here.
800 * @param string $value The value the field was submitted with
801 * @param array $alldata The data collected from the form
802 * @return bool|string Bool true on success, or String error to display.
804 function validate( $value, $alldata ) {
805 // Need to call into grandparent to be a good citizen. :)
806 return HTMLFormField::validate( $value, $alldata );