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' => self
::getSuggestedDurations() === array() ?
'text' : '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( self
::canBlockEmail( $wgUser ) ) {
143 $a['DisableEmail'] = array(
145 'label-message' => 'ipbemailban',
149 if( $wgBlockAllowsUTEdit ){
150 $a['DisableUTEdit'] = array(
152 'label-message' => 'ipb-disableusertalk',
157 $a['AutoBlock'] = array(
159 'label-message' => 'ipbenableautoblock',
163 # Allow some users to hide name from block log, blocklist and listusers
164 if( $wgUser->isAllowed( 'hideuser' ) ) {
165 $a['HideUser'] = array(
167 'label-message' => 'ipbhidename',
168 'cssclass' => 'mw-block-hideuser',
172 # Watchlist their user page? (Only if user is logged in)
173 if( $wgUser->isLoggedIn() ) {
176 'label-message' => 'ipbwatchuser',
180 $a['HardBlock'] = array(
182 'label-message' => 'ipb-hardblock',
186 $a['AlreadyBlocked'] = array(
195 * If the user has already been blocked with similar settings, load that block
196 * and change the defaults for the form fields to match the existing settings.
197 * @param &$fields Array HTMLForm descriptor array
198 * @return Bool whether fields were altered (that is, whether the target is
201 protected function maybeAlterFormDefaults( &$fields ){
202 $fields['Target']['default'] = (string)$this->target
;
204 $block = Block
::newFromTargetAndType( $this->target
, $this->type
);
206 if( $block instanceof Block
&& !$block->mAuto
# The block exists and isn't an autoblock
207 && ( $this->type
!= Block
::TYPE_RANGE
# The block isn't a rangeblock
208 ||
$block->mAddress
== $this->target
) # or if it is, the range is what we're about to block
211 $fields['HardBlock']['default'] = !$block->mAnonOnly
;
212 $fields['CreateAccount']['default'] = $block->mCreateAccount
;
213 $fields['AutoBlock']['default'] = $block->mEnableAutoblock
;
214 if( isset( $fields['DisableEmail'] ) ){
215 $fields['DisableEmail']['default'] = $block->mBlockEmail
;
217 if( isset( $fields['HideUser'] ) ){
218 $fields['HideUser']['default'] = $block->mHideName
;
220 if( isset( $fields['DisableUTEdit'] ) ){
221 $fields['DisableUTEdit']['default'] = !$block->mAllowUsertalk
;
223 $fields['Reason']['default'] = $block->mReason
;
224 $fields['AlreadyBlocked']['default'] = true;
226 if( $block->mExpiry
== 'infinity' ) {
227 $fields['Expiry']['default'] = 'indefinite';
229 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822
, $block->mExpiry
);
238 * Add header elements like block log entries, etc.
239 * @param $form HTMLForm
242 protected function doPreText( HTMLForm
&$form ){
243 $form->addPreText( wfMsgExt( 'blockiptext', 'parse' ) );
245 $otherBlockMessages = array();
246 if( $this->target
!== null ) {
247 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
248 wfRunHooks( 'OtherBlockLogLink', array( &$otherBlockMessages, $this->target
) );
250 if( count( $otherBlockMessages ) ) {
251 $s = Html
::rawElement(
254 wfMsgExt( 'ipb-otherblocks-header', 'parseinline', count( $otherBlockMessages ) )
257 foreach( $otherBlockMessages as $link ) {
258 $list .= Html
::rawElement( 'li', array(), $link ) . "\n";
260 $s .= Html
::rawElement(
262 array( 'class' => 'mw-blockip-alreadyblocked' ),
265 $form->addPreText( $s );
269 # Username/IP is blocked already locally
270 if( $this->alreadyBlocked
) {
271 $form->addPreText( Html
::rawElement(
273 array( 'class' => 'mw-ipb-needreblock', ),
276 array( 'parseinline' ),
283 * Add footer elements to the form
284 * @param $form HTMLForm
287 protected function doPostText( HTMLForm
&$form ){
288 global $wgUser, $wgLang;
290 $skin = $wgUser->getSkin();
292 # Link to the user's contributions, if applicable
293 if( $this->target
instanceof User
){
294 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $this->target
->getName() );
295 $links[] = $skin->link(
297 wfMsgExt( 'ipb-blocklist-contribs', 'escape', $this->target
->getName() )
301 # Link to unblock the specified user, or to a blank unblock form
302 if( $this->target
instanceof User
) {
303 $message = wfMsgExt( 'ipb-unblock-addr', array( 'parseinline' ), $this->target
->getName() );
304 $list = SpecialPage
::getTitleFor( 'Unblock', $this->target
->getName() );
306 $message = wfMsgExt( 'ipb-unblock', array( 'parseinline' ) );
307 $list = SpecialPage
::getTitleFor( 'Unblock' );
309 $links[] = $skin->linkKnown( $list, $message, array() );
311 # Link to the block list
312 $links[] = $skin->linkKnown(
313 SpecialPage
::getTitleFor( 'BlockList' ),
314 wfMsg( 'ipb-blocklist' )
317 # Link to edit the block dropdown reasons, if applicable
318 if ( $wgUser->isAllowed( 'editinterface' ) ) {
319 $links[] = $skin->link(
320 Title
::makeTitle( NS_MEDIAWIKI
, 'Ipbreason-dropdown' ),
321 wfMsgHtml( 'ipb-edit-dropdown' ),
323 array( 'action' => 'edit' )
327 $form->addPostText( Html
::rawElement(
329 array( 'class' => 'mw-ipb-conveniencelinks' ),
330 $wgLang->pipeList( $links )
333 if( $this->target
instanceof User
){
334 # Get relevant extracts from the block and suppression logs, if possible
335 $userpage = $this->target
->getUserPage();
338 LogEventsList
::showLogExtract(
341 $userpage->getPrefixedText(),
345 'msgKey' => array( 'blocklog-showlog', $userpage->getText() ),
346 'showIfEmpty' => false
349 $form->addPostText( $out );
351 # Add suppression block entries if allowed
352 if( $wgUser->isAllowed( 'suppressionlog' ) ) {
353 LogEventsList
::showLogExtract(
356 $userpage->getPrefixedText(),
360 'conds' => array( 'log_action' => array( 'block', 'reblock', 'unblock' ) ),
361 'msgKey' => array( 'blocklog-showsuppresslog', $userpage->getText() ),
362 'showIfEmpty' => false
365 $form->addPostText( $out );
371 * Determine the target of the block, and the type of target
372 * TODO: should be in Block.php?
373 * @param $par String subpage parameter passed to setup, or data value from
375 * @param $request WebRequest optionally try and get data from a request too
378 public static function getTargetAndType( $par, WebRequest
$request = null ){
384 # The HTMLForm will check wpTarget first and only if it doesn't get
385 # a value use the default, which will be generated from the options
386 # below; so this has to have a higher precedence here than $par, or
387 # we could end up with different values in $this->target and the HTMLForm!
388 if( $request instanceof WebRequest
){
389 $target = $request->getText( 'wpTarget', null );
396 if( $request instanceof WebRequest
){
397 $target = $request->getText( 'ip', null );
402 if( $request instanceof WebRequest
){
403 $target = $request->getText( 'wpBlockAddress', null );
409 list( $target, $type ) = Block
::parseTarget( $target );
410 if( $type !== null ){
411 return array( $target, $type );
414 return array( null, null );
418 * HTMLForm field validation-callback for Target field.
422 public static function validateTargetField( $value, $alldata = null ) {
423 global $wgBlockCIDRLimit;
425 list( $target, $type ) = self
::getTargetAndType( $value );
427 if( $type == Block
::TYPE_USER
){
428 # TODO: why do we not have a User->exists() method?
429 if( !$target->getId() ){
430 return wfMessage( 'nosuchusershort', $target->getName() );
433 $status = self
::checkUnblockSelf( $target );
434 if ( $status !== true ) {
435 return wfMessage( 'badaccess', $status );
438 } elseif( $type == Block
::TYPE_RANGE
){
439 list( $ip, $range ) = explode( '/', $target, 2 );
441 if( ( IP
::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 )
442 ||
( IP
::isIPv6( $ip ) && $wgBlockCIDRLimit['IPV6'] == 128 ) )
444 # Range block effectively disabled
445 return wfMessage( 'range_block_disabled' );
448 if( ( IP
::isIPv4( $ip ) && $range > 32 )
449 ||
( IP
::isIPv6( $ip ) && $range > 128 ) )
452 return wfMessage( 'ip_range_invalid' );
455 if( IP
::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
456 return wfMessage( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
459 if( IP
::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
460 return wfMessage( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
463 } elseif( $type == Block
::TYPE_IP
){
467 return wfMessage( 'badipaddress' );
474 * Given the form data, actually implement a block
476 * @return Bool|String
478 public static function processForm( array $data ){
479 global $wgUser, $wgBlockAllowsUTEdit;
481 // Handled by field validator callback
482 // self::validateTargetField( $data['Target'] );
484 list( $target, $type ) = self
::getTargetAndType( $data['Target'] );
485 if( $type == Block
::TYPE_USER
){
487 $target = $user->getName();
488 $userId = $user->getId();
489 } elseif( $type == Block
::TYPE_RANGE
){
491 } elseif( $type == Block
::TYPE_IP
){
492 $target = $target->getName();
495 # This should have been caught in the form field validation
496 return array( 'badipaddress' );
499 if( ( strlen( $data['Expiry'] ) == 0) ||
( strlen( $data['Expiry'] ) > 50 )
500 ||
!self
::parseExpiryInput( $data['Expiry'] ) )
502 return array( 'ipb_expiry_invalid' );
505 if( !$wgBlockAllowsUTEdit ){
506 $data['DisableUTEdit'] = true;
509 # If the user has done the form 'properly', they won't even have been given the
510 # option to suppress-block unless they have the 'hideuser' permission
511 if( !isset( $data['HideUser'] ) ){
512 $data['HideUser'] = false;
514 if( $data['HideUser'] ) {
515 if( !$wgUser->isAllowed('hideuser') ){
516 # this codepath is unreachable except by a malicious user spoofing forms,
517 # or by race conditions (user has oversight and sysop, loads block form,
518 # and is de-oversighted before submission); so need to fail completely
519 # rather than just silently disable hiding
520 return array( 'badaccess-group0' );
523 # Recheck params here...
524 if( $type != Block
::TYPE_USER
) {
525 $data['HideUser'] = false; # IP users should not be hidden
527 } elseif( !in_array( $data['Expiry'], array( 'infinite', 'infinity', 'indefinite' ) ) ) {
529 return array( 'ipb_expiry_temp' );
531 } elseif( $user->getEditCount() > self
::HIDEUSER_CONTRIBLIMIT
) {
532 # Typically, the user should have a handful of edits.
533 # Disallow hiding users with many edits for performance.
534 return array( 'ipb_hide_invalid' );
538 # Create block object. Note that for a user block, ipb_address is only for display purposes
539 # FIXME: Why do we need to pass fourteen optional parameters to do this!?!
541 $target, # IP address or User name
543 $wgUser->getId(), # Blocker id
544 $data['Reason'][0], # Reason string
545 wfTimestampNow(), # Block Timestamp
546 0, # Is this an autoblock (no)
547 self
::parseExpiryInput( $data['Expiry'] ), # Expiry time
548 !$data['HardBlock'], # Block anon only
549 $data['CreateAccount'],
552 $data['DisableEmail'],
553 !$data['DisableUTEdit'] # *Allow* UTEdit
556 if( !wfRunHooks( 'BlockIp', array( &$block, &$wgUser ) ) ) {
557 return array( 'hookaborted' );
560 # Try to insert block. Is there a conflicting block?
561 if( !$block->insert() ) {
563 # Show form unless the user is already aware of this...
564 if( !$data['AlreadyBlocked'] ) {
565 return array( array( 'ipb_already_blocked', $data['Target'] ) );
567 # Otherwise, try to update the block...
570 # This returns direct blocks before autoblocks/rangeblocks, since we should
571 # be sure the user is blocked by now it should work for our purposes
572 $currentBlock = Block
::newFromDB( $target, $userId );
574 if( $block->equals( $currentBlock ) ) {
575 return array( 'ipb_already_blocked' );
578 # If the name was hidden and the blocking user cannot hide
579 # names, then don't allow any block changes...
580 if( $currentBlock->mHideName
&& !$wgUser->isAllowed( 'hideuser' ) ) {
581 return array( 'cant-see-hidden-user' );
584 $currentBlock->delete();
586 $logaction = 'reblock';
588 # Unset _deleted fields if requested
589 if( $currentBlock->mHideName
&& !$data['HideUser'] ) {
590 RevisionDeleteUser
::unsuppressUserName( $target, $userId );
593 # If hiding/unhiding a name, this should go in the private logs
594 if( (bool)$currentBlock->mHideName
){
595 $data['HideUser'] = true;
600 $logaction = 'block';
603 wfRunHooks( 'BlockIpComplete', array( $block, $wgUser ) );
605 # Set *_deleted fields if requested
606 if( $data['HideUser'] ) {
607 RevisionDeleteUser
::suppressUserName( $target, $userId );
610 # Can't watch a rangeblock
611 if( $type != Block
::TYPE_RANGE
&& $data['Watch'] ) {
612 $wgUser->addWatch( Title
::makeTitle( NS_USER
, $target ) );
615 # Block constructor sanitizes certain block options on insert
616 $data['BlockEmail'] = $block->mBlockEmail
;
617 $data['AutoBlock'] = $block->mEnableAutoblock
;
619 # Prepare log parameters
620 $logParams = array();
621 $logParams[] = $data['Expiry'];
622 $logParams[] = self
::blockLogFlags( $data, $type );
624 # Make log entry, if the name is hidden, put it in the oversight log
625 $log_type = $data['HideUser'] ?
'suppress' : 'block';
626 $log = new LogPage( $log_type );
629 Title
::makeTitle( NS_USER
, $target ),
639 * Get an array of suggested block durations from MediaWiki:Ipboptions
640 * FIXME: this uses a rather odd syntax for the options, should it be converted
641 * to the standard "**<duration>|<displayname>" format?
644 public static function getSuggestedDurations( $lang = null ){
646 $msg = $lang === null
647 ?
wfMessage( 'ipboptions' )->inContentLanguage()
648 : wfMessage( 'ipboptions' )->inLanguage( $lang );
654 foreach( explode( ',', $msg ) as $option ) {
655 if( strpos( $option, ':' ) === false ){
656 $option = "$option:$option";
658 list( $show, $value ) = explode( ':', $option );
659 $a[htmlspecialchars( $show )] = htmlspecialchars( $value );
665 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
666 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
667 * @param $expiry String: whatever was typed into the form
668 * @return String: timestamp or "infinity" string for the DB implementation
670 public static function parseExpiryInput( $expiry ) {
671 if ( $expiry == 'infinite' ||
$expiry == 'indefinite' ) {
672 $expiry = Block
::infinity();
674 $expiry = strtotime( $expiry );
675 if ( $expiry < 0 ||
$expiry === false ) {
678 $expiry = wfTimestamp( TS_MW
, $expiry );
684 * Can we do an email block?
685 * @param $user User: the sysop wanting to make a block
688 public static function canBlockEmail( $user ) {
689 global $wgEnableUserEmail, $wgSysopEmailBans;
690 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
694 * bug 15810: blocked admins should not be able to block/unblock
695 * others, and probably shouldn't be able to unblock themselves
697 * @param $user User|Int|String
699 public static function checkUnblockSelf( $user ) {
701 if ( is_int( $user ) ) {
702 $user = User
::newFromId( $user );
703 } elseif ( is_string( $user ) ) {
704 $user = User
::newFromName( $user );
706 if( $wgUser->isBlocked() ){
707 if( $user instanceof User
&& $user->getId() == $wgUser->getId() ) {
708 # User is trying to unblock themselves
709 if ( $wgUser->isAllowed( 'unblockself' ) ) {
712 return 'ipbnounblockself';
715 # User is trying to block/unblock someone else
724 * Return a comma-delimited list of "flags" to be passed to the log
725 * reader for this block, to provide more information in the logs
726 * @param $data Array from HTMLForm data
727 * @param $type Block::TYPE_ constant
730 protected static function blockLogFlags( array $data, $type ) {
731 global $wgBlockAllowsUTEdit;
734 # when blocking a user the option 'anononly' is not available/has no effect -> do not write this into log
735 if( !$data['HardBlock'] && $type != Block
::TYPE_USER
){
736 $flags[] = 'anononly';
739 if( $data['CreateAccount'] ){
740 $flags[] = 'nocreate';
743 # Same as anononly, this is not displayed when blocking an IP address
744 if( !$data['AutoBlock'] && $type != Block
::TYPE_IP
){
745 $flags[] = 'noautoblock';
748 if( $data['DisableEmail'] ){
749 $flags[] = 'noemail';
752 if( $data['DisableUTEdit'] && $wgBlockAllowsUTEdit ){
753 $flags[] = 'nousertalk';
756 if( $data['HideUser'] ){
757 $flags[] = 'hiddenname';
760 return implode( ',', $flags );
765 class IPBlockForm
extends SpecialBlock
{}