Use local context to get message instead of relying on global variables
[lhc/web/wiklou.git] / includes / specials / SpecialBlock.php
index 49b2251..7d93cc7 100644 (file)
@@ -27,7 +27,7 @@
  *
  * @ingroup SpecialPage
  */
-class SpecialBlock extends SpecialPage {
+class SpecialBlock extends FormSpecialPage {
        /** The maximum number of edits a user can have and still be hidden
         * TODO: config setting? */
        const HIDEUSER_CONTRIBLIMIT = 1000;
@@ -55,18 +55,28 @@ class SpecialBlock extends SpecialPage {
                parent::__construct( 'Block', 'block' );
        }
 
-       public function execute( $par ) {
-               # Permission check
-               if( !$this->userCanExecute( $this->getUser() ) ) {
-                       $this->displayRestrictionError();
-                       return;
-               }
+       /**
+        * Checks that the user can unblock themselves if they are trying to do so
+        *
+        * @param User $user
+        * @throws ErrorPageError
+        */
+       protected function checkExecutePermissions( User $user ) {
+                parent::checkExecutePermissions( $user );
 
-               # Can't block when the database is locked
-               if( wfReadOnly() ) {
-                       throw new ReadOnlyError;
+               # bug 15810: blocked admins should have limited access here
+               $status = self::checkUnblockSelf( $this->target, $user );
+               if ( $status !== true ) {
+                       throw new ErrorPageError( 'badaccess', $status );
                }
+       }
 
+       /**
+        * Handle some magic here
+        *
+        * @param $par String
+        */
+       protected function setParameter( $par ) {
                # Extract variables from the request.  Try not to get into a situation where we
                # need to extract *every* variable from the form just for processing here, but
                # there are legitimate uses for some variables
@@ -80,39 +90,31 @@ class SpecialBlock extends SpecialPage {
 
                list( $this->previousTarget, /*...*/ ) = Block::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
                $this->requestedHideUser = $request->getBool( 'wpHideUser' );
+       }
 
-               # bug 15810: blocked admins should have limited access here
-               $status = self::checkUnblockSelf( $this->target );
-               if ( $status !== true ) {
-                       throw new ErrorPageError( 'badaccess', $status );
-               }
-
-               $this->setHeaders();
-               $this->outputHeader();
-
-               $out = $this->getOutput();
-               $out->setPageTitle( wfMsg( 'blockip-title' ) );
-               $out->addModules( array( 'mediawiki.special', 'mediawiki.special.block' ) );
-
-               $fields = $this->getFormFields();
-               $this->maybeAlterFormDefaults( $fields );
-
-               $form = new HTMLForm( $fields, $this->getContext() );
-               $form->setWrapperLegend( wfMsg( 'blockip-legend' ) );
-               $form->setSubmitCallback( array( __CLASS__, 'processForm' ) );
-
-               $t = $this->alreadyBlocked
-                       ? wfMsg( 'ipb-change-block' )
-                       : wfMsg( 'ipbsubmit' );
-               $form->setSubmitText( $t );
+       /**
+        * Customizes the HTMLForm a bit
+        *
+        * @param $form HTMLForm
+        */
+       protected function alterForm( HTMLForm $form ) {
+               $form->setWrapperLegendMsg( 'blockip-legend' );
+               $form->setHeaderText( '' );
+               $form->setSubmitCallback( array( __CLASS__, 'processUIForm' ) );
 
-               $this->doPreText( $form );
-               $this->doHeadertext( $form );
-               $this->doPostText( $form );
+               $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
+               $form->setSubmitTextMsg( $msg );
 
-               if( $form->show() ){
-                       $out->setPageTitle( wfMsg( 'blockipsuccesssub' ) );
-                       $out->addWikiMsg( 'blockipsuccesstext',  $this->target );
+               # Don't need to do anything if the form has been posted
+               if( !$this->getRequest()->wasPosted() && $this->preErrors ){
+                       $s = HTMLForm::formatErrors( $this->preErrors );
+                       if( $s ){
+                               $form->addHeaderText( Html::rawElement(
+                                               'div',
+                                               array( 'class' => 'error' ),
+                                               $s
+                                       ) );
+                       }
                }
        }
 
@@ -141,7 +143,7 @@ class SpecialBlock extends SpecialPage {
                                'required' => true,
                                'tabindex' => '2',
                                'options' => self::getSuggestedDurations(),
-                               'other' => wfMsg( 'ipbother' ),
+                               'other' => $this->msg( 'ipbother' )->text(),
                        ),
                        'Reason' => array(
                                'type' => 'selectandother',
@@ -213,13 +215,15 @@ class SpecialBlock extends SpecialPage {
                        'label-message' => 'ipb-confirm',
                );
 
+               $this->maybeAlterFormDefaults( $a );
+
                return $a;
        }
 
        /**
         * If the user has already been blocked with similar settings, load that block
         * and change the defaults for the form fields to match the existing settings.
-        * @param &$fields Array HTMLForm descriptor array
+        * @param $fields Array HTMLForm descriptor array
         * @return Bool whether fields were altered (that is, whether the target is
         *     already blocked)
         */
@@ -293,11 +297,9 @@ class SpecialBlock extends SpecialPage {
 
        /**
         * Add header elements like block log entries, etc.
-        * @param  $form HTMLForm
-        * @return void
         */
-       protected function doPreText( HTMLForm &$form ){
-               $form->addPreText( wfMsgExt( 'blockiptext', 'parse' ) );
+       protected function preText(){
+               $text = $this->msg( 'blockiptext' )->parse();
 
                $otherBlockMessages = array();
                if( $this->target !== null ) {
@@ -308,7 +310,7 @@ class SpecialBlock extends SpecialPage {
                                $s = Html::rawElement(
                                        'h2',
                                        array(),
-                                       wfMsgExt( 'ipb-otherblocks-header', 'parseinline', count( $otherBlockMessages ) )
+                                       $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
                                ) . "\n";
 
                                $list = '';
@@ -323,51 +325,33 @@ class SpecialBlock extends SpecialPage {
                                        $list
                                ) . "\n";
 
-                               $form->addPreText( $s );
+                               $text .= $s;
                        }
                }
-       }
 
-       /**
-        * Add header text inside the form, just underneath where the errors would go
-        * @param $form HTMLForm
-        * @return void
-        */
-       protected function doHeaderText( HTMLForm &$form ){
-               # Don't need to do anything if the form has been posted
-               if( !$this->getRequest()->wasPosted() && $this->preErrors ){
-                       $s = HTMLForm::formatErrors( $this->preErrors );
-                       if( $s ){
-                               $form->addHeaderText( Html::rawElement(
-                                       'div',
-                                       array( 'class' => 'error' ),
-                                       $s
-                               ) );
-                       }
-               }
+               return $text;
        }
 
        /**
         * Add footer elements to the form
-        * @param  $form HTMLForm
-        * @return void
+        * @return string
         */
-       protected function doPostText( HTMLForm &$form ){
+       protected function postText(){
                # Link to the user's contributions, if applicable
                if( $this->target instanceof User ){
                        $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
                        $links[] = Linker::link(
                                $contribsPage,
-                               wfMsgExt( 'ipb-blocklist-contribs', 'escape', $this->target->getName() )
+                               $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->escaped()
                        );
                }
 
                # Link to unblock the specified user, or to a blank unblock form
                if( $this->target instanceof User ) {
-                       $message = wfMsgExt( 'ipb-unblock-addr', array( 'parseinline' ), $this->target->getName() );
+                       $message = $this->msg( 'ipb-unblock-addr', $this->target->getName() )->parse();
                        $list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
                } else {
-                       $message = wfMsgExt( 'ipb-unblock', array( 'parseinline' ) );
+                       $message = $this->msg( 'ipb-unblock' )->parse();
                        $list = SpecialPage::getTitleFor( 'Unblock' );
                }
                $links[] = Linker::linkKnown( $list, $message, array() );
@@ -375,7 +359,7 @@ class SpecialBlock extends SpecialPage {
                # Link to the block list
                $links[] = Linker::linkKnown(
                        SpecialPage::getTitleFor( 'BlockList' ),
-                       wfMsg( 'ipb-blocklist' )
+                       $this->msg( 'ipb-blocklist' )->escaped()
                );
 
                $user = $this->getUser();
@@ -384,17 +368,17 @@ class SpecialBlock extends SpecialPage {
                if ( $user->isAllowed( 'editinterface' ) ) {
                        $links[] = Linker::link(
                                Title::makeTitle( NS_MEDIAWIKI, 'Ipbreason-dropdown' ),
-                               wfMsgHtml( 'ipb-edit-dropdown' ),
+                               $this->msg( 'ipb-edit-dropdown' )->escaped(),
                                array(),
                                array( 'action' => 'edit' )
                        );
                }
 
-               $form->addPostText( Html::rawElement(
+               $text =  Html::rawElement(
                        'p',
                        array( 'class' => 'mw-ipb-conveniencelinks' ),
-                       $this->getLang()->pipeList( $links )
-               ) );
+                       $this->getLanguage()->pipeList( $links )
+               );
 
                if( $this->target instanceof User ){
                        # Get relevant extracts from the block and suppression logs, if possible
@@ -412,7 +396,7 @@ class SpecialBlock extends SpecialPage {
                                        'showIfEmpty' => false
                                )
                        );
-                       $form->addPostText( $out );
+                       $text .= $out;
 
                        # Add suppression block entries if allowed
                        if( $user->isAllowed( 'suppressionlog' ) ) {
@@ -429,9 +413,11 @@ class SpecialBlock extends SpecialPage {
                                        )
                                );
 
-                               $form->addPostText( $out );
+                               $text .= $out;
                        }
                }
+
+               return $text;
        }
 
        /**
@@ -490,9 +476,10 @@ class SpecialBlock extends SpecialPage {
         * @since 1.18
         * @param $value String
         * @param $alldata Array
+        * @param $form HTMLForm
         * @return Message
         */
-       public static function validateTargetField( $value, $alldata = null ) {
+       public static function validateTargetField( $value, $alldata, $form ) {
                global $wgBlockCIDRLimit;
 
                list( $target, $type ) = self::getTargetAndType( $value );
@@ -500,55 +487,68 @@ class SpecialBlock extends SpecialPage {
                if( $type == Block::TYPE_USER ){
                        # TODO: why do we not have a User->exists() method?
                        if( !$target->getId() ){
-                               return wfMessage( 'nosuchusershort',
+                               return $form->msg( 'nosuchusershort',
                                        wfEscapeWikiText( $target->getName() ) );
                        }
 
-                       $status = self::checkUnblockSelf( $target );
+                       $status = self::checkUnblockSelf( $target, $form->getUser() );
                        if ( $status !== true ) {
-                               return wfMessage( 'badaccess', $status );
+                               return $form->msg( 'badaccess', $status );
                        }
 
                } elseif( $type == Block::TYPE_RANGE ){
                        list( $ip, $range ) = explode( '/', $target, 2 );
 
                        if( ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 )
-                               || ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPV6'] == 128 ) )
+                               || ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 ) )
                        {
                                # Range block effectively disabled
-                               return wfMessage( 'range_block_disabled' );
+                               return $form->msg( 'range_block_disabled' );
                        }
 
                        if( ( IP::isIPv4( $ip ) && $range > 32 )
                                || ( IP::isIPv6( $ip ) && $range > 128 ) )
                        {
                                # Dodgy range
-                               return wfMessage( 'ip_range_invalid' );
+                               return $form->msg( 'ip_range_invalid' );
                        }
 
                        if( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
-                               return wfMessage( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
+                               return $form->msg( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
                        }
 
                        if( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
-                               return wfMessage( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
+                               return $form->msg( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
                        }
                } elseif( $type == Block::TYPE_IP ){
                        # All is well
                } else {
-                       return wfMessage( 'badipaddress' );
+                       return $form->msg( 'badipaddress' );
                }
 
                return true;
        }
 
+       /**
+        * Submit callback for an HTMLForm object, will simply pass
+        * @param $data array
+        * @param $form HTMLForm
+        * @return Bool|String
+        */
+       public static function processUIForm( array $data, HTMLForm $form ) {
+               return self::processForm( $data, $form->getContext() );
+       }
+
        /**
         * Given the form data, actually implement a block
         * @param  $data Array
+        * @param  $context IContextSource
         * @return Bool|String
         */
-       public static function processForm( array $data ){
-               global $wgUser, $wgBlockAllowsUTEdit;
+       public static function processForm( array $data, IContextSource $context ){
+               global $wgBlockAllowsUTEdit;
+
+               $performer = $context->getUser();
 
                // Handled by field validator callback
                // self::validateTargetField( $data['Target'] );
@@ -565,9 +565,13 @@ class SpecialBlock extends SpecialPage {
 
                        # Give admins a heads-up before they go and block themselves.  Much messier
                        # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
-                       # permission anyway, although the code does allow for it
-                       if( $target === $wgUser->getName() &&
-                               ( $data['PreviousTarget'] !== $data['Target'] || !$data['Confirm'] ) )
+                       # permission anyway, although the code does allow for it.
+                       # Note: Important to use $target instead of $data['Target']
+                       # since both $data['PreviousTarget'] and $target are normalized
+                       # but $data['target'] gets overriden by (non-normalized) request variable
+                       # from previous request.
+                       if( $target === $performer->getName() &&
+                               ( $data['PreviousTarget'] !== $target || !$data['Confirm'] ) )
                        {
                                return array( 'ipb-blockingself' );
                        }
@@ -598,7 +602,7 @@ class SpecialBlock extends SpecialPage {
                }
 
                if( $data['HideUser'] ) {
-                       if( !$wgUser->isAllowed('hideuser') ){
+                       if( !$performer->isAllowed('hideuser') ){
                                # this codepath is unreachable except by a malicious user spoofing forms,
                                # or by race conditions (user has oversight and sysop, loads block form,
                                # and is de-oversighted before submission); so need to fail completely
@@ -624,7 +628,7 @@ class SpecialBlock extends SpecialPage {
                # Create block object.
                $block = new Block();
                $block->setTarget( $target );
-               $block->setBlocker( $wgUser );
+               $block->setBlocker( $performer );
                $block->mReason = $data['Reason'][0];
                $block->mExpiry = self::parseExpiryInput( $data['Expiry'] );
                $block->prevents( 'createaccount', $data['CreateAccount'] );
@@ -634,7 +638,7 @@ class SpecialBlock extends SpecialPage {
                $block->isAutoblocking( $data['AutoBlock'] );
                $block->mHideName = $data['HideUser'];
 
-               if( !wfRunHooks( 'BlockIp', array( &$block, &$wgUser ) ) ) {
+               if( !wfRunHooks( 'BlockIp', array( &$block, &$performer ) ) ) {
                        return array( 'hookaborted' );
                }
 
@@ -658,7 +662,7 @@ class SpecialBlock extends SpecialPage {
 
                                # If the name was hidden and the blocking user cannot hide
                                # names, then don't allow any block changes...
-                               if( $currentBlock->mHideName && !$wgUser->isAllowed( 'hideuser' ) ) {
+                               if( $currentBlock->mHideName && !$performer->isAllowed( 'hideuser' ) ) {
                                        return array( 'cant-see-hidden-user' );
                                }
 
@@ -680,7 +684,7 @@ class SpecialBlock extends SpecialPage {
                        $logaction = 'block';
                }
 
-               wfRunHooks( 'BlockIpComplete', array( $block, $wgUser ) );
+               wfRunHooks( 'BlockIpComplete', array( $block, $performer ) );
 
                # Set *_deleted fields if requested
                if( $data['HideUser'] ) {
@@ -689,7 +693,7 @@ class SpecialBlock extends SpecialPage {
 
                # Can't watch a rangeblock
                if( $type != Block::TYPE_RANGE && $data['Watch'] ) {
-                       $wgUser->addWatch( Title::makeTitle( NS_USER, $target ) );
+                       $performer->addWatch( Title::makeTitle( NS_USER, $target ) );
                }
 
                # Block constructor sanitizes certain block options on insert
@@ -791,24 +795,23 @@ class SpecialBlock extends SpecialPage {
         * others, and probably shouldn't be able to unblock themselves
         * either.
         * @param $user User|Int|String
+        * @param $performer User user doing the request
         * @return Bool|String true or error message key
         */
-       public static function checkUnblockSelf( $user ) {
-               global $wgUser;
-
+       public static function checkUnblockSelf( $user, User $performer ) {
                if ( is_int( $user ) ) {
                        $user = User::newFromId( $user );
                } elseif ( is_string( $user ) ) {
                        $user = User::newFromName( $user );
                }
 
-               if( $wgUser->isBlocked() ){
-                       if( $user instanceof User && $user->getId() == $wgUser->getId() ) {
+               if( $performer->isBlocked() ){
+                       if( $user instanceof User && $user->getId() == $performer->getId() ) {
                                # User is trying to unblock themselves
-                               if ( $wgUser->isAllowed( 'unblockself' ) ) {
+                               if ( $performer->isAllowed( 'unblockself' ) ) {
                                        return true;
                                # User blocked themselves and is now trying to reverse it
-                               } elseif ( $wgUser->blockedBy() === $wgUser->getName() ) {
+                               } elseif ( $performer->blockedBy() === $performer->getName() ) {
                                        return true;
                                } else {
                                        return 'ipbnounblockself';
@@ -826,7 +829,7 @@ class SpecialBlock extends SpecialPage {
         * Return a comma-delimited list of "flags" to be passed to the log
         * reader for this block, to provide more information in the logs
         * @param $data Array from HTMLForm data
-        * @param $type Block::TYPE_ constant
+        * @param $type Block::TYPE_ constant (USER, RANGE, or IP)
         * @return array
         */
        protected static function blockLogFlags( array $data, $type ) {
@@ -845,7 +848,7 @@ class SpecialBlock extends SpecialPage {
                }
 
                # Same as anononly, this is not displayed when blocking an IP address
-               if( !$data['AutoBlock'] && $type != Block::TYPE_IP ){
+               if( !$data['AutoBlock'] && $type == Block::TYPE_USER ){
                        // For grepping: message block-log-flags-noautoblock
                        $flags[] = 'noautoblock';
                }
@@ -867,6 +870,26 @@ class SpecialBlock extends SpecialPage {
 
                return implode( ',', $flags );
        }
+
+       /**
+        * Process the form on POST submission.
+        * @param  $data Array
+        * @return Bool|Array true for success, false for didn't-try, array of errors on failure
+        */
+       public function onSubmit( array $data ) {
+               // This isn't used since we need that HTMLForm that's passed in the
+               // second parameter. See alterForm for the real function
+       }
+
+       /**
+        * Do something exciting on successful processing of the form, most likely to show a
+        * confirmation message
+        */
+       public function onSuccess() {
+               $out = $this->getOutput();
+               $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
+               $out->addWikiMsg( 'blockipsuccesstext',  $this->target );
+       }
 }
 
 # BC @since 1.18