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->addHTML( wfMsgExt( 'blockipsuccesstext', array( 'parse' ), $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',
122 'type' => 'selectorother',
123 'label-message' => 'ipbexpiry',
126 'options' => self
::getSuggestedDurations(),
127 'other' => wfMsg( 'ipbother' ),
130 'type' => 'selectandother',
131 'label-message' => 'ipbreason',
132 'options-message' => 'ipbreason-dropdown',
134 'CreateAccount' => array(
136 'label-message' => 'ipbcreateaccount',
141 if( wfMsgForContent( 'ipboptions' ) == '-' ){
142 $a['Expiry']['type'] = 'text';
145 if( self
::canBlockEmail( $wgUser ) ) {
146 $a['DisableEmail'] = array(
148 'label-message' => 'ipbemailban',
152 if( $wgBlockAllowsUTEdit ){
153 $a['DisableUTEdit'] = array(
155 'label-message' => 'ipb-disableusertalk',
160 $a['AutoBlock'] = array(
162 'label-message' => 'ipbenableautoblock',
166 # Allow some users to hide name from block log, blocklist and listusers
167 if( $wgUser->isAllowed( 'hideuser' ) ) {
168 $a['HideUser'] = array(
170 'label-message' => 'ipbhidename',
171 'cssclass' => 'mw-block-hideuser',
175 # Watchlist their user page? (Only if user is logged in)
176 if( $wgUser->isLoggedIn() ) {
179 'label-message' => 'ipbwatchuser',
183 $a['HardBlock'] = array(
185 'label-message' => 'ipb-hardblock',
189 $a['AlreadyBlocked'] = array(
198 * If the user has already been blocked with similar settings, load that block
199 * and change the defaults for the form fields to match the existing settings.
200 * @param &$fields Array HTMLForm descriptor array
201 * @return Bool whether fields were altered (that is, whether the target is
204 protected function maybeAlterFormDefaults( &$fields ){
205 $fields['Target']['default'] = $this->target
;
207 $block = self
::getBlockFromTargetAndType( $this->target
, $this->type
);
209 if( $block instanceof Block
&& !$block->mAuto
# The block exists and isn't an autoblock
210 && ( $this->type
!= Block
::TYPE_RANGE
# The block isn't a rangeblock
211 ||
$block->mAddress
== $this->target
) # or if it is, the range is what we're about to block
214 $fields['HardBlock']['default'] = !$block->mAnonOnly
;
215 $fields['CreateAccount']['default'] = $block->mCreateAccount
;
216 $fields['AutoBlock']['default'] = $block->mEnableAutoblock
;
217 $fields['DisableEmail']['default'] = $block->mBlockEmail
;
218 $fields['HideUser']['default'] = $block->mHideName
;
219 $fields['DisableUTEdit']['default'] = !$block->mAllowUsertalk
;
220 $fields['Reason']['default'] = $block->mReason
;
221 $fields['AlreadyBlocked']['default'] = true;
223 if( $block->mExpiry
== 'infinity' ) {
224 $fields['Expiry']['default'] = 'indefinite';
226 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822
, $block->mExpiry
);
235 * Add header elements like block log entries, etc.
236 * @param $form HTMLForm
239 protected function doPreText( HTMLForm
&$form ){
240 $form->addPreText( wfMsgExt( 'blockiptext', 'parse' ) );
242 $otherBlockMessages = array();
243 if( $this->target
!== null ) {
244 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
245 wfRunHooks( 'OtherBlockLogLink', array( &$otherBlockMessages, $this->target
) );
247 if( count( $otherBlockMessages ) ) {
248 $s = Html
::rawElement(
251 wfMsgExt( 'ipb-otherblocks-header', 'parseinline', count( $otherBlockMessages ) )
254 foreach( $otherBlockMessages as $link ) {
255 $list .= Html
::rawElement( 'li', array(), $link ) . "\n";
257 $s .= Html
::rawElement(
259 array( 'class' => 'mw-blockip-alreadyblocked' ),
262 $form->addPreText( $s );
266 # Username/IP is blocked already locally
267 if( $this->alreadyBlocked
) {
268 $form->addPreText( Html
::rawElement(
270 array( 'class' => 'mw-ipb-needreblock', ),
273 array( 'parseinline' ),
280 * Add footer elements to the form
281 * @param $form HTMLForm
284 protected function doPostText( HTMLForm
&$form ){
285 global $wgUser, $wgLang;
287 $skin = $wgUser->getSkin();
289 # Link to the user's contributions, if applicable
290 if( $this->target
instanceof User
){
291 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $this->target
->getName() );
292 $links[] = $skin->link(
294 wfMsgExt( 'ipb-blocklist-contribs', 'escape', $this->target
->getName() )
298 # Link to unblock the specified user, or to a blank unblock form
299 $list = SpecialPage
::getTitleFor( 'Ipblocklist' );
300 $query = array( 'action' => 'unblock' );
301 if( $this->target
instanceof User
) {
302 $message = wfMsgExt( 'ipb-unblock-addr', array( 'parseinline' ), $this->target
->getName() );
303 $query['ip'] = $this->target
->getName();
305 $message = wfMsgExt( 'ipb-unblock', array( 'parseinline' ) );
307 $links[] = $skin->linkKnown( $list, $message, array(), $query );
309 # Link to the block list
310 $links[] = $skin->linkKnown(
311 SpecialPage
::getTitleFor( 'Ipblocklist' ),
312 wfMsg( 'ipb-blocklist' )
315 # Link to edit the block dropdown reasons, if applicable
316 if ( $wgUser->isAllowed( 'editinterface' ) ) {
317 $links[] = $skin->link(
318 Title
::makeTitle( NS_MEDIAWIKI
, 'Ipbreason-dropdown' ),
319 wfMsgHtml( 'ipb-edit-dropdown' ),
321 array( 'action' => 'edit' )
325 $form->addPostText( Html
::rawElement(
327 array( 'class' => 'mw-ipb-conveniencelinks' ),
328 $wgLang->pipeList( $links )
331 if( $this->target
instanceof User
){
332 # Get relevant extracts from the block and suppression logs, if possible
333 $userpage = $this->target
->getUserPage();
336 LogEventsList
::showLogExtract(
339 $userpage->getPrefixedText(),
343 'msgKey' => array( 'blocklog-showlog', $userpage->getText() ),
344 'showIfEmpty' => false
347 $form->addPostText( $out );
349 # Add suppression block entries if allowed
350 if( $wgUser->isAllowed( 'suppressionlog' ) ) {
351 LogEventsList
::showLogExtract(
354 $userpage->getPrefixedText(),
358 'conds' => array( 'log_action' => array( 'block', 'reblock', 'unblock' ) ),
359 'msgKey' => array( 'blocklog-showsuppresslog', $userpage->getText() ),
360 'showIfEmpty' => false
363 $form->addPostText( $out );
369 * Determine the target of the block, and the type of target
370 * TODO: should be in Block.php?
371 * @param $par String subpage parameter passed to setup, or data value from
373 * @param $request WebRequest optionally try and get data from a request too
376 public static function getTargetAndType( $par, WebRequest
$request = null ){
382 # The HTMLForm will check wpTarget first and only if it doesn't get
383 # a value use the default, which will be generated from the options
384 # below; so this has to have a higher precedence here than $par, or
385 # we could end up with different values in $this->target and the HTMLForm!
386 if( $request instanceof WebRequest
){
387 $target = $request->getText( 'wpTarget', null );
394 if( $request instanceof WebRequest
){
395 $target = $request->getText( 'ip', null );
400 if( $request instanceof WebRequest
){
401 $target = $request->getText( 'wpBlockAddress', null );
408 $userObj = User
::newFromName( $target );
409 if( $userObj instanceof User
){
410 return array( $userObj, Block
::TYPE_USER
);
411 } elseif( IP
::isValid( $target ) ){
412 # We can still create a User if it's an IP address, but we need to turn
413 # off validation checking (which would exclude IP addresses)
415 User
::newFromName( IP
::sanitizeIP( $target ), false ),
419 } elseif( IP
::isValidBlock( $target ) ){
420 # Can't create a User from an IP range
421 return array( Block
::normaliseRange( $target ), Block
::TYPE_RANGE
);
424 return array( null, null );
428 * Given a target and the target's type, get a block object if possible
429 * @param $target String|User
430 * @param $type Block::TYPE_ constant
432 * TODO: this probably belongs in Block.php when that mess is cleared up
434 public static function getBlockFromTargetAndType( $target, $type ){
435 if( $target instanceof User
){
436 if( $type == Block
::TYPE_IP
){
437 return Block
::newFromDB( $target->getName(), 0 );
438 } elseif( $type == Block
::TYPE_USER
) {
439 return Block
::newFromDB( '', $target->getId() );
441 # Should be unreachable;
444 } elseif( $type == Block
::TYPE_RANGE
){
445 return Block
::newFromDB( '', $target );
452 * Given the form data, actually implement a block
454 * @return Bool|String
456 public static function processForm( array $data ){
457 global $wgUser, $wgBlockAllowsUTEdit, $wgBlockCIDRLimit;
459 list( $target, $type ) = self
::getTargetAndType( $data['Target'] );
461 if( $type == Block
::TYPE_USER
){
462 # TODO: why do we not have a User->exists() method?
463 if( !$target->getId() ){
464 return array( array( 'nosuchusershort', $target->getName() ) );
467 $status = self
::checkUnblockSelf( $target );
468 if ( $status !== true ) {
469 return array( array( 'badaccess', $status ) );
473 $target = $user->getName();
474 $userId = $user->getId();
476 } elseif( $type == Block
::TYPE_RANGE
){
477 list( $ip, $range ) = explode( '/', $target, 2 );
479 if( ( IP
::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 )
480 ||
( IP
::isIPv6( $ip ) && $wgBlockCIDRLimit['IPV6'] == 128 ) )
482 # Range block effectively disabled
483 return array( 'range_block_disabled' );
486 if( ( IP
::isIPv4( $ip ) && $range > 32 )
487 ||
( IP
::isIPv6( $ip ) && $range > 128 ) )
490 return array( 'ip_range_invalid' );
493 if( IP
::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
494 return array( array( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] ) );
497 if( IP
::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
498 return array( array( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] ) );
503 } elseif( $type == Block
::TYPE_IP
){
505 $target = $target->getName();
509 return array( 'badipaddress' );
512 if( ( strlen( $data['Expiry'] ) == 0) ||
( strlen( $data['Expiry'] ) > 50 )
513 ||
!Block
::parseExpiryInput( $data['Expiry'] ) )
515 return array( 'ipb_expiry_invalid' );
518 if( !$wgBlockAllowsUTEdit ){
519 $data['PreventUTEdit'] = true;
522 # If the user has done the form 'properly', they won't even have been given the
523 # option to suppress-block unless they have the 'hideuser' permission
524 if( !isset( $data['HideUser'] ) ){
525 $data['HideUser'] = false;
527 if( $data['HideUser'] ) {
528 if( !$wgUser->isAllowed('hideuser') ){
529 # this codepath is unreachable except by a malicious user spoofing forms,
530 # or by race conditions (user has oversight and sysop, loads block form,
531 # and is de-oversighted before submission); so need to fail completely
532 # rather than just silently disable hiding
533 return array( 'badaccess-group0' );
536 # Recheck params here...
537 if( $type != Block
::TYPE_USER
) {
538 $data['HideUser'] = false; # IP users should not be hidden
540 } elseif( !in_array( $data['Expiry'], array( 'inifinite', 'infinity', 'indefinite' ) ) ) {
542 return array( 'ipb_expiry_temp' );
544 } elseif( $user->getEditCount() > self
::HIDEUSER_CONTRIBLIMIT
) {
545 # Typically, the user should have a handful of edits.
546 # Disallow hiding users with many edits for performance.
547 return array( 'ipb_hide_invalid' );
551 # Create block object. Note that for a user block, ipb_address is only for display purposes
552 # FIXME: Why do we need to pass fourteen optional parameters to do this!?!
554 $target, # IP address or User name
556 $wgUser->getId(), # Blocker id
557 $data['Reason'][0], # Reason string
558 wfTimestampNow(), # Block Timestamp
559 0, # Is this an autoblock (no)
560 Block
::parseExpiryInput( $data['Expiry'] ), # Expiry time
561 !$data['HardBlock'], # Block anon only
562 $data['CreateAccount'],
565 $data['DisableEmail'],
566 !$data['DisableUTEdit'] # *Allow* UTEdit
569 if( !wfRunHooks( 'BlockIp', array( &$block, &$wgUser ) ) ) {
570 return array( 'hookaborted' );
573 # Try to insert block. Is there a conflicting block?
574 if( !$block->insert() ) {
576 # Show form unless the user is already aware of this...
577 if( !$data['AlreadyBlocked'] ) {
578 return array( array( 'ipb_already_blocked', $data['Target'] ) );
580 # Otherwise, try to update the block...
583 # This returns direct blocks before autoblocks/rangeblocks, since we should
584 # be sure the user is blocked by now it should work for our purposes
585 $currentBlock = Block
::newFromDB( $target, $userId );
587 if( $block->equals( $currentBlock ) ) {
588 return array( 'ipb_already_blocked' );
591 # If the name was hidden and the blocking user cannot hide
592 # names, then don't allow any block changes...
593 if( $currentBlock->mHideName
&& !$wgUser->isAllowed( 'hideuser' ) ) {
594 return array( 'cant-see-hidden-user' );
597 $currentBlock->delete();
599 $logaction = 'reblock';
601 # Unset _deleted fields if requested
602 if( $currentBlock->mHideName
&& !$data['HideUser'] ) {
603 RevisionDeleteUser
::unsuppressUserName( $target, $userId );
606 # If hiding/unhiding a name, this should go in the private logs
607 if( (bool)$currentBlock->mHideName
){
608 $data['HideUser'] = true;
613 $logaction = 'block';
616 wfRunHooks( 'BlockIpComplete', array( $block, $wgUser ) );
618 # Set *_deleted fields if requested
619 if( $data['HideUser'] ) {
620 RevisionDeleteUser
::suppressUserName( $target, $userId );
623 # Can't watch a rangeblock
624 if( $type != Block
::TYPE_RANGE
&& $data['Watch'] ) {
625 $wgUser->addWatch( Title
::makeTitle( NS_USER
, $target ) );
628 # Block constructor sanitizes certain block options on insert
629 $data['BlockEmail'] = $block->mBlockEmail
;
630 $data['AutoBlock'] = $block->mEnableAutoblock
;
632 # Prepare log parameters
633 $logParams = array();
634 $logParams[] = $data['Expiry'];
635 $logParams[] = self
::blockLogFlags( $data, $type );
637 # Make log entry, if the name is hidden, put it in the oversight log
638 $log_type = $data['HideUser'] ?
'suppress' : 'block';
639 $log = new LogPage( $log_type );
642 Title
::makeTitle( NS_USER
, $target ),
652 * Get an array of suggested block durations from MediaWiki:Ipboptions
653 * FIXME: this uses a rather odd syntax for the options, should it be converted
654 * to the standard "**<duration>|<displayname>" format?
657 protected static function getSuggestedDurations(){
659 foreach( explode( ',', wfMsgForContent( 'ipboptions' ) ) as $option ) {
660 if( strpos( $option, ':' ) === false ) $option = "$option:$option";
661 list( $show, $value ) = explode( ':', $option );
662 $a[htmlspecialchars( $show )] = htmlspecialchars( $value );
668 * Can we do an email block?
669 * @param $user User: the sysop wanting to make a block
672 public static function canBlockEmail( $user ) {
673 global $wgEnableUserEmail, $wgSysopEmailBans;
674 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
678 * bug 15810: blocked admins should not be able to block/unblock
679 * others, and probably shouldn't be able to unblock themselves
681 * @param $user User|Int|String
683 public static function checkUnblockSelf( $user ) {
685 if ( is_int( $user ) ) {
686 $user = User
::newFromId( $user );
687 } elseif ( is_string( $user ) ) {
688 $user = User
::newFromName( $user );
690 if( $wgUser->isBlocked() ){
691 if( $user instanceof User
&& $user->getId() == $wgUser->getId() ) {
692 # User is trying to unblock themselves
693 if ( $wgUser->isAllowed( 'unblockself' ) ) {
696 return 'ipbnounblockself';
699 # User is trying to block/unblock someone else
708 * Return a comma-delimited list of "flags" to be passed to the log
709 * reader for this block, to provide more information in the logs
710 * @param $data Array from HTMLForm data
711 * @param $type Block::TYPE_ constant
714 protected static function blockLogFlags( array $data, $type ) {
715 global $wgBlockAllowsUTEdit;
718 # when blocking a user the option 'anononly' is not available/has no effect -> do not write this into log
719 if( !$data['HardBlock'] && $type != Block
::TYPE_USER
){
720 $flags[] = 'anononly';
723 if( $data['CreateAccount'] ){
724 $flags[] = 'nocreate';
727 # Same as anononly, this is not displayed when blocking an IP address
728 if( !$data['AutoBlock'] && $type != Block
::TYPE_IP
){
729 $flags[] = 'noautoblock';
732 if( $data['DisableEmail'] ){
733 $flags[] = 'noemail';
736 if( $data['DisableUTEdit'] && $wgBlockAllowsUTEdit ){
737 $flags[] = 'nousertalk';
740 if( $data['HideUser'] ){
741 $flags[] = 'hiddenname';
744 return implode( ',', $flags );
749 class IPBlockForm
extends SpecialBlock
{}