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
24 use MediaWiki\Block\BlockRestriction
;
25 use MediaWiki\Block\Restriction\PageRestriction
;
28 * A special page that allows users with 'block' right to block users from
29 * editing pages and other actions
31 * @ingroup SpecialPage
33 class SpecialBlock
extends FormSpecialPage
{
34 /** @var User|string|null User to be blocked, as passed either by parameter (url?wpTarget=Foo)
35 * or as subpage (Special:Block/Foo) */
38 /** @var int Block::TYPE_ constant */
41 /** @var User|string The previous block target */
42 protected $previousTarget;
44 /** @var bool Whether the previous submission of the form asked for HideUser */
45 protected $requestedHideUser;
48 protected $alreadyBlocked;
51 protected $preErrors = [];
53 public function __construct() {
54 parent
::__construct( 'Block', 'block' );
57 public function doesWrites() {
62 * Checks that the user can unblock themselves if they are trying to do so
65 * @throws ErrorPageError
67 protected function checkExecutePermissions( User
$user ) {
68 parent
::checkExecutePermissions( $user );
69 # T17810: blocked admins should have limited access here
70 $status = self
::checkUnblockSelf( $this->target
, $user );
71 if ( $status !== true ) {
72 throw new ErrorPageError( 'badaccess', $status );
77 * We allow certain special cases where user is blocked
81 public function requiresUnblock() {
86 * Handle some magic here
90 protected function setParameter( $par ) {
91 # Extract variables from the request. Try not to get into a situation where we
92 # need to extract *every* variable from the form just for processing here, but
93 # there are legitimate uses for some variables
94 $request = $this->getRequest();
95 list( $this->target
, $this->type
) = self
::getTargetAndType( $par, $request );
96 if ( $this->target
instanceof User
) {
97 # Set the 'relevant user' in the skin, so it displays links like Contributions,
98 # User logs, UserRights, etc.
99 $this->getSkin()->setRelevantUser( $this->target
);
102 list( $this->previousTarget
, /*...*/ ) =
103 Block
::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
104 $this->requestedHideUser
= $request->getBool( 'wpHideUser' );
108 * Customizes the HTMLForm a bit
110 * @param HTMLForm $form
112 protected function alterForm( HTMLForm
$form ) {
113 $form->setHeaderText( '' );
114 $form->setSubmitDestructive();
116 $msg = $this->alreadyBlocked ?
'ipb-change-block' : 'ipbsubmit';
117 $form->setSubmitTextMsg( $msg );
119 $this->addHelpLink( 'Help:Blocking users' );
121 # Don't need to do anything if the form has been posted
122 if ( !$this->getRequest()->wasPosted() && $this->preErrors
) {
123 $s = $form->formatErrors( $this->preErrors
);
125 $form->addHeaderText( Html
::rawElement(
127 [ 'class' => 'error' ],
134 protected function getDisplayFormat() {
139 * Get the HTMLForm descriptor array for the block form
142 protected function getFormFields() {
143 global $wgBlockAllowsUTEdit;
145 $user = $this->getUser();
147 $suggestedDurations = self
::getSuggestedDurations();
149 $conf = $this->getConfig();
150 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
151 $enablePartialBlocks = $conf->get( 'EnablePartialBlocks' );
159 'label-message' => 'ipaddressorusername',
160 'id' => 'mw-bi-target',
164 'validation-callback' => [ __CLASS__
, 'validateTargetField' ],
167 if ( $enablePartialBlocks ) {
168 $a['EditingRestriction'] = [
170 'label' => $this->msg( 'ipb-type-label' )->text(),
172 $this->msg( 'ipb-sitewide' )->text() => 'sitewide',
173 $this->msg( 'ipb-partial' )->text() => 'partial',
176 $a['PageRestrictions'] = [
177 'type' => 'titlesmultiselect',
178 'label' => $this->msg( 'ipb-pages-label' )->text(),
181 'cssclass' => 'mw-block-page-restrictions',
182 'showMissing' => false,
184 'autocomplete' => false
191 'label-message' => 'ipbexpiry',
193 'options' => $suggestedDurations,
194 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
198 'type' => 'selectandother',
199 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
200 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
201 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
202 'maxlength' => $oldCommentSchema ?
255 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
203 'maxlength-unit' => 'codepoints',
204 'label-message' => 'ipbreason',
205 'options-message' => 'ipbreason-dropdown',
208 $a['CreateAccount'] = [
210 'label-message' => 'ipbcreateaccount',
214 if ( self
::canBlockEmail( $user ) ) {
215 $a['DisableEmail'] = [
217 'label-message' => 'ipbemailban',
221 if ( $wgBlockAllowsUTEdit ) {
222 $a['DisableUTEdit'] = [
224 'label-message' => 'ipb-disableusertalk',
231 'label-message' => 'ipbenableautoblock',
235 # Allow some users to hide name from block log, blocklist and listusers
236 if ( $user->isAllowed( 'hideuser' ) ) {
239 'label-message' => 'ipbhidename',
240 'cssclass' => 'mw-block-hideuser',
244 # Watchlist their user page? (Only if user is logged in)
245 if ( $user->isLoggedIn() ) {
248 'label-message' => 'ipbwatchuser',
254 'label-message' => 'ipb-hardblock',
258 # This is basically a copy of the Target field, but the user can't change it, so we
259 # can see if the warnings we maybe showed to the user before still apply
260 $a['PreviousTarget'] = [
265 # We'll turn this into a checkbox if we need to
269 'label-message' => 'ipb-confirm',
270 'cssclass' => 'mw-block-confirm',
273 $this->maybeAlterFormDefaults( $a );
275 // Allow extensions to add more fields
276 Hooks
::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
282 * If the user has already been blocked with similar settings, load that block
283 * and change the defaults for the form fields to match the existing settings.
284 * @param array &$fields HTMLForm descriptor array
285 * @return bool Whether fields were altered (that is, whether the target is
288 protected function maybeAlterFormDefaults( &$fields ) {
289 # This will be overwritten by request data
290 $fields['Target']['default'] = (string)$this->target
;
292 if ( $this->target
) {
293 $status = self
::validateTarget( $this->target
, $this->getUser() );
294 if ( !$status->isOK() ) {
295 $errors = $status->getErrorsArray();
296 $this->preErrors
= array_merge( $this->preErrors
, $errors );
301 $fields['PreviousTarget']['default'] = (string)$this->target
;
303 $block = Block
::newFromTarget( $this->target
);
305 if ( $block instanceof Block
&& !$block->mAuto
# The block exists and isn't an autoblock
306 && ( $this->type
!= Block
::TYPE_RANGE
# The block isn't a rangeblock
307 ||
$block->getTarget() == $this->target
) # or if it is, the range is what we're about to block
309 $fields['HardBlock']['default'] = $block->isHardblock();
310 $fields['CreateAccount']['default'] = $block->prevents( 'createaccount' );
311 $fields['AutoBlock']['default'] = $block->isAutoblocking();
313 if ( isset( $fields['DisableEmail'] ) ) {
314 $fields['DisableEmail']['default'] = $block->prevents( 'sendemail' );
317 if ( isset( $fields['HideUser'] ) ) {
318 $fields['HideUser']['default'] = $block->mHideName
;
321 if ( isset( $fields['DisableUTEdit'] ) ) {
322 $fields['DisableUTEdit']['default'] = $block->prevents( 'editownusertalk' );
325 // If the username was hidden (ipb_deleted == 1), don't show the reason
326 // unless this user also has rights to hideuser: T37839
327 if ( !$block->mHideName ||
$this->getUser()->isAllowed( 'hideuser' ) ) {
328 $fields['Reason']['default'] = $block->mReason
;
330 $fields['Reason']['default'] = '';
333 if ( $this->getRequest()->wasPosted() ) {
334 # Ok, so we got a POST submission asking us to reblock a user. So show the
335 # confirm checkbox; the user will only see it if they haven't previously
336 $fields['Confirm']['type'] = 'check';
338 # We got a target, but it wasn't a POST request, so the user must have gone
339 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
340 # as long as they go ahead and block *that* user
341 $fields['Confirm']['default'] = 1;
344 if ( $block->mExpiry
== 'infinity' ) {
345 $fields['Expiry']['default'] = 'infinite';
347 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822
, $block->mExpiry
);
350 $this->alreadyBlocked
= true;
351 $this->preErrors
[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
354 # We always need confirmation to do HideUser
355 if ( $this->requestedHideUser
) {
356 $fields['Confirm']['type'] = 'check';
357 unset( $fields['Confirm']['default'] );
358 $this->preErrors
[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
361 # Or if the user is trying to block themselves
362 if ( (string)$this->target
=== $this->getUser()->getName() ) {
363 $fields['Confirm']['type'] = 'check';
364 unset( $fields['Confirm']['default'] );
365 $this->preErrors
[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
368 if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
369 if ( $block instanceof Block
&& !$block->isSitewide() ) {
370 $fields['EditingRestriction']['default'] = 'partial';
372 $fields['EditingRestriction']['default'] = 'sitewide';
375 if ( $block instanceof Block
) {
376 $pageRestrictions = [];
377 foreach ( $block->getRestrictions() as $restriction ) {
378 if ( $restriction->getType() !== 'page' ) {
382 $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
385 // Sort the restrictions so they are in alphabetical order.
386 sort( $pageRestrictions );
387 $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
393 * Add header elements like block log entries, etc.
396 protected function preText() {
397 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
399 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
400 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
402 $otherBlockMessages = [];
403 if ( $this->target
!== null ) {
404 $targetName = $this->target
;
405 if ( $this->target
instanceof User
) {
406 $targetName = $this->target
->getName();
408 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
409 Hooks
::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
411 if ( count( $otherBlockMessages ) ) {
412 $s = Html
::rawElement(
415 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
420 foreach ( $otherBlockMessages as $link ) {
421 $list .= Html
::rawElement( 'li', [], $link ) . "\n";
424 $s .= Html
::rawElement(
426 [ 'class' => 'mw-blockip-alreadyblocked' ],
438 * Add footer elements to the form
441 protected function postText() {
444 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
446 $linkRenderer = $this->getLinkRenderer();
447 # Link to the user's contributions, if applicable
448 if ( $this->target
instanceof User
) {
449 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $this->target
->getName() );
450 $links[] = $linkRenderer->makeLink(
452 $this->msg( 'ipb-blocklist-contribs', $this->target
->getName() )->text()
456 # Link to unblock the specified user, or to a blank unblock form
457 if ( $this->target
instanceof User
) {
458 $message = $this->msg(
460 wfEscapeWikiText( $this->target
->getName() )
462 $list = SpecialPage
::getTitleFor( 'Unblock', $this->target
->getName() );
464 $message = $this->msg( 'ipb-unblock' )->parse();
465 $list = SpecialPage
::getTitleFor( 'Unblock' );
467 $links[] = $linkRenderer->makeKnownLink(
469 new HtmlArmor( $message )
472 # Link to the block list
473 $links[] = $linkRenderer->makeKnownLink(
474 SpecialPage
::getTitleFor( 'BlockList' ),
475 $this->msg( 'ipb-blocklist' )->text()
478 $user = $this->getUser();
480 # Link to edit the block dropdown reasons, if applicable
481 if ( $user->isAllowed( 'editinterface' ) ) {
482 $links[] = $linkRenderer->makeKnownLink(
483 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
484 $this->msg( 'ipb-edit-dropdown' )->text(),
486 [ 'action' => 'edit' ]
490 $text = Html
::rawElement(
492 [ 'class' => 'mw-ipb-conveniencelinks' ],
493 $this->getLanguage()->pipeList( $links )
496 $userTitle = self
::getTargetUserTitle( $this->target
);
498 # Get relevant extracts from the block and suppression logs, if possible
501 LogEventsList
::showLogExtract(
508 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
509 'showIfEmpty' => false
514 # Add suppression block entries if allowed
515 if ( $user->isAllowed( 'suppressionlog' ) ) {
516 LogEventsList
::showLogExtract(
523 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
524 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
525 'showIfEmpty' => false
537 * Get a user page target for things like logs.
538 * This handles account and IP range targets.
539 * @param User|string $target
542 protected static function getTargetUserTitle( $target ) {
543 if ( $target instanceof User
) {
544 return $target->getUserPage();
545 } elseif ( IP
::isIPAddress( $target ) ) {
546 return Title
::makeTitleSafe( NS_USER
, $target );
553 * Determine the target of the block, and the type of target
554 * @todo Should be in Block.php?
555 * @param string $par Subpage parameter passed to setup, or data value from
557 * @param WebRequest|null $request Optionally try and get data from a request too
558 * @return array [ User|string|null, Block::TYPE_ constant|null ]
560 public static function getTargetAndType( $par, WebRequest
$request = null ) {
567 # The HTMLForm will check wpTarget first and only if it doesn't get
568 # a value use the default, which will be generated from the options
569 # below; so this has to have a higher precedence here than $par, or
570 # we could end up with different values in $this->target and the HTMLForm!
571 if ( $request instanceof WebRequest
) {
572 $target = $request->getText( 'wpTarget', null );
579 if ( $request instanceof WebRequest
) {
580 $target = $request->getText( 'ip', null );
585 if ( $request instanceof WebRequest
) {
586 $target = $request->getText( 'wpBlockAddress', null );
593 list( $target, $type ) = Block
::parseTarget( $target );
595 if ( $type !== null ) {
596 return [ $target, $type ];
600 return [ null, null ];
604 * HTMLForm field validation-callback for Target field.
606 * @param string $value
607 * @param array $alldata
608 * @param HTMLForm $form
611 public static function validateTargetField( $value, $alldata, $form ) {
612 $status = self
::validateTarget( $value, $form->getUser() );
613 if ( !$status->isOK() ) {
614 $errors = $status->getErrorsArray();
616 return $form->msg( ...$errors[0] );
623 * Validate a block target.
626 * @param string $value Block target to check
627 * @param User $user Performer of the block
630 public static function validateTarget( $value, User
$user ) {
631 global $wgBlockCIDRLimit;
633 /** @var User $target */
634 list( $target, $type ) = self
::getTargetAndType( $value );
635 $status = Status
::newGood( $target );
637 if ( $type == Block
::TYPE_USER
) {
638 if ( $target->isAnon() ) {
641 wfEscapeWikiText( $target->getName() )
645 $unblockStatus = self
::checkUnblockSelf( $target, $user );
646 if ( $unblockStatus !== true ) {
647 $status->fatal( 'badaccess', $unblockStatus );
649 } elseif ( $type == Block
::TYPE_RANGE
) {
650 list( $ip, $range ) = explode( '/', $target, 2 );
653 ( IP
::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
654 ( IP
::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
656 // Range block effectively disabled
657 $status->fatal( 'range_block_disabled' );
661 ( IP
::isIPv4( $ip ) && $range > 32 ) ||
662 ( IP
::isIPv6( $ip ) && $range > 128 )
665 $status->fatal( 'ip_range_invalid' );
668 if ( IP
::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
669 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
672 if ( IP
::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
673 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
675 } elseif ( $type == Block
::TYPE_IP
) {
678 $status->fatal( 'badipaddress' );
685 * Given the form data, actually implement a block. This is also called from ApiBlock.
688 * @param IContextSource $context
689 * @return bool|string
691 public static function processForm( array $data, IContextSource
$context ) {
692 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit;
694 $performer = $context->getUser();
695 $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
697 // Handled by field validator callback
698 // self::validateTargetField( $data['Target'] );
700 # This might have been a hidden field or a checkbox, so interesting data
702 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
704 /** @var User $target */
705 list( $target, $type ) = self
::getTargetAndType( $data['Target'] );
706 if ( $type == Block
::TYPE_USER
) {
708 $target = $user->getName();
709 $userId = $user->getId();
711 # Give admins a heads-up before they go and block themselves. Much messier
712 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
713 # permission anyway, although the code does allow for it.
714 # Note: Important to use $target instead of $data['Target']
715 # since both $data['PreviousTarget'] and $target are normalized
716 # but $data['target'] gets overridden by (non-normalized) request variable
717 # from previous request.
718 if ( $target === $performer->getName() &&
719 ( $data['PreviousTarget'] !== $target ||
!$data['Confirm'] )
721 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
723 } elseif ( $type == Block
::TYPE_RANGE
) {
726 } elseif ( $type == Block
::TYPE_IP
) {
728 $target = $target->getName();
731 # This should have been caught in the form field validation
732 return [ 'badipaddress' ];
735 $expiryTime = self
::parseExpiryInput( $data['Expiry'] );
738 // an expiry time is needed
739 ( strlen( $data['Expiry'] ) == 0 ) ||
740 // can't be a larger string as 50 (it should be a time format in any way)
741 ( strlen( $data['Expiry'] ) > 50 ) ||
742 // check, if the time could be parsed
745 return [ 'ipb_expiry_invalid' ];
748 // an expiry time should be in the future, not in the
749 // past (wouldn't make any sense) - bug T123069
750 if ( $expiryTime < wfTimestampNow() ) {
751 return [ 'ipb_expiry_old' ];
754 if ( !isset( $data['DisableEmail'] ) ) {
755 $data['DisableEmail'] = false;
758 # If the user has done the form 'properly', they won't even have been given the
759 # option to suppress-block unless they have the 'hideuser' permission
760 if ( !isset( $data['HideUser'] ) ) {
761 $data['HideUser'] = false;
764 if ( $data['HideUser'] ) {
765 if ( !$performer->isAllowed( 'hideuser' ) ) {
766 # this codepath is unreachable except by a malicious user spoofing forms,
767 # or by race conditions (user has hideuser and block rights, loads block form,
768 # and loses hideuser rights before submission); so need to fail completely
769 # rather than just silently disable hiding
770 return [ 'badaccess-group0' ];
773 # Recheck params here...
774 if ( $type != Block
::TYPE_USER
) {
775 $data['HideUser'] = false; # IP users should not be hidden
776 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
778 return [ 'ipb_expiry_temp' ];
779 } elseif ( $wgHideUserContribLimit !== false
780 && $user->getEditCount() > $wgHideUserContribLimit
782 # Typically, the user should have a handful of edits.
783 # Disallow hiding users with many edits for performance.
784 return [ [ 'ipb_hide_invalid',
785 Message
::numParam( $wgHideUserContribLimit ) ] ];
786 } elseif ( !$data['Confirm'] ) {
787 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
791 # Create block object.
792 $block = new Block();
793 $block->setTarget( $target );
794 $block->setBlocker( $performer );
795 $block->mReason
= $data['Reason'][0];
796 $block->mExpiry
= $expiryTime;
797 $block->prevents( 'createaccount', $data['CreateAccount'] );
798 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit ||
$data['DisableUTEdit'] ) );
799 $block->prevents( 'sendemail', $data['DisableEmail'] );
800 $block->isHardblock( $data['HardBlock'] );
801 $block->isAutoblocking( $data['AutoBlock'] );
802 $block->mHideName
= $data['HideUser'];
805 $enablePartialBlocks &&
806 isset( $data['EditingRestriction'] ) &&
807 $data['EditingRestriction'] === 'partial'
809 $block->isSitewide( false );
812 $reason = [ 'hookaborted' ];
813 if ( !Hooks
::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
818 if ( $enablePartialBlocks ) {
819 if ( !empty( $data['PageRestrictions'] ) ) {
820 $restrictions = array_map( function ( $text ) {
821 $title = Title
::newFromText( $text );
822 // Use the link cache since the title has already been loaded when
823 // the field was validated.
824 $restriction = new PageRestriction( 0, $title->getArticleId() );
825 $restriction->setTitle( $title );
827 }, explode( "\n", $data['PageRestrictions'] ) );
830 $block->setRestrictions( $restrictions );
834 # Try to insert block. Is there a conflicting block?
835 $status = $block->insert();
837 # Indicates whether the user is confirming the block and is aware of
838 # the conflict (did not change the block target in the meantime)
839 $blockNotConfirmed = !$data['Confirm'] ||
( array_key_exists( 'PreviousTarget', $data )
840 && $data['PreviousTarget'] !== $target );
842 # Special case for API - T34434
843 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
845 # Show form unless the user is already aware of this...
846 if ( $blockNotConfirmed ||
$reblockNotAllowed ) {
847 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
848 # Otherwise, try to update the block...
850 # This returns direct blocks before autoblocks/rangeblocks, since we should
851 # be sure the user is blocked by now it should work for our purposes
852 $currentBlock = Block
::newFromTarget( $target );
853 if ( $block->equals( $currentBlock ) ) {
854 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
856 # If the name was hidden and the blocking user cannot hide
857 # names, then don't allow any block changes...
858 if ( $currentBlock->mHideName
&& !$performer->isAllowed( 'hideuser' ) ) {
859 return [ 'cant-see-hidden-user' ];
862 $priorBlock = clone $currentBlock;
863 $currentBlock->isHardblock( $block->isHardblock() );
864 $currentBlock->prevents( 'createaccount', $block->prevents( 'createaccount' ) );
865 $currentBlock->mExpiry
= $block->mExpiry
;
866 $currentBlock->isAutoblocking( $block->isAutoblocking() );
867 $currentBlock->mHideName
= $block->mHideName
;
868 $currentBlock->prevents( 'sendemail', $block->prevents( 'sendemail' ) );
869 $currentBlock->prevents( 'editownusertalk', $block->prevents( 'editownusertalk' ) );
870 $currentBlock->mReason
= $block->mReason
;
872 if ( $enablePartialBlocks ) {
873 // Maintain the sitewide status. If partial blocks is not enabled,
874 // saving the block will result in a sitewide block.
875 $currentBlock->isSitewide( $block->isSitewide() );
877 // Set the block id of the restrictions.
878 $currentBlock->setRestrictions(
879 BlockRestriction
::setBlockId( $currentBlock->getId(), $restrictions )
883 $status = $currentBlock->update();
885 $logaction = 'reblock';
887 # Unset _deleted fields if requested
888 if ( $currentBlock->mHideName
&& !$data['HideUser'] ) {
889 RevisionDeleteUser
::unsuppressUserName( $target, $userId );
892 # If hiding/unhiding a name, this should go in the private logs
893 if ( (bool)$currentBlock->mHideName
) {
894 $data['HideUser'] = true;
898 $logaction = 'block';
901 Hooks
::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
903 # Set *_deleted fields if requested
904 if ( $data['HideUser'] ) {
905 RevisionDeleteUser
::suppressUserName( $target, $userId );
908 # Can't watch a rangeblock
909 if ( $type != Block
::TYPE_RANGE
&& $data['Watch'] ) {
910 WatchAction
::doWatch(
911 Title
::makeTitle( NS_USER
, $target ),
913 User
::IGNORE_USER_RIGHTS
917 # Block constructor sanitizes certain block options on insert
918 $data['BlockEmail'] = $block->prevents( 'sendemail' );
919 $data['AutoBlock'] = $block->isAutoblocking();
921 # Prepare log parameters
923 $logParams['5::duration'] = $data['Expiry'];
924 $logParams['6::flags'] = self
::blockLogFlags( $data, $type );
925 $logParams['sitewide'] = $block->isSitewide();
927 if ( $enablePartialBlocks && !empty( $data['PageRestrictions'] ) ) {
928 $logParams['7::restrictions'] = [
929 'pages' => explode( "\n", $data['PageRestrictions'] ),
933 # Make log entry, if the name is hidden, put it in the suppression log
934 $log_type = $data['HideUser'] ?
'suppress' : 'block';
935 $logEntry = new ManualLogEntry( $log_type, $logaction );
936 $logEntry->setTarget( Title
::makeTitle( NS_USER
, $target ) );
937 $logEntry->setComment( $data['Reason'][0] );
938 $logEntry->setPerformer( $performer );
939 $logEntry->setParameters( $logParams );
940 # Relate log ID to block IDs (T27763)
941 $blockIds = array_merge( [ $status['id'] ], $status['autoIds'] );
942 $logEntry->setRelations( [ 'ipb_id' => $blockIds ] );
943 $logId = $logEntry->insert();
945 if ( !empty( $data['Tags'] ) ) {
946 $logEntry->setTags( $data['Tags'] );
949 $logEntry->publish( $logId );
955 * Get an array of suggested block durations from MediaWiki:Ipboptions
956 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
957 * to the standard "**<duration>|<displayname>" format?
958 * @param Language|null $lang The language to get the durations in, or null to use
959 * the wiki's content language
960 * @param bool $includeOther Whether to include the 'other' option in the list of
964 public static function getSuggestedDurations( Language
$lang = null, $includeOther = true ) {
966 $msg = $lang === null
967 ?
wfMessage( 'ipboptions' )->inContentLanguage()->text()
968 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
974 foreach ( explode( ',', $msg ) as $option ) {
975 if ( strpos( $option, ':' ) === false ) {
976 $option = "$option:$option";
979 list( $show, $value ) = explode( ':', $option );
983 if ( $a && $includeOther ) {
984 // if options exist, add other to the end instead of the begining (which
985 // is what happens by default).
986 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
993 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
994 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
996 * @todo strtotime() only accepts English strings. This means the expiry input
997 * can only be specified in English.
998 * @see https://secure.php.net/manual/en/function.strtotime.php
1000 * @param string $expiry Whatever was typed into the form
1001 * @return string|bool Timestamp or 'infinity' or false on error.
1003 public static function parseExpiryInput( $expiry ) {
1004 if ( wfIsInfinity( $expiry ) ) {
1008 $expiry = strtotime( $expiry );
1010 if ( $expiry < 0 ||
$expiry === false ) {
1014 return wfTimestamp( TS_MW
, $expiry );
1018 * Can we do an email block?
1019 * @param User $user The sysop wanting to make a block
1022 public static function canBlockEmail( $user ) {
1023 global $wgEnableUserEmail, $wgSysopEmailBans;
1025 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1029 * T17810: blocked admins should not be able to block/unblock
1030 * others, and probably shouldn't be able to unblock themselves
1033 * Exception: Users can block the user who blocked them, to reduce
1034 * advantage of a malicious account blocking all admins (T150826)
1036 * @param User|int|string $user Target to block or unblock
1037 * @param User $performer User doing the request
1038 * @return bool|string True or error message key
1040 public static function checkUnblockSelf( $user, User
$performer ) {
1041 if ( is_int( $user ) ) {
1042 $user = User
::newFromId( $user );
1043 } elseif ( is_string( $user ) ) {
1044 $user = User
::newFromName( $user );
1046 if ( $performer->isBlocked() ) {
1047 if ( $user instanceof User
&& $user->getId() == $performer->getId() ) {
1048 # User is trying to unblock themselves
1049 if ( $performer->isAllowed( 'unblockself' ) ) {
1051 # User blocked themselves and is now trying to reverse it
1052 } elseif ( $performer->blockedBy() === $performer->getName() ) {
1055 return 'ipbnounblockself';
1058 $user instanceof User
&&
1059 $performer->getBlock() instanceof Block
&&
1060 $performer->getBlock()->getBy() &&
1061 $performer->getBlock()->getBy() === $user->getId()
1063 // Allow users to block the user that blocked them.
1064 // This is to prevent a situation where a malicious user
1065 // blocks all other users. This way, the non-malicious
1066 // user can block the malicious user back, resulting
1071 # User is trying to block/unblock someone else
1072 return 'ipbblocked';
1080 * Return a comma-delimited list of "flags" to be passed to the log
1081 * reader for this block, to provide more information in the logs
1082 * @param array $data From HTMLForm data
1083 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
1086 protected static function blockLogFlags( array $data, $type ) {
1087 $config = RequestContext
::getMain()->getConfig();
1089 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1093 # when blocking a user the option 'anononly' is not available/has no effect
1094 # -> do not write this into log
1095 if ( !$data['HardBlock'] && $type != Block
::TYPE_USER
) {
1096 // For grepping: message block-log-flags-anononly
1097 $flags[] = 'anononly';
1100 if ( $data['CreateAccount'] ) {
1101 // For grepping: message block-log-flags-nocreate
1102 $flags[] = 'nocreate';
1105 # Same as anononly, this is not displayed when blocking an IP address
1106 if ( !$data['AutoBlock'] && $type == Block
::TYPE_USER
) {
1107 // For grepping: message block-log-flags-noautoblock
1108 $flags[] = 'noautoblock';
1111 if ( $data['DisableEmail'] ) {
1112 // For grepping: message block-log-flags-noemail
1113 $flags[] = 'noemail';
1116 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1117 // For grepping: message block-log-flags-nousertalk
1118 $flags[] = 'nousertalk';
1121 if ( $data['HideUser'] ) {
1122 // For grepping: message block-log-flags-hiddenname
1123 $flags[] = 'hiddenname';
1126 return implode( ',', $flags );
1130 * Process the form on POST submission.
1131 * @param array $data
1132 * @param HTMLForm|null $form
1133 * @return bool|array True for success, false for didn't-try, array of errors on failure
1135 public function onSubmit( array $data, HTMLForm
$form = null ) {
1136 return self
::processForm( $data, $form->getContext() );
1140 * Do something exciting on successful processing of the form, most likely to show a
1141 * confirmation message
1143 public function onSuccess() {
1144 $out = $this->getOutput();
1145 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1146 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target
) );
1150 * Return an array of subpages beginning with $search that this special page will accept.
1152 * @param string $search Prefix to search for
1153 * @param int $limit Maximum number of results to return (usually 10)
1154 * @param int $offset Number of results to skip (usually 0)
1155 * @return string[] Matching subpages
1157 public function prefixSearchSubpages( $search, $limit, $offset ) {
1158 $user = User
::newFromName( $search );
1160 // No prefix suggestion for invalid user
1163 // Autocomplete subpage as user list - public to allow caching
1164 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
1167 protected function getGroupName() {