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 'id' => 'mw-bi-target',
163 'validation-callback' => [ __CLASS__
, 'validateTargetField' ],
164 'section' => 'target',
169 'label-message' => 'block-prevent-edit',
171 'section' => 'actions',
172 'disabled' => $enablePartialBlocks ?
false : true,
175 if ( $enablePartialBlocks ) {
176 $a['EditingRestriction'] = [
178 'cssclass' => 'mw-block-editing-restriction',
180 $this->msg( 'ipb-sitewide' )->text() => 'sitewide',
181 $this->msg( 'ipb-partial' )->text() => 'partial',
183 'section' => 'actions',
185 $a['PageRestrictions'] = [
186 'type' => 'titlesmultiselect',
187 'label' => $this->msg( 'ipb-pages-label' )->text(),
190 'cssclass' => 'mw-block-page-restrictions',
191 'showMissing' => false,
193 'autocomplete' => false
195 'section' => 'actions',
199 $a['CreateAccount'] = [
201 'label-message' => 'ipbcreateaccount',
203 'section' => 'actions',
206 if ( self
::canBlockEmail( $user ) ) {
207 $a['DisableEmail'] = [
209 'label-message' => 'ipbemailban',
210 'section' => 'actions',
214 if ( $wgBlockAllowsUTEdit ) {
215 $a['DisableUTEdit'] = [
217 'label-message' => 'ipb-disableusertalk',
219 'section' => 'actions',
226 'options' => $suggestedDurations,
227 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
228 'section' => 'expiry',
232 'type' => 'selectandother',
233 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
234 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
235 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
236 'maxlength' => $oldCommentSchema ?
255 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
237 'maxlength-unit' => 'codepoints',
238 'options-message' => 'ipbreason-dropdown',
239 'section' => 'reason',
244 'label-message' => 'ipbenableautoblock',
246 'section' => 'options',
249 # Allow some users to hide name from block log, blocklist and listusers
250 if ( $user->isAllowed( 'hideuser' ) ) {
253 'label-message' => 'ipbhidename',
254 'cssclass' => 'mw-block-hideuser',
255 'section' => 'options',
259 # Watchlist their user page? (Only if user is logged in)
260 if ( $user->isLoggedIn() ) {
263 'label-message' => 'ipbwatchuser',
264 'section' => 'options',
270 'label-message' => 'ipb-hardblock',
272 'section' => 'options',
275 # This is basically a copy of the Target field, but the user can't change it, so we
276 # can see if the warnings we maybe showed to the user before still apply
277 $a['PreviousTarget'] = [
282 # We'll turn this into a checkbox if we need to
286 'label-message' => 'ipb-confirm',
287 'cssclass' => 'mw-block-confirm',
290 $this->maybeAlterFormDefaults( $a );
292 // Allow extensions to add more fields
293 Hooks
::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
299 * If the user has already been blocked with similar settings, load that block
300 * and change the defaults for the form fields to match the existing settings.
301 * @param array &$fields HTMLForm descriptor array
302 * @return bool Whether fields were altered (that is, whether the target is
305 protected function maybeAlterFormDefaults( &$fields ) {
306 # This will be overwritten by request data
307 $fields['Target']['default'] = (string)$this->target
;
309 if ( $this->target
) {
310 $status = self
::validateTarget( $this->target
, $this->getUser() );
311 if ( !$status->isOK() ) {
312 $errors = $status->getErrorsArray();
313 $this->preErrors
= array_merge( $this->preErrors
, $errors );
318 $fields['PreviousTarget']['default'] = (string)$this->target
;
320 $block = Block
::newFromTarget( $this->target
);
322 if ( $block instanceof Block
&& !$block->mAuto
# The block exists and isn't an autoblock
323 && ( $this->type
!= Block
::TYPE_RANGE
# The block isn't a rangeblock
324 ||
$block->getTarget() == $this->target
) # or if it is, the range is what we're about to block
326 $fields['HardBlock']['default'] = $block->isHardblock();
327 $fields['CreateAccount']['default'] = $block->prevents( 'createaccount' );
328 $fields['AutoBlock']['default'] = $block->isAutoblocking();
330 if ( isset( $fields['DisableEmail'] ) ) {
331 $fields['DisableEmail']['default'] = $block->prevents( 'sendemail' );
334 if ( isset( $fields['HideUser'] ) ) {
335 $fields['HideUser']['default'] = $block->mHideName
;
338 if ( isset( $fields['DisableUTEdit'] ) ) {
339 $fields['DisableUTEdit']['default'] = $block->prevents( 'editownusertalk' );
342 // If the username was hidden (ipb_deleted == 1), don't show the reason
343 // unless this user also has rights to hideuser: T37839
344 if ( !$block->mHideName ||
$this->getUser()->isAllowed( 'hideuser' ) ) {
345 $fields['Reason']['default'] = $block->mReason
;
347 $fields['Reason']['default'] = '';
350 if ( $this->getRequest()->wasPosted() ) {
351 # Ok, so we got a POST submission asking us to reblock a user. So show the
352 # confirm checkbox; the user will only see it if they haven't previously
353 $fields['Confirm']['type'] = 'check';
355 # We got a target, but it wasn't a POST request, so the user must have gone
356 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
357 # as long as they go ahead and block *that* user
358 $fields['Confirm']['default'] = 1;
361 if ( $block->mExpiry
== 'infinity' ) {
362 $fields['Expiry']['default'] = 'infinite';
364 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822
, $block->mExpiry
);
367 $this->alreadyBlocked
= true;
368 $this->preErrors
[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
371 # We always need confirmation to do HideUser
372 if ( $this->requestedHideUser
) {
373 $fields['Confirm']['type'] = 'check';
374 unset( $fields['Confirm']['default'] );
375 $this->preErrors
[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
378 # Or if the user is trying to block themselves
379 if ( (string)$this->target
=== $this->getUser()->getName() ) {
380 $fields['Confirm']['type'] = 'check';
381 unset( $fields['Confirm']['default'] );
382 $this->preErrors
[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
385 if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
386 if ( $block instanceof Block
&& !$block->isSitewide() ) {
387 $fields['EditingRestriction']['default'] = 'partial';
389 $fields['EditingRestriction']['default'] = 'sitewide';
392 if ( $block instanceof Block
) {
393 $pageRestrictions = [];
394 foreach ( $block->getRestrictions() as $restriction ) {
395 if ( $restriction->getType() !== 'page' ) {
399 $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
402 if ( !$block->isSitewide() && empty( $pageRestrictions ) ) {
403 $fields['Editing']['default'] = false;
406 // Sort the restrictions so they are in alphabetical order.
407 sort( $pageRestrictions );
408 $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
414 * Add header elements like block log entries, etc.
417 protected function preText() {
418 $this->getOutput()->addModuleStyles( [
419 'mediawiki.widgets.TagMultiselectWidget.styles',
422 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
424 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
425 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
427 $otherBlockMessages = [];
428 if ( $this->target
!== null ) {
429 $targetName = $this->target
;
430 if ( $this->target
instanceof User
) {
431 $targetName = $this->target
->getName();
433 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
434 Hooks
::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
436 if ( count( $otherBlockMessages ) ) {
437 $s = Html
::rawElement(
440 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
445 foreach ( $otherBlockMessages as $link ) {
446 $list .= Html
::rawElement( 'li', [], $link ) . "\n";
449 $s .= Html
::rawElement(
451 [ 'class' => 'mw-blockip-alreadyblocked' ],
463 * Add footer elements to the form
466 protected function postText() {
469 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
471 $linkRenderer = $this->getLinkRenderer();
472 # Link to the user's contributions, if applicable
473 if ( $this->target
instanceof User
) {
474 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $this->target
->getName() );
475 $links[] = $linkRenderer->makeLink(
477 $this->msg( 'ipb-blocklist-contribs', $this->target
->getName() )->text()
481 # Link to unblock the specified user, or to a blank unblock form
482 if ( $this->target
instanceof User
) {
483 $message = $this->msg(
485 wfEscapeWikiText( $this->target
->getName() )
487 $list = SpecialPage
::getTitleFor( 'Unblock', $this->target
->getName() );
489 $message = $this->msg( 'ipb-unblock' )->parse();
490 $list = SpecialPage
::getTitleFor( 'Unblock' );
492 $links[] = $linkRenderer->makeKnownLink(
494 new HtmlArmor( $message )
497 # Link to the block list
498 $links[] = $linkRenderer->makeKnownLink(
499 SpecialPage
::getTitleFor( 'BlockList' ),
500 $this->msg( 'ipb-blocklist' )->text()
503 $user = $this->getUser();
505 # Link to edit the block dropdown reasons, if applicable
506 if ( $user->isAllowed( 'editinterface' ) ) {
507 $links[] = $linkRenderer->makeKnownLink(
508 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
509 $this->msg( 'ipb-edit-dropdown' )->text(),
511 [ 'action' => 'edit' ]
515 $text = Html
::rawElement(
517 [ 'class' => 'mw-ipb-conveniencelinks' ],
518 $this->getLanguage()->pipeList( $links )
521 $userTitle = self
::getTargetUserTitle( $this->target
);
523 # Get relevant extracts from the block and suppression logs, if possible
526 LogEventsList
::showLogExtract(
533 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
534 'showIfEmpty' => false
539 # Add suppression block entries if allowed
540 if ( $user->isAllowed( 'suppressionlog' ) ) {
541 LogEventsList
::showLogExtract(
548 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
549 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
550 'showIfEmpty' => false
562 * Get a user page target for things like logs.
563 * This handles account and IP range targets.
564 * @param User|string $target
567 protected static function getTargetUserTitle( $target ) {
568 if ( $target instanceof User
) {
569 return $target->getUserPage();
570 } elseif ( IP
::isIPAddress( $target ) ) {
571 return Title
::makeTitleSafe( NS_USER
, $target );
578 * Determine the target of the block, and the type of target
579 * @todo Should be in Block.php?
580 * @param string $par Subpage parameter passed to setup, or data value from
582 * @param WebRequest|null $request Optionally try and get data from a request too
583 * @return array [ User|string|null, Block::TYPE_ constant|null ]
585 public static function getTargetAndType( $par, WebRequest
$request = null ) {
592 # The HTMLForm will check wpTarget first and only if it doesn't get
593 # a value use the default, which will be generated from the options
594 # below; so this has to have a higher precedence here than $par, or
595 # we could end up with different values in $this->target and the HTMLForm!
596 if ( $request instanceof WebRequest
) {
597 $target = $request->getText( 'wpTarget', null );
604 if ( $request instanceof WebRequest
) {
605 $target = $request->getText( 'ip', null );
610 if ( $request instanceof WebRequest
) {
611 $target = $request->getText( 'wpBlockAddress', null );
618 list( $target, $type ) = Block
::parseTarget( $target );
620 if ( $type !== null ) {
621 return [ $target, $type ];
625 return [ null, null ];
629 * HTMLForm field validation-callback for Target field.
631 * @param string $value
632 * @param array $alldata
633 * @param HTMLForm $form
636 public static function validateTargetField( $value, $alldata, $form ) {
637 $status = self
::validateTarget( $value, $form->getUser() );
638 if ( !$status->isOK() ) {
639 $errors = $status->getErrorsArray();
641 return $form->msg( ...$errors[0] );
648 * Validate a block target.
651 * @param string $value Block target to check
652 * @param User $user Performer of the block
655 public static function validateTarget( $value, User
$user ) {
656 global $wgBlockCIDRLimit;
658 /** @var User $target */
659 list( $target, $type ) = self
::getTargetAndType( $value );
660 $status = Status
::newGood( $target );
662 if ( $type == Block
::TYPE_USER
) {
663 if ( $target->isAnon() ) {
666 wfEscapeWikiText( $target->getName() )
670 $unblockStatus = self
::checkUnblockSelf( $target, $user );
671 if ( $unblockStatus !== true ) {
672 $status->fatal( 'badaccess', $unblockStatus );
674 } elseif ( $type == Block
::TYPE_RANGE
) {
675 list( $ip, $range ) = explode( '/', $target, 2 );
678 ( IP
::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
679 ( IP
::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
681 // Range block effectively disabled
682 $status->fatal( 'range_block_disabled' );
686 ( IP
::isIPv4( $ip ) && $range > 32 ) ||
687 ( IP
::isIPv6( $ip ) && $range > 128 )
690 $status->fatal( 'ip_range_invalid' );
693 if ( IP
::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
694 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
697 if ( IP
::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
698 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
700 } elseif ( $type == Block
::TYPE_IP
) {
703 $status->fatal( 'badipaddress' );
710 * Given the form data, actually implement a block. This is also called from ApiBlock.
713 * @param IContextSource $context
714 * @return bool|string
716 public static function processForm( array $data, IContextSource
$context ) {
717 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit;
719 $performer = $context->getUser();
720 $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
722 // Handled by field validator callback
723 // self::validateTargetField( $data['Target'] );
725 # This might have been a hidden field or a checkbox, so interesting data
727 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
729 /** @var User $target */
730 list( $target, $type ) = self
::getTargetAndType( $data['Target'] );
731 if ( $type == Block
::TYPE_USER
) {
733 $target = $user->getName();
734 $userId = $user->getId();
736 # Give admins a heads-up before they go and block themselves. Much messier
737 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
738 # permission anyway, although the code does allow for it.
739 # Note: Important to use $target instead of $data['Target']
740 # since both $data['PreviousTarget'] and $target are normalized
741 # but $data['target'] gets overridden by (non-normalized) request variable
742 # from previous request.
743 if ( $target === $performer->getName() &&
744 ( $data['PreviousTarget'] !== $target ||
!$data['Confirm'] )
746 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
748 } elseif ( $type == Block
::TYPE_RANGE
) {
751 } elseif ( $type == Block
::TYPE_IP
) {
753 $target = $target->getName();
756 # This should have been caught in the form field validation
757 return [ 'badipaddress' ];
760 $expiryTime = self
::parseExpiryInput( $data['Expiry'] );
763 // an expiry time is needed
764 ( strlen( $data['Expiry'] ) == 0 ) ||
765 // can't be a larger string as 50 (it should be a time format in any way)
766 ( strlen( $data['Expiry'] ) > 50 ) ||
767 // check, if the time could be parsed
770 return [ 'ipb_expiry_invalid' ];
773 // an expiry time should be in the future, not in the
774 // past (wouldn't make any sense) - bug T123069
775 if ( $expiryTime < wfTimestampNow() ) {
776 return [ 'ipb_expiry_old' ];
779 if ( !isset( $data['DisableEmail'] ) ) {
780 $data['DisableEmail'] = false;
783 # If the user has done the form 'properly', they won't even have been given the
784 # option to suppress-block unless they have the 'hideuser' permission
785 if ( !isset( $data['HideUser'] ) ) {
786 $data['HideUser'] = false;
789 if ( $data['HideUser'] ) {
790 if ( !$performer->isAllowed( 'hideuser' ) ) {
791 # this codepath is unreachable except by a malicious user spoofing forms,
792 # or by race conditions (user has hideuser and block rights, loads block form,
793 # and loses hideuser rights before submission); so need to fail completely
794 # rather than just silently disable hiding
795 return [ 'badaccess-group0' ];
798 # Recheck params here...
799 if ( $type != Block
::TYPE_USER
) {
800 $data['HideUser'] = false; # IP users should not be hidden
801 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
803 return [ 'ipb_expiry_temp' ];
804 } elseif ( $wgHideUserContribLimit !== false
805 && $user->getEditCount() > $wgHideUserContribLimit
807 # Typically, the user should have a handful of edits.
808 # Disallow hiding users with many edits for performance.
809 return [ [ 'ipb_hide_invalid',
810 Message
::numParam( $wgHideUserContribLimit ) ] ];
811 } elseif ( !$data['Confirm'] ) {
812 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
816 # Create block object.
817 $block = new Block();
818 $block->setTarget( $target );
819 $block->setBlocker( $performer );
820 $block->mReason
= $data['Reason'][0];
821 $block->mExpiry
= $expiryTime;
822 $block->prevents( 'createaccount', $data['CreateAccount'] );
823 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit ||
$data['DisableUTEdit'] ) );
824 $block->prevents( 'sendemail', $data['DisableEmail'] );
825 $block->isHardblock( $data['HardBlock'] );
826 $block->isAutoblocking( $data['AutoBlock'] );
827 $block->mHideName
= $data['HideUser'];
830 $enablePartialBlocks &&
831 isset( $data['EditingRestriction'] ) &&
832 $data['EditingRestriction'] === 'partial'
834 $block->isSitewide( false );
837 $reason = [ 'hookaborted' ];
838 if ( !Hooks
::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
843 if ( $enablePartialBlocks ) {
844 if ( $data['PageRestrictions'] !== '' ) {
845 $restrictions = array_map( function ( $text ) {
846 $title = Title
::newFromText( $text );
847 // Use the link cache since the title has already been loaded when
848 // the field was validated.
849 $restriction = new PageRestriction( 0, $title->getArticleId() );
850 $restriction->setTitle( $title );
852 }, explode( "\n", $data['PageRestrictions'] ) );
855 $block->setRestrictions( $restrictions );
859 # Try to insert block. Is there a conflicting block?
860 $status = $block->insert();
862 # Indicates whether the user is confirming the block and is aware of
863 # the conflict (did not change the block target in the meantime)
864 $blockNotConfirmed = !$data['Confirm'] ||
( array_key_exists( 'PreviousTarget', $data )
865 && $data['PreviousTarget'] !== $target );
867 # Special case for API - T34434
868 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
870 # Show form unless the user is already aware of this...
871 if ( $blockNotConfirmed ||
$reblockNotAllowed ) {
872 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
873 # Otherwise, try to update the block...
875 # This returns direct blocks before autoblocks/rangeblocks, since we should
876 # be sure the user is blocked by now it should work for our purposes
877 $currentBlock = Block
::newFromTarget( $target );
878 if ( $block->equals( $currentBlock ) ) {
879 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
881 # If the name was hidden and the blocking user cannot hide
882 # names, then don't allow any block changes...
883 if ( $currentBlock->mHideName
&& !$performer->isAllowed( 'hideuser' ) ) {
884 return [ 'cant-see-hidden-user' ];
887 $priorBlock = clone $currentBlock;
888 $currentBlock->isHardblock( $block->isHardblock() );
889 $currentBlock->prevents( 'createaccount', $block->prevents( 'createaccount' ) );
890 $currentBlock->mExpiry
= $block->mExpiry
;
891 $currentBlock->isAutoblocking( $block->isAutoblocking() );
892 $currentBlock->mHideName
= $block->mHideName
;
893 $currentBlock->prevents( 'sendemail', $block->prevents( 'sendemail' ) );
894 $currentBlock->prevents( 'editownusertalk', $block->prevents( 'editownusertalk' ) );
895 $currentBlock->mReason
= $block->mReason
;
897 if ( $enablePartialBlocks ) {
898 // Maintain the sitewide status. If partial blocks is not enabled,
899 // saving the block will result in a sitewide block.
900 $currentBlock->isSitewide( $block->isSitewide() );
902 // Set the block id of the restrictions.
903 $currentBlock->setRestrictions(
904 BlockRestriction
::setBlockId( $currentBlock->getId(), $restrictions )
908 $status = $currentBlock->update();
909 // TODO handle failure
911 $logaction = 'reblock';
913 # Unset _deleted fields if requested
914 if ( $currentBlock->mHideName
&& !$data['HideUser'] ) {
915 RevisionDeleteUser
::unsuppressUserName( $target, $userId );
918 # If hiding/unhiding a name, this should go in the private logs
919 if ( (bool)$currentBlock->mHideName
) {
920 $data['HideUser'] = true;
923 $block = $currentBlock;
926 $logaction = 'block';
929 Hooks
::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
931 # Set *_deleted fields if requested
932 if ( $data['HideUser'] ) {
933 RevisionDeleteUser
::suppressUserName( $target, $userId );
936 # Can't watch a rangeblock
937 if ( $type != Block
::TYPE_RANGE
&& $data['Watch'] ) {
938 WatchAction
::doWatch(
939 Title
::makeTitle( NS_USER
, $target ),
941 User
::IGNORE_USER_RIGHTS
945 # Block constructor sanitizes certain block options on insert
946 $data['BlockEmail'] = $block->prevents( 'sendemail' );
947 $data['AutoBlock'] = $block->isAutoblocking();
949 # Prepare log parameters
951 $logParams['5::duration'] = $data['Expiry'];
952 $logParams['6::flags'] = self
::blockLogFlags( $data, $type );
953 $logParams['sitewide'] = $block->isSitewide();
955 if ( $enablePartialBlocks && $data['PageRestrictions'] !== '' ) {
956 $logParams['7::restrictions'] = [
957 'pages' => explode( "\n", $data['PageRestrictions'] ),
961 # Make log entry, if the name is hidden, put it in the suppression log
962 $log_type = $data['HideUser'] ?
'suppress' : 'block';
963 $logEntry = new ManualLogEntry( $log_type, $logaction );
964 $logEntry->setTarget( Title
::makeTitle( NS_USER
, $target ) );
965 $logEntry->setComment( $data['Reason'][0] );
966 $logEntry->setPerformer( $performer );
967 $logEntry->setParameters( $logParams );
968 # Relate log ID to block ID (T27763)
969 $logEntry->setRelations( [ 'ipb_id' => $block->getId() ] );
970 $logId = $logEntry->insert();
972 if ( !empty( $data['Tags'] ) ) {
973 $logEntry->setTags( $data['Tags'] );
976 $logEntry->publish( $logId );
982 * Get an array of suggested block durations from MediaWiki:Ipboptions
983 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
984 * to the standard "**<duration>|<displayname>" format?
985 * @param Language|null $lang The language to get the durations in, or null to use
986 * the wiki's content language
987 * @param bool $includeOther Whether to include the 'other' option in the list of
991 public static function getSuggestedDurations( Language
$lang = null, $includeOther = true ) {
993 $msg = $lang === null
994 ?
wfMessage( 'ipboptions' )->inContentLanguage()->text()
995 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
1001 foreach ( explode( ',', $msg ) as $option ) {
1002 if ( strpos( $option, ':' ) === false ) {
1003 $option = "$option:$option";
1006 list( $show, $value ) = explode( ':', $option );
1010 if ( $a && $includeOther ) {
1011 // if options exist, add other to the end instead of the begining (which
1012 // is what happens by default).
1013 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
1020 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1021 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
1023 * @todo strtotime() only accepts English strings. This means the expiry input
1024 * can only be specified in English.
1025 * @see https://secure.php.net/manual/en/function.strtotime.php
1027 * @param string $expiry Whatever was typed into the form
1028 * @return string|bool Timestamp or 'infinity' or false on error.
1030 public static function parseExpiryInput( $expiry ) {
1031 if ( wfIsInfinity( $expiry ) ) {
1035 $expiry = strtotime( $expiry );
1037 if ( $expiry < 0 ||
$expiry === false ) {
1041 return wfTimestamp( TS_MW
, $expiry );
1045 * Can we do an email block?
1046 * @param User $user The sysop wanting to make a block
1049 public static function canBlockEmail( $user ) {
1050 global $wgEnableUserEmail, $wgSysopEmailBans;
1052 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1056 * T17810: blocked admins should not be able to block/unblock
1057 * others, and probably shouldn't be able to unblock themselves
1060 * Exception: Users can block the user who blocked them, to reduce
1061 * advantage of a malicious account blocking all admins (T150826)
1063 * @param User|int|string|null $target Target to block or unblock; could be a User object,
1064 * or a user ID or username, or null when the target is not known yet (e.g. when
1065 * displaying Special:Block)
1066 * @param User $performer User doing the request
1067 * @return bool|string True or error message key
1069 public static function checkUnblockSelf( $target, User
$performer ) {
1070 if ( is_int( $target ) ) {
1071 $target = User
::newFromId( $target );
1072 } elseif ( is_string( $target ) ) {
1073 $target = User
::newFromName( $target );
1075 if ( $performer->isBlocked() ) {
1076 if ( $target instanceof User
&& $target->getId() == $performer->getId() ) {
1077 # User is trying to unblock themselves
1078 if ( $performer->isAllowed( 'unblockself' ) ) {
1080 # User blocked themselves and is now trying to reverse it
1081 } elseif ( $performer->blockedBy() === $performer->getName() ) {
1084 return 'ipbnounblockself';
1087 $target instanceof User
&&
1088 $performer->getBlock() instanceof Block
&&
1089 $performer->getBlock()->getBy() &&
1090 $performer->getBlock()->getBy() === $target->getId()
1092 // Allow users to block the user that blocked them.
1093 // This is to prevent a situation where a malicious user
1094 // blocks all other users. This way, the non-malicious
1095 // user can block the malicious user back, resulting
1100 # User is trying to block/unblock someone else
1101 return 'ipbblocked';
1109 * Return a comma-delimited list of "flags" to be passed to the log
1110 * reader for this block, to provide more information in the logs
1111 * @param array $data From HTMLForm data
1112 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
1115 protected static function blockLogFlags( array $data, $type ) {
1116 $config = RequestContext
::getMain()->getConfig();
1118 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1122 # when blocking a user the option 'anononly' is not available/has no effect
1123 # -> do not write this into log
1124 if ( !$data['HardBlock'] && $type != Block
::TYPE_USER
) {
1125 // For grepping: message block-log-flags-anononly
1126 $flags[] = 'anononly';
1129 if ( $data['CreateAccount'] ) {
1130 // For grepping: message block-log-flags-nocreate
1131 $flags[] = 'nocreate';
1134 # Same as anononly, this is not displayed when blocking an IP address
1135 if ( !$data['AutoBlock'] && $type == Block
::TYPE_USER
) {
1136 // For grepping: message block-log-flags-noautoblock
1137 $flags[] = 'noautoblock';
1140 if ( $data['DisableEmail'] ) {
1141 // For grepping: message block-log-flags-noemail
1142 $flags[] = 'noemail';
1145 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1146 // For grepping: message block-log-flags-nousertalk
1147 $flags[] = 'nousertalk';
1150 if ( $data['HideUser'] ) {
1151 // For grepping: message block-log-flags-hiddenname
1152 $flags[] = 'hiddenname';
1155 return implode( ',', $flags );
1159 * Process the form on POST submission.
1160 * @param array $data
1161 * @param HTMLForm|null $form
1162 * @return bool|array True for success, false for didn't-try, array of errors on failure
1164 public function onSubmit( array $data, HTMLForm
$form = null ) {
1165 // If "Editing" checkbox is unchecked, the block must be a partial block affecting
1166 // actions other than editing, and there must be no restrictions.
1167 if ( isset( $data['Editing'] ) && $data['Editing'] === false ) {
1168 $data['EditingRestriction'] = 'partial';
1169 $data['PageRestrictions'] = '';
1171 return self
::processForm( $data, $form->getContext() );
1175 * Do something exciting on successful processing of the form, most likely to show a
1176 * confirmation message
1178 public function onSuccess() {
1179 $out = $this->getOutput();
1180 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1181 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target
) );
1185 * Return an array of subpages beginning with $search that this special page will accept.
1187 * @param string $search Prefix to search for
1188 * @param int $limit Maximum number of results to return (usually 10)
1189 * @param int $offset Number of results to skip (usually 0)
1190 * @return string[] Matching subpages
1192 public function prefixSearchSubpages( $search, $limit, $offset ) {
1193 $user = User
::newFromName( $search );
1195 // No prefix suggestion for invalid user
1198 // Autocomplete subpage as user list - public to allow caching
1199 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
1202 protected function getGroupName() {