3 * Implements Special:Block
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
25 * A special page that allows users with 'block' right to block users from
26 * editing pages and other actions
28 * @ingroup SpecialPage
30 class SpecialBlock
extends SpecialPage
{
32 /** The maximum number of edits a user can have and still be hidden
33 * TODO: config setting? */
34 const HIDEUSER_CONTRIBLIMIT
= 1000;
36 /** @var User user to be blocked, as passed either by parameter (url?wpTarget=Foo)
37 * or as subpage (Special:Block/Foo) */
40 /// @var Block::TYPE_ constant
44 protected $alreadyBlocked;
46 public function __construct() {
47 parent
::__construct( 'Block', 'block' );
50 public function execute( $par ) {
51 global $wgUser, $wgOut, $wgRequest;
53 # Can't block when the database is locked
55 $wgOut->readOnlyPage();
59 if( !$this->userCanExecute( $wgUser ) ) {
60 $wgOut->permissionRequired( 'block' );
64 # Extract variables from the request. Try not to get into a situation where we
65 # need to extract *every* variable from the form just for processing here, but
66 # there are legitimate uses for some variables
67 list( $this->target
, $this->type
) = self
::getTargetAndType( $par, $wgRequest );
68 if ( $this->target
instanceof User
) {
69 # Set the 'relevant user' in the skin, so it displays links like Contributions,
70 # User logs, UserRights, etc.
71 $wgUser->getSkin()->setRelevantUser( $this->target
);
74 # bug 15810: blocked admins should have limited access here
75 $status = self
::checkUnblockSelf( $this->target
);
76 if ( $status !== true ) {
77 throw new ErrorPageError( 'badaccess', $status );
80 $wgOut->setPageTitle( wfMsg( 'blockip-title' ) );
81 $wgOut->addModules( 'mediawiki.special', 'mediawiki.special.block' );
83 $fields = self
::getFormFields();
84 $this->alreadyBlocked
= $this->maybeAlterFormDefaults( $fields );
86 $form = new HTMLForm( $fields );
87 $form->setTitle( $this->getTitle() );
88 $form->setWrapperLegend( wfMsg( 'blockip-legend' ) );
89 $form->setSubmitCallback( array( __CLASS__
, 'processForm' ) );
91 $t = $this->alreadyBlocked
92 ?
wfMsg( 'ipb-change-block' )
93 : wfMsg( 'ipbsubmit' );
94 $form->setSubmitText( $t );
96 $this->doPreText( $form );
97 $this->doPostText( $form );
100 $wgOut->setPageTitle( wfMsg( 'blockipsuccesssub' ) );
101 $wgOut->addWikiMsg( 'blockipsuccesstext', $this->target
);
106 * Get the HTMLForm descriptor array for the block form
109 protected static function getFormFields(){
110 global $wgUser, $wgBlockAllowsUTEdit;
115 'label-message' => 'ipadressorusername',
117 'id' => 'mw-bi-target',
120 'validation-callback' => array( __CLASS__
, 'validateTargetField' ),
123 'type' => 'selectorother',
124 'label-message' => 'ipbexpiry',
127 'options' => self
::getSuggestedDurations(),
128 'other' => wfMsg( 'ipbother' ),
131 'type' => 'selectandother',
132 'label-message' => 'ipbreason',
133 'options-message' => 'ipbreason-dropdown',
135 'CreateAccount' => array(
137 'label-message' => 'ipbcreateaccount',
142 if( wfMsgForContent( 'ipboptions' ) == '-' ){
143 $a['Expiry']['type'] = 'text';
146 if( self
::canBlockEmail( $wgUser ) ) {
147 $a['DisableEmail'] = array(
149 'label-message' => 'ipbemailban',
153 if( $wgBlockAllowsUTEdit ){
154 $a['DisableUTEdit'] = array(
156 'label-message' => 'ipb-disableusertalk',
161 $a['AutoBlock'] = array(
163 'label-message' => 'ipbenableautoblock',
167 # Allow some users to hide name from block log, blocklist and listusers
168 if( $wgUser->isAllowed( 'hideuser' ) ) {
169 $a['HideUser'] = array(
171 'label-message' => 'ipbhidename',
172 'cssclass' => 'mw-block-hideuser',
176 # Watchlist their user page? (Only if user is logged in)
177 if( $wgUser->isLoggedIn() ) {
180 'label-message' => 'ipbwatchuser',
184 $a['HardBlock'] = array(
186 'label-message' => 'ipb-hardblock',
190 $a['AlreadyBlocked'] = array(
199 * If the user has already been blocked with similar settings, load that block
200 * and change the defaults for the form fields to match the existing settings.
201 * @param &$fields Array HTMLForm descriptor array
202 * @return Bool whether fields were altered (that is, whether the target is
205 protected function maybeAlterFormDefaults( &$fields ){
206 $fields['Target']['default'] = (string)$this->target
;
208 $block = Block
::newFromTargetAndType( $this->target
, $this->type
);
210 if( $block instanceof Block
&& !$block->mAuto
# The block exists and isn't an autoblock
211 && ( $this->type
!= Block
::TYPE_RANGE
# The block isn't a rangeblock
212 ||
$block->mAddress
== $this->target
) # or if it is, the range is what we're about to block
215 $fields['HardBlock']['default'] = !$block->mAnonOnly
;
216 $fields['CreateAccount']['default'] = $block->mCreateAccount
;
217 $fields['AutoBlock']['default'] = $block->mEnableAutoblock
;
218 if( isset( $fields['DisableEmail'] ) ){
219 $fields['DisableEmail']['default'] = $block->mBlockEmail
;
221 if( isset( $fields['HideUser'] ) ){
222 $fields['HideUser']['default'] = $block->mHideName
;
224 if( isset( $fields['DisableUTEdit'] ) ){
225 $fields['DisableUTEdit']['default'] = !$block->mAllowUsertalk
;
227 $fields['Reason']['default'] = $block->mReason
;
228 $fields['AlreadyBlocked']['default'] = true;
230 if( $block->mExpiry
== 'infinity' ) {
231 $fields['Expiry']['default'] = 'indefinite';
233 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822
, $block->mExpiry
);
242 * Add header elements like block log entries, etc.
243 * @param $form HTMLForm
246 protected function doPreText( HTMLForm
&$form ){
247 $form->addPreText( wfMsgExt( 'blockiptext', 'parse' ) );
249 $otherBlockMessages = array();
250 if( $this->target
!== null ) {
251 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
252 wfRunHooks( 'OtherBlockLogLink', array( &$otherBlockMessages, $this->target
) );
254 if( count( $otherBlockMessages ) ) {
255 $s = Html
::rawElement(
258 wfMsgExt( 'ipb-otherblocks-header', 'parseinline', count( $otherBlockMessages ) )
261 foreach( $otherBlockMessages as $link ) {
262 $list .= Html
::rawElement( 'li', array(), $link ) . "\n";
264 $s .= Html
::rawElement(
266 array( 'class' => 'mw-blockip-alreadyblocked' ),
269 $form->addPreText( $s );
273 # Username/IP is blocked already locally
274 if( $this->alreadyBlocked
) {
275 $form->addPreText( Html
::rawElement(
277 array( 'class' => 'mw-ipb-needreblock', ),
280 array( 'parseinline' ),
287 * Add footer elements to the form
288 * @param $form HTMLForm
291 protected function doPostText( HTMLForm
&$form ){
292 global $wgUser, $wgLang;
294 $skin = $wgUser->getSkin();
296 # Link to the user's contributions, if applicable
297 if( $this->target
instanceof User
){
298 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $this->target
->getName() );
299 $links[] = $skin->link(
301 wfMsgExt( 'ipb-blocklist-contribs', 'escape', $this->target
->getName() )
305 # Link to unblock the specified user, or to a blank unblock form
306 if( $this->target
instanceof User
) {
307 $message = wfMsgExt( 'ipb-unblock-addr', array( 'parseinline' ), $this->target
->getName() );
308 $list = SpecialPage
::getTitleFor( 'Unblock', $this->target
->getName() );
310 $message = wfMsgExt( 'ipb-unblock', array( 'parseinline' ) );
311 $list = SpecialPage
::getTitleFor( 'Unblock' );
313 $links[] = $skin->linkKnown( $list, $message, array() );
315 # Link to the block list
316 $links[] = $skin->linkKnown(
317 SpecialPage
::getTitleFor( 'BlockList' ),
318 wfMsg( 'ipb-blocklist' )
321 # Link to edit the block dropdown reasons, if applicable
322 if ( $wgUser->isAllowed( 'editinterface' ) ) {
323 $links[] = $skin->link(
324 Title
::makeTitle( NS_MEDIAWIKI
, 'Ipbreason-dropdown' ),
325 wfMsgHtml( 'ipb-edit-dropdown' ),
327 array( 'action' => 'edit' )
331 $form->addPostText( Html
::rawElement(
333 array( 'class' => 'mw-ipb-conveniencelinks' ),
334 $wgLang->pipeList( $links )
337 if( $this->target
instanceof User
){
338 # Get relevant extracts from the block and suppression logs, if possible
339 $userpage = $this->target
->getUserPage();
342 LogEventsList
::showLogExtract(
345 $userpage->getPrefixedText(),
349 'msgKey' => array( 'blocklog-showlog', $userpage->getText() ),
350 'showIfEmpty' => false
353 $form->addPostText( $out );
355 # Add suppression block entries if allowed
356 if( $wgUser->isAllowed( 'suppressionlog' ) ) {
357 LogEventsList
::showLogExtract(
360 $userpage->getPrefixedText(),
364 'conds' => array( 'log_action' => array( 'block', 'reblock', 'unblock' ) ),
365 'msgKey' => array( 'blocklog-showsuppresslog', $userpage->getText() ),
366 'showIfEmpty' => false
369 $form->addPostText( $out );
375 * Determine the target of the block, and the type of target
376 * TODO: should be in Block.php?
377 * @param $par String subpage parameter passed to setup, or data value from
379 * @param $request WebRequest optionally try and get data from a request too
382 public static function getTargetAndType( $par, WebRequest
$request = null ){
388 # The HTMLForm will check wpTarget first and only if it doesn't get
389 # a value use the default, which will be generated from the options
390 # below; so this has to have a higher precedence here than $par, or
391 # we could end up with different values in $this->target and the HTMLForm!
392 if( $request instanceof WebRequest
){
393 $target = $request->getText( 'wpTarget', null );
400 if( $request instanceof WebRequest
){
401 $target = $request->getText( 'ip', null );
406 if( $request instanceof WebRequest
){
407 $target = $request->getText( 'wpBlockAddress', null );
413 list( $target, $type ) = Block
::parseTarget( $target );
414 if( $type !== null ){
415 return array( $target, $type );
418 return array( null, null );
422 * HTMLForm field validation-callback for Target field.
426 public static function validateTargetField( $value, $alldata = null ) {
427 global $wgBlockCIDRLimit;
429 list( $target, $type ) = self
::getTargetAndType( $value );
431 if( $type == Block
::TYPE_USER
){
432 # TODO: why do we not have a User->exists() method?
433 if( !$target->getId() ){
434 return wfMessage( 'nosuchusershort', $target->getName() );
437 $status = self
::checkUnblockSelf( $target );
438 if ( $status !== true ) {
439 return wfMessage( 'badaccess', $status );
442 } elseif( $type == Block
::TYPE_RANGE
){
443 list( $ip, $range ) = explode( '/', $target, 2 );
445 if( ( IP
::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 )
446 ||
( IP
::isIPv6( $ip ) && $wgBlockCIDRLimit['IPV6'] == 128 ) )
448 # Range block effectively disabled
449 return wfMessage( 'range_block_disabled' );
452 if( ( IP
::isIPv4( $ip ) && $range > 32 )
453 ||
( IP
::isIPv6( $ip ) && $range > 128 ) )
456 return wfMessage( 'ip_range_invalid' );
459 if( IP
::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
460 return wfMessage( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
463 if( IP
::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
464 return wfMessage( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
467 } elseif( $type == Block
::TYPE_IP
){
471 return wfMessage( 'badipaddress' );
478 * Given the form data, actually implement a block
480 * @return Bool|String
482 public static function processForm( array $data ){
483 global $wgUser, $wgBlockAllowsUTEdit;
485 // Handled by field validator callback
486 // self::validateTargetField( $data['Target'] );
488 list( $target, $type ) = self
::getTargetAndType( $data['Target'] );
489 if( $type == Block
::TYPE_USER
){
491 $target = $user->getName();
492 $userId = $user->getId();
493 } elseif( $type == Block
::TYPE_RANGE
){
495 } elseif( $type == Block
::TYPE_IP
){
496 $target = $target->getName();
499 # This should have been caught in the form field validation
500 return array( 'badipaddress' );
503 if( ( strlen( $data['Expiry'] ) == 0) ||
( strlen( $data['Expiry'] ) > 50 )
504 ||
!Block
::parseExpiryInput( $data['Expiry'] ) )
506 return array( 'ipb_expiry_invalid' );
509 if( !$wgBlockAllowsUTEdit ){
510 $data['DisableUTEdit'] = true;
513 # If the user has done the form 'properly', they won't even have been given the
514 # option to suppress-block unless they have the 'hideuser' permission
515 if( !isset( $data['HideUser'] ) ){
516 $data['HideUser'] = false;
518 if( $data['HideUser'] ) {
519 if( !$wgUser->isAllowed('hideuser') ){
520 # this codepath is unreachable except by a malicious user spoofing forms,
521 # or by race conditions (user has oversight and sysop, loads block form,
522 # and is de-oversighted before submission); so need to fail completely
523 # rather than just silently disable hiding
524 return array( 'badaccess-group0' );
527 # Recheck params here...
528 if( $type != Block
::TYPE_USER
) {
529 $data['HideUser'] = false; # IP users should not be hidden
531 } elseif( !in_array( $data['Expiry'], array( 'infinite', 'infinity', 'indefinite' ) ) ) {
533 return array( 'ipb_expiry_temp' );
535 } elseif( $user->getEditCount() > self
::HIDEUSER_CONTRIBLIMIT
) {
536 # Typically, the user should have a handful of edits.
537 # Disallow hiding users with many edits for performance.
538 return array( 'ipb_hide_invalid' );
542 # Create block object. Note that for a user block, ipb_address is only for display purposes
543 # FIXME: Why do we need to pass fourteen optional parameters to do this!?!
545 $target, # IP address or User name
547 $wgUser->getId(), # Blocker id
548 $data['Reason'][0], # Reason string
549 wfTimestampNow(), # Block Timestamp
550 0, # Is this an autoblock (no)
551 Block
::parseExpiryInput( $data['Expiry'] ), # Expiry time
552 !$data['HardBlock'], # Block anon only
553 $data['CreateAccount'],
556 $data['DisableEmail'],
557 !$data['DisableUTEdit'] # *Allow* UTEdit
560 if( !wfRunHooks( 'BlockIp', array( &$block, &$wgUser ) ) ) {
561 return array( 'hookaborted' );
564 # Try to insert block. Is there a conflicting block?
565 if( !$block->insert() ) {
567 # Show form unless the user is already aware of this...
568 if( !$data['AlreadyBlocked'] ) {
569 return array( array( 'ipb_already_blocked', $data['Target'] ) );
571 # Otherwise, try to update the block...
574 # This returns direct blocks before autoblocks/rangeblocks, since we should
575 # be sure the user is blocked by now it should work for our purposes
576 $currentBlock = Block
::newFromDB( $target, $userId );
578 if( $block->equals( $currentBlock ) ) {
579 return array( 'ipb_already_blocked' );
582 # If the name was hidden and the blocking user cannot hide
583 # names, then don't allow any block changes...
584 if( $currentBlock->mHideName
&& !$wgUser->isAllowed( 'hideuser' ) ) {
585 return array( 'cant-see-hidden-user' );
588 $currentBlock->delete();
590 $logaction = 'reblock';
592 # Unset _deleted fields if requested
593 if( $currentBlock->mHideName
&& !$data['HideUser'] ) {
594 RevisionDeleteUser
::unsuppressUserName( $target, $userId );
597 # If hiding/unhiding a name, this should go in the private logs
598 if( (bool)$currentBlock->mHideName
){
599 $data['HideUser'] = true;
604 $logaction = 'block';
607 wfRunHooks( 'BlockIpComplete', array( $block, $wgUser ) );
609 # Set *_deleted fields if requested
610 if( $data['HideUser'] ) {
611 RevisionDeleteUser
::suppressUserName( $target, $userId );
614 # Can't watch a rangeblock
615 if( $type != Block
::TYPE_RANGE
&& $data['Watch'] ) {
616 $wgUser->addWatch( Title
::makeTitle( NS_USER
, $target ) );
619 # Block constructor sanitizes certain block options on insert
620 $data['BlockEmail'] = $block->mBlockEmail
;
621 $data['AutoBlock'] = $block->mEnableAutoblock
;
623 # Prepare log parameters
624 $logParams = array();
625 $logParams[] = $data['Expiry'];
626 $logParams[] = self
::blockLogFlags( $data, $type );
628 # Make log entry, if the name is hidden, put it in the oversight log
629 $log_type = $data['HideUser'] ?
'suppress' : 'block';
630 $log = new LogPage( $log_type );
633 Title
::makeTitle( NS_USER
, $target ),
643 * Get an array of suggested block durations from MediaWiki:Ipboptions
644 * FIXME: this uses a rather odd syntax for the options, should it be converted
645 * to the standard "**<duration>|<displayname>" format?
648 protected static function getSuggestedDurations(){
650 foreach( explode( ',', wfMsgForContent( 'ipboptions' ) ) as $option ) {
651 if( strpos( $option, ':' ) === false ) $option = "$option:$option";
652 list( $show, $value ) = explode( ':', $option );
653 $a[htmlspecialchars( $show )] = htmlspecialchars( $value );
659 * Can we do an email block?
660 * @param $user User: the sysop wanting to make a block
663 public static function canBlockEmail( $user ) {
664 global $wgEnableUserEmail, $wgSysopEmailBans;
665 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
669 * bug 15810: blocked admins should not be able to block/unblock
670 * others, and probably shouldn't be able to unblock themselves
672 * @param $user User|Int|String
674 public static function checkUnblockSelf( $user ) {
676 if ( is_int( $user ) ) {
677 $user = User
::newFromId( $user );
678 } elseif ( is_string( $user ) ) {
679 $user = User
::newFromName( $user );
681 if( $wgUser->isBlocked() ){
682 if( $user instanceof User
&& $user->getId() == $wgUser->getId() ) {
683 # User is trying to unblock themselves
684 if ( $wgUser->isAllowed( 'unblockself' ) ) {
687 return 'ipbnounblockself';
690 # User is trying to block/unblock someone else
699 * Return a comma-delimited list of "flags" to be passed to the log
700 * reader for this block, to provide more information in the logs
701 * @param $data Array from HTMLForm data
702 * @param $type Block::TYPE_ constant
705 protected static function blockLogFlags( array $data, $type ) {
706 global $wgBlockAllowsUTEdit;
709 # when blocking a user the option 'anononly' is not available/has no effect -> do not write this into log
710 if( !$data['HardBlock'] && $type != Block
::TYPE_USER
){
711 $flags[] = 'anononly';
714 if( $data['CreateAccount'] ){
715 $flags[] = 'nocreate';
718 # Same as anononly, this is not displayed when blocking an IP address
719 if( !$data['AutoBlock'] && $type != Block
::TYPE_IP
){
720 $flags[] = 'noautoblock';
723 if( $data['DisableEmail'] ){
724 $flags[] = 'noemail';
727 if( $data['DisableUTEdit'] && $wgBlockAllowsUTEdit ){
728 $flags[] = 'nousertalk';
731 if( $data['HideUser'] ){
732 $flags[] = 'hiddenname';
735 return implode( ',', $flags );
740 class IPBlockForm
extends SpecialBlock
{}