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 );
70 # T17810: blocked admins should have limited access here
71 $status = self
::checkUnblockSelf( $this->target
, $user );
72 if ( $status !== true ) {
73 throw new ErrorPageError( 'badaccess', $status );
78 * Handle some magic here
82 protected function setParameter( $par ) {
83 # Extract variables from the request. Try not to get into a situation where we
84 # need to extract *every* variable from the form just for processing here, but
85 # there are legitimate uses for some variables
86 $request = $this->getRequest();
87 list( $this->target
, $this->type
) = self
::getTargetAndType( $par, $request );
88 if ( $this->target
instanceof User
) {
89 # Set the 'relevant user' in the skin, so it displays links like Contributions,
90 # User logs, UserRights, etc.
91 $this->getSkin()->setRelevantUser( $this->target
);
94 list( $this->previousTarget
, /*...*/ ) =
95 Block
::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
96 $this->requestedHideUser
= $request->getBool( 'wpHideUser' );
100 * Customizes the HTMLForm a bit
102 * @param HTMLForm $form
104 protected function alterForm( HTMLForm
$form ) {
105 $form->setHeaderText( '' );
106 $form->setSubmitDestructive();
108 $msg = $this->alreadyBlocked ?
'ipb-change-block' : 'ipbsubmit';
109 $form->setSubmitTextMsg( $msg );
111 $this->addHelpLink( 'Help:Blocking users' );
113 # Don't need to do anything if the form has been posted
114 if ( !$this->getRequest()->wasPosted() && $this->preErrors
) {
115 $s = $form->formatErrors( $this->preErrors
);
117 $form->addHeaderText( Html
::rawElement(
119 [ 'class' => 'error' ],
126 protected function getDisplayFormat() {
131 * Get the HTMLForm descriptor array for the block form
134 protected function getFormFields() {
135 global $wgBlockAllowsUTEdit;
137 $user = $this->getUser();
139 $suggestedDurations = self
::getSuggestedDurations();
141 $conf = $this->getConfig();
142 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
143 $enablePartialBlocks = $conf->get( 'EnablePartialBlocks' );
151 'label-message' => 'ipaddressorusername',
152 'id' => 'mw-bi-target',
156 'validation-callback' => [ __CLASS__
, 'validateTargetField' ],
159 if ( $enablePartialBlocks ) {
160 $a['EditingRestriction'] = [
162 'label' => $this->msg( 'ipb-type-label' )->text(),
164 $this->msg( 'ipb-sitewide' )->text() => 'sitewide',
165 $this->msg( 'ipb-partial' )->text() => 'partial',
168 $a['PageRestrictions'] = [
169 'type' => 'titlesmultiselect',
170 'label' => $this->msg( 'ipb-pages-label' )->text(),
173 'cssclass' => 'mw-block-page-restrictions',
174 'showMissing' => false,
176 'autocomplete' => false
183 'label-message' => 'ipbexpiry',
185 'options' => $suggestedDurations,
186 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
190 'type' => 'selectandother',
191 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
192 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
193 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
194 'maxlength' => $oldCommentSchema ?
255 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
195 'maxlength-unit' => 'codepoints',
196 'label-message' => 'ipbreason',
197 'options-message' => 'ipbreason-dropdown',
200 $a['CreateAccount'] = [
202 'label-message' => 'ipbcreateaccount',
206 if ( self
::canBlockEmail( $user ) ) {
207 $a['DisableEmail'] = [
209 'label-message' => 'ipbemailban',
213 if ( $wgBlockAllowsUTEdit ) {
214 $a['DisableUTEdit'] = [
216 'label-message' => 'ipb-disableusertalk',
223 'label-message' => 'ipbenableautoblock',
227 # Allow some users to hide name from block log, blocklist and listusers
228 if ( $user->isAllowed( 'hideuser' ) ) {
231 'label-message' => 'ipbhidename',
232 'cssclass' => 'mw-block-hideuser',
236 # Watchlist their user page? (Only if user is logged in)
237 if ( $user->isLoggedIn() ) {
240 'label-message' => 'ipbwatchuser',
246 'label-message' => 'ipb-hardblock',
250 # This is basically a copy of the Target field, but the user can't change it, so we
251 # can see if the warnings we maybe showed to the user before still apply
252 $a['PreviousTarget'] = [
257 # We'll turn this into a checkbox if we need to
261 'label-message' => 'ipb-confirm',
262 'cssclass' => 'mw-block-confirm',
265 $this->maybeAlterFormDefaults( $a );
267 // Allow extensions to add more fields
268 Hooks
::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
274 * If the user has already been blocked with similar settings, load that block
275 * and change the defaults for the form fields to match the existing settings.
276 * @param array &$fields HTMLForm descriptor array
277 * @return bool Whether fields were altered (that is, whether the target is
280 protected function maybeAlterFormDefaults( &$fields ) {
281 # This will be overwritten by request data
282 $fields['Target']['default'] = (string)$this->target
;
284 if ( $this->target
) {
285 $status = self
::validateTarget( $this->target
, $this->getUser() );
286 if ( !$status->isOK() ) {
287 $errors = $status->getErrorsArray();
288 $this->preErrors
= array_merge( $this->preErrors
, $errors );
293 $fields['PreviousTarget']['default'] = (string)$this->target
;
295 $block = Block
::newFromTarget( $this->target
);
297 if ( $block instanceof Block
&& !$block->mAuto
# The block exists and isn't an autoblock
298 && ( $this->type
!= Block
::TYPE_RANGE
# The block isn't a rangeblock
299 ||
$block->getTarget() == $this->target
) # or if it is, the range is what we're about to block
301 $fields['HardBlock']['default'] = $block->isHardblock();
302 $fields['CreateAccount']['default'] = $block->prevents( 'createaccount' );
303 $fields['AutoBlock']['default'] = $block->isAutoblocking();
305 if ( isset( $fields['DisableEmail'] ) ) {
306 $fields['DisableEmail']['default'] = $block->prevents( 'sendemail' );
309 if ( isset( $fields['HideUser'] ) ) {
310 $fields['HideUser']['default'] = $block->mHideName
;
313 if ( isset( $fields['DisableUTEdit'] ) ) {
314 $fields['DisableUTEdit']['default'] = $block->prevents( 'editownusertalk' );
317 // If the username was hidden (ipb_deleted == 1), don't show the reason
318 // unless this user also has rights to hideuser: T37839
319 if ( !$block->mHideName ||
$this->getUser()->isAllowed( 'hideuser' ) ) {
320 $fields['Reason']['default'] = $block->mReason
;
322 $fields['Reason']['default'] = '';
325 if ( $this->getRequest()->wasPosted() ) {
326 # Ok, so we got a POST submission asking us to reblock a user. So show the
327 # confirm checkbox; the user will only see it if they haven't previously
328 $fields['Confirm']['type'] = 'check';
330 # We got a target, but it wasn't a POST request, so the user must have gone
331 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
332 # as long as they go ahead and block *that* user
333 $fields['Confirm']['default'] = 1;
336 if ( $block->mExpiry
== 'infinity' ) {
337 $fields['Expiry']['default'] = 'infinite';
339 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822
, $block->mExpiry
);
342 $this->alreadyBlocked
= true;
343 $this->preErrors
[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
346 # We always need confirmation to do HideUser
347 if ( $this->requestedHideUser
) {
348 $fields['Confirm']['type'] = 'check';
349 unset( $fields['Confirm']['default'] );
350 $this->preErrors
[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
353 # Or if the user is trying to block themselves
354 if ( (string)$this->target
=== $this->getUser()->getName() ) {
355 $fields['Confirm']['type'] = 'check';
356 unset( $fields['Confirm']['default'] );
357 $this->preErrors
[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
360 if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
361 if ( $block instanceof Block
&& !$block->isSitewide() ) {
362 $fields['EditingRestriction']['default'] = 'partial';
364 $fields['EditingRestriction']['default'] = 'sitewide';
367 if ( $block instanceof Block
) {
368 $pageRestrictions = [];
369 foreach ( $block->getRestrictions() as $restriction ) {
370 if ( $restriction->getType() !== 'page' ) {
374 $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
377 // Sort the restrictions so they are in alphabetical order.
378 sort( $pageRestrictions );
379 $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
385 * Add header elements like block log entries, etc.
388 protected function preText() {
389 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
391 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
392 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
394 $otherBlockMessages = [];
395 if ( $this->target
!== null ) {
396 $targetName = $this->target
;
397 if ( $this->target
instanceof User
) {
398 $targetName = $this->target
->getName();
400 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
401 Hooks
::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
403 if ( count( $otherBlockMessages ) ) {
404 $s = Html
::rawElement(
407 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
412 foreach ( $otherBlockMessages as $link ) {
413 $list .= Html
::rawElement( 'li', [], $link ) . "\n";
416 $s .= Html
::rawElement(
418 [ 'class' => 'mw-blockip-alreadyblocked' ],
430 * Add footer elements to the form
433 protected function postText() {
436 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
438 $linkRenderer = $this->getLinkRenderer();
439 # Link to the user's contributions, if applicable
440 if ( $this->target
instanceof User
) {
441 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $this->target
->getName() );
442 $links[] = $linkRenderer->makeLink(
444 $this->msg( 'ipb-blocklist-contribs', $this->target
->getName() )->text()
448 # Link to unblock the specified user, or to a blank unblock form
449 if ( $this->target
instanceof User
) {
450 $message = $this->msg(
452 wfEscapeWikiText( $this->target
->getName() )
454 $list = SpecialPage
::getTitleFor( 'Unblock', $this->target
->getName() );
456 $message = $this->msg( 'ipb-unblock' )->parse();
457 $list = SpecialPage
::getTitleFor( 'Unblock' );
459 $links[] = $linkRenderer->makeKnownLink(
461 new HtmlArmor( $message )
464 # Link to the block list
465 $links[] = $linkRenderer->makeKnownLink(
466 SpecialPage
::getTitleFor( 'BlockList' ),
467 $this->msg( 'ipb-blocklist' )->text()
470 $user = $this->getUser();
472 # Link to edit the block dropdown reasons, if applicable
473 if ( $user->isAllowed( 'editinterface' ) ) {
474 $links[] = $linkRenderer->makeKnownLink(
475 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
476 $this->msg( 'ipb-edit-dropdown' )->text(),
478 [ 'action' => 'edit' ]
482 $text = Html
::rawElement(
484 [ 'class' => 'mw-ipb-conveniencelinks' ],
485 $this->getLanguage()->pipeList( $links )
488 $userTitle = self
::getTargetUserTitle( $this->target
);
490 # Get relevant extracts from the block and suppression logs, if possible
493 LogEventsList
::showLogExtract(
500 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
501 'showIfEmpty' => false
506 # Add suppression block entries if allowed
507 if ( $user->isAllowed( 'suppressionlog' ) ) {
508 LogEventsList
::showLogExtract(
515 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
516 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
517 'showIfEmpty' => false
529 * Get a user page target for things like logs.
530 * This handles account and IP range targets.
531 * @param User|string $target
534 protected static function getTargetUserTitle( $target ) {
535 if ( $target instanceof User
) {
536 return $target->getUserPage();
537 } elseif ( IP
::isIPAddress( $target ) ) {
538 return Title
::makeTitleSafe( NS_USER
, $target );
545 * Determine the target of the block, and the type of target
546 * @todo Should be in Block.php?
547 * @param string $par Subpage parameter passed to setup, or data value from
549 * @param WebRequest|null $request Optionally try and get data from a request too
550 * @return array [ User|string|null, Block::TYPE_ constant|null ]
552 public static function getTargetAndType( $par, WebRequest
$request = null ) {
559 # The HTMLForm will check wpTarget first and only if it doesn't get
560 # a value use the default, which will be generated from the options
561 # below; so this has to have a higher precedence here than $par, or
562 # we could end up with different values in $this->target and the HTMLForm!
563 if ( $request instanceof WebRequest
) {
564 $target = $request->getText( 'wpTarget', null );
571 if ( $request instanceof WebRequest
) {
572 $target = $request->getText( 'ip', null );
577 if ( $request instanceof WebRequest
) {
578 $target = $request->getText( 'wpBlockAddress', null );
585 list( $target, $type ) = Block
::parseTarget( $target );
587 if ( $type !== null ) {
588 return [ $target, $type ];
592 return [ null, null ];
596 * HTMLForm field validation-callback for Target field.
598 * @param string $value
599 * @param array $alldata
600 * @param HTMLForm $form
603 public static function validateTargetField( $value, $alldata, $form ) {
604 $status = self
::validateTarget( $value, $form->getUser() );
605 if ( !$status->isOK() ) {
606 $errors = $status->getErrorsArray();
608 return $form->msg( ...$errors[0] );
615 * Validate a block target.
618 * @param string $value Block target to check
619 * @param User $user Performer of the block
622 public static function validateTarget( $value, User
$user ) {
623 global $wgBlockCIDRLimit;
625 /** @var User $target */
626 list( $target, $type ) = self
::getTargetAndType( $value );
627 $status = Status
::newGood( $target );
629 if ( $type == Block
::TYPE_USER
) {
630 if ( $target->isAnon() ) {
633 wfEscapeWikiText( $target->getName() )
637 $unblockStatus = self
::checkUnblockSelf( $target, $user );
638 if ( $unblockStatus !== true ) {
639 $status->fatal( 'badaccess', $unblockStatus );
641 } elseif ( $type == Block
::TYPE_RANGE
) {
642 list( $ip, $range ) = explode( '/', $target, 2 );
645 ( IP
::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
646 ( IP
::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
648 // Range block effectively disabled
649 $status->fatal( 'range_block_disabled' );
653 ( IP
::isIPv4( $ip ) && $range > 32 ) ||
654 ( IP
::isIPv6( $ip ) && $range > 128 )
657 $status->fatal( 'ip_range_invalid' );
660 if ( IP
::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
661 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
664 if ( IP
::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
665 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
667 } elseif ( $type == Block
::TYPE_IP
) {
670 $status->fatal( 'badipaddress' );
677 * Given the form data, actually implement a block. This is also called from ApiBlock.
680 * @param IContextSource $context
681 * @return bool|string
683 public static function processForm( array $data, IContextSource
$context ) {
684 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit;
686 $performer = $context->getUser();
687 $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
689 // Handled by field validator callback
690 // self::validateTargetField( $data['Target'] );
692 # This might have been a hidden field or a checkbox, so interesting data
694 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
696 /** @var User $target */
697 list( $target, $type ) = self
::getTargetAndType( $data['Target'] );
698 if ( $type == Block
::TYPE_USER
) {
700 $target = $user->getName();
701 $userId = $user->getId();
703 # Give admins a heads-up before they go and block themselves. Much messier
704 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
705 # permission anyway, although the code does allow for it.
706 # Note: Important to use $target instead of $data['Target']
707 # since both $data['PreviousTarget'] and $target are normalized
708 # but $data['target'] gets overridden by (non-normalized) request variable
709 # from previous request.
710 if ( $target === $performer->getName() &&
711 ( $data['PreviousTarget'] !== $target ||
!$data['Confirm'] )
713 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
715 } elseif ( $type == Block
::TYPE_RANGE
) {
718 } elseif ( $type == Block
::TYPE_IP
) {
720 $target = $target->getName();
723 # This should have been caught in the form field validation
724 return [ 'badipaddress' ];
727 $expiryTime = self
::parseExpiryInput( $data['Expiry'] );
730 // an expiry time is needed
731 ( strlen( $data['Expiry'] ) == 0 ) ||
732 // can't be a larger string as 50 (it should be a time format in any way)
733 ( strlen( $data['Expiry'] ) > 50 ) ||
734 // check, if the time could be parsed
737 return [ 'ipb_expiry_invalid' ];
740 // an expiry time should be in the future, not in the
741 // past (wouldn't make any sense) - bug T123069
742 if ( $expiryTime < wfTimestampNow() ) {
743 return [ 'ipb_expiry_old' ];
746 if ( !isset( $data['DisableEmail'] ) ) {
747 $data['DisableEmail'] = false;
750 # If the user has done the form 'properly', they won't even have been given the
751 # option to suppress-block unless they have the 'hideuser' permission
752 if ( !isset( $data['HideUser'] ) ) {
753 $data['HideUser'] = false;
756 if ( $data['HideUser'] ) {
757 if ( !$performer->isAllowed( 'hideuser' ) ) {
758 # this codepath is unreachable except by a malicious user spoofing forms,
759 # or by race conditions (user has hideuser and block rights, loads block form,
760 # and loses hideuser rights before submission); so need to fail completely
761 # rather than just silently disable hiding
762 return [ 'badaccess-group0' ];
765 # Recheck params here...
766 if ( $type != Block
::TYPE_USER
) {
767 $data['HideUser'] = false; # IP users should not be hidden
768 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
770 return [ 'ipb_expiry_temp' ];
771 } elseif ( $wgHideUserContribLimit !== false
772 && $user->getEditCount() > $wgHideUserContribLimit
774 # Typically, the user should have a handful of edits.
775 # Disallow hiding users with many edits for performance.
776 return [ [ 'ipb_hide_invalid',
777 Message
::numParam( $wgHideUserContribLimit ) ] ];
778 } elseif ( !$data['Confirm'] ) {
779 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
783 # Create block object.
784 $block = new Block();
785 $block->setTarget( $target );
786 $block->setBlocker( $performer );
787 $block->mReason
= $data['Reason'][0];
788 $block->mExpiry
= $expiryTime;
789 $block->prevents( 'createaccount', $data['CreateAccount'] );
790 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit ||
$data['DisableUTEdit'] ) );
791 $block->prevents( 'sendemail', $data['DisableEmail'] );
792 $block->isHardblock( $data['HardBlock'] );
793 $block->isAutoblocking( $data['AutoBlock'] );
794 $block->mHideName
= $data['HideUser'];
797 $enablePartialBlocks &&
798 isset( $data['EditingRestriction'] ) &&
799 $data['EditingRestriction'] === 'partial'
801 $block->isSitewide( false );
804 $reason = [ 'hookaborted' ];
805 if ( !Hooks
::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
810 if ( $enablePartialBlocks ) {
811 if ( !empty( $data['PageRestrictions'] ) ) {
812 $restrictions = array_map( function ( $text ) {
813 $title = Title
::newFromText( $text );
814 // Use the link cache since the title has already been loaded when
815 // the field was validated.
816 $restriction = new PageRestriction( 0, $title->getArticleId() );
817 $restriction->setTitle( $title );
819 }, explode( "\n", $data['PageRestrictions'] ) );
822 $block->setRestrictions( $restrictions );
826 # Try to insert block. Is there a conflicting block?
827 $status = $block->insert();
829 # Indicates whether the user is confirming the block and is aware of
830 # the conflict (did not change the block target in the meantime)
831 $blockNotConfirmed = !$data['Confirm'] ||
( array_key_exists( 'PreviousTarget', $data )
832 && $data['PreviousTarget'] !== $target );
834 # Special case for API - T34434
835 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
837 # Show form unless the user is already aware of this...
838 if ( $blockNotConfirmed ||
$reblockNotAllowed ) {
839 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
840 # Otherwise, try to update the block...
842 # This returns direct blocks before autoblocks/rangeblocks, since we should
843 # be sure the user is blocked by now it should work for our purposes
844 $currentBlock = Block
::newFromTarget( $target );
845 if ( $block->equals( $currentBlock ) ) {
846 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
848 # If the name was hidden and the blocking user cannot hide
849 # names, then don't allow any block changes...
850 if ( $currentBlock->mHideName
&& !$performer->isAllowed( 'hideuser' ) ) {
851 return [ 'cant-see-hidden-user' ];
854 $priorBlock = clone $currentBlock;
855 $currentBlock->isHardblock( $block->isHardblock() );
856 $currentBlock->prevents( 'createaccount', $block->prevents( 'createaccount' ) );
857 $currentBlock->mExpiry
= $block->mExpiry
;
858 $currentBlock->isAutoblocking( $block->isAutoblocking() );
859 $currentBlock->mHideName
= $block->mHideName
;
860 $currentBlock->prevents( 'sendemail', $block->prevents( 'sendemail' ) );
861 $currentBlock->prevents( 'editownusertalk', $block->prevents( 'editownusertalk' ) );
862 $currentBlock->mReason
= $block->mReason
;
864 if ( $enablePartialBlocks ) {
865 // Maintain the sitewide status. If partial blocks is not enabled,
866 // saving the block will result in a sitewide block.
867 $currentBlock->isSitewide( $block->isSitewide() );
869 // Set the block id of the restrictions.
870 $currentBlock->setRestrictions(
871 BlockRestriction
::setBlockId( $currentBlock->getId(), $restrictions )
875 $status = $currentBlock->update();
877 $logaction = 'reblock';
879 # Unset _deleted fields if requested
880 if ( $currentBlock->mHideName
&& !$data['HideUser'] ) {
881 RevisionDeleteUser
::unsuppressUserName( $target, $userId );
884 # If hiding/unhiding a name, this should go in the private logs
885 if ( (bool)$currentBlock->mHideName
) {
886 $data['HideUser'] = true;
890 $logaction = 'block';
893 Hooks
::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
895 # Set *_deleted fields if requested
896 if ( $data['HideUser'] ) {
897 RevisionDeleteUser
::suppressUserName( $target, $userId );
900 # Can't watch a rangeblock
901 if ( $type != Block
::TYPE_RANGE
&& $data['Watch'] ) {
902 WatchAction
::doWatch(
903 Title
::makeTitle( NS_USER
, $target ),
905 User
::IGNORE_USER_RIGHTS
909 # Block constructor sanitizes certain block options on insert
910 $data['BlockEmail'] = $block->prevents( 'sendemail' );
911 $data['AutoBlock'] = $block->isAutoblocking();
913 # Prepare log parameters
915 $logParams['5::duration'] = $data['Expiry'];
916 $logParams['6::flags'] = self
::blockLogFlags( $data, $type );
917 $logParams['sitewide'] = $block->isSitewide();
919 if ( $enablePartialBlocks && !empty( $data['PageRestrictions'] ) ) {
920 $logParams['7::restrictions'] = [
921 'pages' => explode( "\n", $data['PageRestrictions'] ),
925 # Make log entry, if the name is hidden, put it in the suppression log
926 $log_type = $data['HideUser'] ?
'suppress' : 'block';
927 $logEntry = new ManualLogEntry( $log_type, $logaction );
928 $logEntry->setTarget( Title
::makeTitle( NS_USER
, $target ) );
929 $logEntry->setComment( $data['Reason'][0] );
930 $logEntry->setPerformer( $performer );
931 $logEntry->setParameters( $logParams );
932 # Relate log ID to block IDs (T27763)
933 $blockIds = array_merge( [ $status['id'] ], $status['autoIds'] );
934 $logEntry->setRelations( [ 'ipb_id' => $blockIds ] );
935 $logId = $logEntry->insert();
937 if ( !empty( $data['Tags'] ) ) {
938 $logEntry->setTags( $data['Tags'] );
941 $logEntry->publish( $logId );
947 * Get an array of suggested block durations from MediaWiki:Ipboptions
948 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
949 * to the standard "**<duration>|<displayname>" format?
950 * @param Language|null $lang The language to get the durations in, or null to use
951 * the wiki's content language
952 * @param bool $includeOther Whether to include the 'other' option in the list of
956 public static function getSuggestedDurations( Language
$lang = null, $includeOther = true ) {
958 $msg = $lang === null
959 ?
wfMessage( 'ipboptions' )->inContentLanguage()->text()
960 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
966 foreach ( explode( ',', $msg ) as $option ) {
967 if ( strpos( $option, ':' ) === false ) {
968 $option = "$option:$option";
971 list( $show, $value ) = explode( ':', $option );
975 if ( $a && $includeOther ) {
976 // if options exist, add other to the end instead of the begining (which
977 // is what happens by default).
978 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
985 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
986 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
988 * @todo strtotime() only accepts English strings. This means the expiry input
989 * can only be specified in English.
990 * @see https://secure.php.net/manual/en/function.strtotime.php
992 * @param string $expiry Whatever was typed into the form
993 * @return string|bool Timestamp or 'infinity' or false on error.
995 public static function parseExpiryInput( $expiry ) {
996 if ( wfIsInfinity( $expiry ) ) {
1000 $expiry = strtotime( $expiry );
1002 if ( $expiry < 0 ||
$expiry === false ) {
1006 return wfTimestamp( TS_MW
, $expiry );
1010 * Can we do an email block?
1011 * @param User $user The sysop wanting to make a block
1014 public static function canBlockEmail( $user ) {
1015 global $wgEnableUserEmail, $wgSysopEmailBans;
1017 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1021 * T17810: blocked admins should not be able to block/unblock
1022 * others, and probably shouldn't be able to unblock themselves
1024 * @param User|int|string $user
1025 * @param User $performer User doing the request
1026 * @return bool|string True or error message key
1028 public static function checkUnblockSelf( $user, User
$performer ) {
1029 if ( is_int( $user ) ) {
1030 $user = User
::newFromId( $user );
1031 } elseif ( is_string( $user ) ) {
1032 $user = User
::newFromName( $user );
1035 if ( $performer->isBlocked() ) {
1036 if ( $user instanceof User
&& $user->getId() == $performer->getId() ) {
1037 # User is trying to unblock themselves
1038 if ( $performer->isAllowed( 'unblockself' ) ) {
1040 # User blocked themselves and is now trying to reverse it
1041 } elseif ( $performer->blockedBy() === $performer->getName() ) {
1044 return 'ipbnounblockself';
1047 # User is trying to block/unblock someone else
1048 return 'ipbblocked';
1056 * Return a comma-delimited list of "flags" to be passed to the log
1057 * reader for this block, to provide more information in the logs
1058 * @param array $data From HTMLForm data
1059 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
1062 protected static function blockLogFlags( array $data, $type ) {
1063 $config = RequestContext
::getMain()->getConfig();
1065 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1069 # when blocking a user the option 'anononly' is not available/has no effect
1070 # -> do not write this into log
1071 if ( !$data['HardBlock'] && $type != Block
::TYPE_USER
) {
1072 // For grepping: message block-log-flags-anononly
1073 $flags[] = 'anononly';
1076 if ( $data['CreateAccount'] ) {
1077 // For grepping: message block-log-flags-nocreate
1078 $flags[] = 'nocreate';
1081 # Same as anononly, this is not displayed when blocking an IP address
1082 if ( !$data['AutoBlock'] && $type == Block
::TYPE_USER
) {
1083 // For grepping: message block-log-flags-noautoblock
1084 $flags[] = 'noautoblock';
1087 if ( $data['DisableEmail'] ) {
1088 // For grepping: message block-log-flags-noemail
1089 $flags[] = 'noemail';
1092 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1093 // For grepping: message block-log-flags-nousertalk
1094 $flags[] = 'nousertalk';
1097 if ( $data['HideUser'] ) {
1098 // For grepping: message block-log-flags-hiddenname
1099 $flags[] = 'hiddenname';
1102 return implode( ',', $flags );
1106 * Process the form on POST submission.
1107 * @param array $data
1108 * @param HTMLForm|null $form
1109 * @return bool|array True for success, false for didn't-try, array of errors on failure
1111 public function onSubmit( array $data, HTMLForm
$form = null ) {
1112 return self
::processForm( $data, $form->getContext() );
1116 * Do something exciting on successful processing of the form, most likely to show a
1117 * confirmation message
1119 public function onSuccess() {
1120 $out = $this->getOutput();
1121 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1122 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target
) );
1126 * Return an array of subpages beginning with $search that this special page will accept.
1128 * @param string $search Prefix to search for
1129 * @param int $limit Maximum number of results to return (usually 10)
1130 * @param int $offset Number of results to skip (usually 0)
1131 * @return string[] Matching subpages
1133 public function prefixSearchSubpages( $search, $limit, $offset ) {
1134 $user = User
::newFromName( $search );
1136 // No prefix suggestion for invalid user
1139 // Autocomplete subpage as user list - public to allow caching
1140 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
1143 protected function getGroupName() {