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 // Sort the restrictions so they are in alphabetical order.
403 sort( $pageRestrictions );
404 $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
410 * Add header elements like block log entries, etc.
413 protected function preText() {
414 $this->getOutput()->addModuleStyles( [
415 'mediawiki.widgets.TagMultiselectWidget.styles',
418 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
420 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
421 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
423 $otherBlockMessages = [];
424 if ( $this->target
!== null ) {
425 $targetName = $this->target
;
426 if ( $this->target
instanceof User
) {
427 $targetName = $this->target
->getName();
429 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
430 Hooks
::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
432 if ( count( $otherBlockMessages ) ) {
433 $s = Html
::rawElement(
436 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
441 foreach ( $otherBlockMessages as $link ) {
442 $list .= Html
::rawElement( 'li', [], $link ) . "\n";
445 $s .= Html
::rawElement(
447 [ 'class' => 'mw-blockip-alreadyblocked' ],
459 * Add footer elements to the form
462 protected function postText() {
465 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
467 $linkRenderer = $this->getLinkRenderer();
468 # Link to the user's contributions, if applicable
469 if ( $this->target
instanceof User
) {
470 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $this->target
->getName() );
471 $links[] = $linkRenderer->makeLink(
473 $this->msg( 'ipb-blocklist-contribs', $this->target
->getName() )->text()
477 # Link to unblock the specified user, or to a blank unblock form
478 if ( $this->target
instanceof User
) {
479 $message = $this->msg(
481 wfEscapeWikiText( $this->target
->getName() )
483 $list = SpecialPage
::getTitleFor( 'Unblock', $this->target
->getName() );
485 $message = $this->msg( 'ipb-unblock' )->parse();
486 $list = SpecialPage
::getTitleFor( 'Unblock' );
488 $links[] = $linkRenderer->makeKnownLink(
490 new HtmlArmor( $message )
493 # Link to the block list
494 $links[] = $linkRenderer->makeKnownLink(
495 SpecialPage
::getTitleFor( 'BlockList' ),
496 $this->msg( 'ipb-blocklist' )->text()
499 $user = $this->getUser();
501 # Link to edit the block dropdown reasons, if applicable
502 if ( $user->isAllowed( 'editinterface' ) ) {
503 $links[] = $linkRenderer->makeKnownLink(
504 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
505 $this->msg( 'ipb-edit-dropdown' )->text(),
507 [ 'action' => 'edit' ]
511 $text = Html
::rawElement(
513 [ 'class' => 'mw-ipb-conveniencelinks' ],
514 $this->getLanguage()->pipeList( $links )
517 $userTitle = self
::getTargetUserTitle( $this->target
);
519 # Get relevant extracts from the block and suppression logs, if possible
522 LogEventsList
::showLogExtract(
529 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
530 'showIfEmpty' => false
535 # Add suppression block entries if allowed
536 if ( $user->isAllowed( 'suppressionlog' ) ) {
537 LogEventsList
::showLogExtract(
544 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
545 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
546 'showIfEmpty' => false
558 * Get a user page target for things like logs.
559 * This handles account and IP range targets.
560 * @param User|string $target
563 protected static function getTargetUserTitle( $target ) {
564 if ( $target instanceof User
) {
565 return $target->getUserPage();
566 } elseif ( IP
::isIPAddress( $target ) ) {
567 return Title
::makeTitleSafe( NS_USER
, $target );
574 * Determine the target of the block, and the type of target
575 * @todo Should be in Block.php?
576 * @param string $par Subpage parameter passed to setup, or data value from
578 * @param WebRequest|null $request Optionally try and get data from a request too
579 * @return array [ User|string|null, Block::TYPE_ constant|null ]
581 public static function getTargetAndType( $par, WebRequest
$request = null ) {
588 # The HTMLForm will check wpTarget first and only if it doesn't get
589 # a value use the default, which will be generated from the options
590 # below; so this has to have a higher precedence here than $par, or
591 # we could end up with different values in $this->target and the HTMLForm!
592 if ( $request instanceof WebRequest
) {
593 $target = $request->getText( 'wpTarget', null );
600 if ( $request instanceof WebRequest
) {
601 $target = $request->getText( 'ip', null );
606 if ( $request instanceof WebRequest
) {
607 $target = $request->getText( 'wpBlockAddress', null );
614 list( $target, $type ) = Block
::parseTarget( $target );
616 if ( $type !== null ) {
617 return [ $target, $type ];
621 return [ null, null ];
625 * HTMLForm field validation-callback for Target field.
627 * @param string $value
628 * @param array $alldata
629 * @param HTMLForm $form
632 public static function validateTargetField( $value, $alldata, $form ) {
633 $status = self
::validateTarget( $value, $form->getUser() );
634 if ( !$status->isOK() ) {
635 $errors = $status->getErrorsArray();
637 return $form->msg( ...$errors[0] );
644 * Validate a block target.
647 * @param string $value Block target to check
648 * @param User $user Performer of the block
651 public static function validateTarget( $value, User
$user ) {
652 global $wgBlockCIDRLimit;
654 /** @var User $target */
655 list( $target, $type ) = self
::getTargetAndType( $value );
656 $status = Status
::newGood( $target );
658 if ( $type == Block
::TYPE_USER
) {
659 if ( $target->isAnon() ) {
662 wfEscapeWikiText( $target->getName() )
666 $unblockStatus = self
::checkUnblockSelf( $target, $user );
667 if ( $unblockStatus !== true ) {
668 $status->fatal( 'badaccess', $unblockStatus );
670 } elseif ( $type == Block
::TYPE_RANGE
) {
671 list( $ip, $range ) = explode( '/', $target, 2 );
674 ( IP
::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
675 ( IP
::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
677 // Range block effectively disabled
678 $status->fatal( 'range_block_disabled' );
682 ( IP
::isIPv4( $ip ) && $range > 32 ) ||
683 ( IP
::isIPv6( $ip ) && $range > 128 )
686 $status->fatal( 'ip_range_invalid' );
689 if ( IP
::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
690 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
693 if ( IP
::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
694 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
696 } elseif ( $type == Block
::TYPE_IP
) {
699 $status->fatal( 'badipaddress' );
706 * Given the form data, actually implement a block. This is also called from ApiBlock.
709 * @param IContextSource $context
710 * @return bool|string
712 public static function processForm( array $data, IContextSource
$context ) {
713 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit;
715 $performer = $context->getUser();
716 $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
718 // Handled by field validator callback
719 // self::validateTargetField( $data['Target'] );
721 # This might have been a hidden field or a checkbox, so interesting data
723 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
725 /** @var User $target */
726 list( $target, $type ) = self
::getTargetAndType( $data['Target'] );
727 if ( $type == Block
::TYPE_USER
) {
729 $target = $user->getName();
730 $userId = $user->getId();
732 # Give admins a heads-up before they go and block themselves. Much messier
733 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
734 # permission anyway, although the code does allow for it.
735 # Note: Important to use $target instead of $data['Target']
736 # since both $data['PreviousTarget'] and $target are normalized
737 # but $data['target'] gets overridden by (non-normalized) request variable
738 # from previous request.
739 if ( $target === $performer->getName() &&
740 ( $data['PreviousTarget'] !== $target ||
!$data['Confirm'] )
742 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
744 } elseif ( $type == Block
::TYPE_RANGE
) {
747 } elseif ( $type == Block
::TYPE_IP
) {
749 $target = $target->getName();
752 # This should have been caught in the form field validation
753 return [ 'badipaddress' ];
756 $expiryTime = self
::parseExpiryInput( $data['Expiry'] );
759 // an expiry time is needed
760 ( strlen( $data['Expiry'] ) == 0 ) ||
761 // can't be a larger string as 50 (it should be a time format in any way)
762 ( strlen( $data['Expiry'] ) > 50 ) ||
763 // check, if the time could be parsed
766 return [ 'ipb_expiry_invalid' ];
769 // an expiry time should be in the future, not in the
770 // past (wouldn't make any sense) - bug T123069
771 if ( $expiryTime < wfTimestampNow() ) {
772 return [ 'ipb_expiry_old' ];
775 if ( !isset( $data['DisableEmail'] ) ) {
776 $data['DisableEmail'] = false;
779 # If the user has done the form 'properly', they won't even have been given the
780 # option to suppress-block unless they have the 'hideuser' permission
781 if ( !isset( $data['HideUser'] ) ) {
782 $data['HideUser'] = false;
785 if ( $data['HideUser'] ) {
786 if ( !$performer->isAllowed( 'hideuser' ) ) {
787 # this codepath is unreachable except by a malicious user spoofing forms,
788 # or by race conditions (user has hideuser and block rights, loads block form,
789 # and loses hideuser rights before submission); so need to fail completely
790 # rather than just silently disable hiding
791 return [ 'badaccess-group0' ];
794 # Recheck params here...
795 if ( $type != Block
::TYPE_USER
) {
796 $data['HideUser'] = false; # IP users should not be hidden
797 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
799 return [ 'ipb_expiry_temp' ];
800 } elseif ( $wgHideUserContribLimit !== false
801 && $user->getEditCount() > $wgHideUserContribLimit
803 # Typically, the user should have a handful of edits.
804 # Disallow hiding users with many edits for performance.
805 return [ [ 'ipb_hide_invalid',
806 Message
::numParam( $wgHideUserContribLimit ) ] ];
807 } elseif ( !$data['Confirm'] ) {
808 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
812 # Create block object.
813 $block = new Block();
814 $block->setTarget( $target );
815 $block->setBlocker( $performer );
816 $block->mReason
= $data['Reason'][0];
817 $block->mExpiry
= $expiryTime;
818 $block->prevents( 'createaccount', $data['CreateAccount'] );
819 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit ||
$data['DisableUTEdit'] ) );
820 $block->prevents( 'sendemail', $data['DisableEmail'] );
821 $block->isHardblock( $data['HardBlock'] );
822 $block->isAutoblocking( $data['AutoBlock'] );
823 $block->mHideName
= $data['HideUser'];
826 $enablePartialBlocks &&
827 isset( $data['EditingRestriction'] ) &&
828 $data['EditingRestriction'] === 'partial'
830 $block->isSitewide( false );
833 $reason = [ 'hookaborted' ];
834 if ( !Hooks
::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
839 if ( $enablePartialBlocks ) {
840 if ( !empty( $data['PageRestrictions'] ) ) {
841 $restrictions = array_map( function ( $text ) {
842 $title = Title
::newFromText( $text );
843 // Use the link cache since the title has already been loaded when
844 // the field was validated.
845 $restriction = new PageRestriction( 0, $title->getArticleId() );
846 $restriction->setTitle( $title );
848 }, explode( "\n", $data['PageRestrictions'] ) );
851 $block->setRestrictions( $restrictions );
855 # Try to insert block. Is there a conflicting block?
856 $status = $block->insert();
858 # Indicates whether the user is confirming the block and is aware of
859 # the conflict (did not change the block target in the meantime)
860 $blockNotConfirmed = !$data['Confirm'] ||
( array_key_exists( 'PreviousTarget', $data )
861 && $data['PreviousTarget'] !== $target );
863 # Special case for API - T34434
864 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
866 # Show form unless the user is already aware of this...
867 if ( $blockNotConfirmed ||
$reblockNotAllowed ) {
868 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
869 # Otherwise, try to update the block...
871 # This returns direct blocks before autoblocks/rangeblocks, since we should
872 # be sure the user is blocked by now it should work for our purposes
873 $currentBlock = Block
::newFromTarget( $target );
874 if ( $block->equals( $currentBlock ) ) {
875 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
877 # If the name was hidden and the blocking user cannot hide
878 # names, then don't allow any block changes...
879 if ( $currentBlock->mHideName
&& !$performer->isAllowed( 'hideuser' ) ) {
880 return [ 'cant-see-hidden-user' ];
883 $priorBlock = clone $currentBlock;
884 $currentBlock->isHardblock( $block->isHardblock() );
885 $currentBlock->prevents( 'createaccount', $block->prevents( 'createaccount' ) );
886 $currentBlock->mExpiry
= $block->mExpiry
;
887 $currentBlock->isAutoblocking( $block->isAutoblocking() );
888 $currentBlock->mHideName
= $block->mHideName
;
889 $currentBlock->prevents( 'sendemail', $block->prevents( 'sendemail' ) );
890 $currentBlock->prevents( 'editownusertalk', $block->prevents( 'editownusertalk' ) );
891 $currentBlock->mReason
= $block->mReason
;
893 if ( $enablePartialBlocks ) {
894 // Maintain the sitewide status. If partial blocks is not enabled,
895 // saving the block will result in a sitewide block.
896 $currentBlock->isSitewide( $block->isSitewide() );
898 // Set the block id of the restrictions.
899 $currentBlock->setRestrictions(
900 BlockRestriction
::setBlockId( $currentBlock->getId(), $restrictions )
904 $status = $currentBlock->update();
905 // TODO handle failure
907 $logaction = 'reblock';
909 # Unset _deleted fields if requested
910 if ( $currentBlock->mHideName
&& !$data['HideUser'] ) {
911 RevisionDeleteUser
::unsuppressUserName( $target, $userId );
914 # If hiding/unhiding a name, this should go in the private logs
915 if ( (bool)$currentBlock->mHideName
) {
916 $data['HideUser'] = true;
919 $block = $currentBlock;
922 $logaction = 'block';
925 Hooks
::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
927 # Set *_deleted fields if requested
928 if ( $data['HideUser'] ) {
929 RevisionDeleteUser
::suppressUserName( $target, $userId );
932 # Can't watch a rangeblock
933 if ( $type != Block
::TYPE_RANGE
&& $data['Watch'] ) {
934 WatchAction
::doWatch(
935 Title
::makeTitle( NS_USER
, $target ),
937 User
::IGNORE_USER_RIGHTS
941 # Block constructor sanitizes certain block options on insert
942 $data['BlockEmail'] = $block->prevents( 'sendemail' );
943 $data['AutoBlock'] = $block->isAutoblocking();
945 # Prepare log parameters
947 $logParams['5::duration'] = $data['Expiry'];
948 $logParams['6::flags'] = self
::blockLogFlags( $data, $type );
949 $logParams['sitewide'] = $block->isSitewide();
951 if ( $enablePartialBlocks && !empty( $data['PageRestrictions'] ) ) {
952 $logParams['7::restrictions'] = [
953 'pages' => explode( "\n", $data['PageRestrictions'] ),
957 # Make log entry, if the name is hidden, put it in the suppression log
958 $log_type = $data['HideUser'] ?
'suppress' : 'block';
959 $logEntry = new ManualLogEntry( $log_type, $logaction );
960 $logEntry->setTarget( Title
::makeTitle( NS_USER
, $target ) );
961 $logEntry->setComment( $data['Reason'][0] );
962 $logEntry->setPerformer( $performer );
963 $logEntry->setParameters( $logParams );
964 # Relate log ID to block ID (T27763)
965 $logEntry->setRelations( [ 'ipb_id' => $block->getId() ] );
966 $logId = $logEntry->insert();
968 if ( !empty( $data['Tags'] ) ) {
969 $logEntry->setTags( $data['Tags'] );
972 $logEntry->publish( $logId );
978 * Get an array of suggested block durations from MediaWiki:Ipboptions
979 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
980 * to the standard "**<duration>|<displayname>" format?
981 * @param Language|null $lang The language to get the durations in, or null to use
982 * the wiki's content language
983 * @param bool $includeOther Whether to include the 'other' option in the list of
987 public static function getSuggestedDurations( Language
$lang = null, $includeOther = true ) {
989 $msg = $lang === null
990 ?
wfMessage( 'ipboptions' )->inContentLanguage()->text()
991 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
997 foreach ( explode( ',', $msg ) as $option ) {
998 if ( strpos( $option, ':' ) === false ) {
999 $option = "$option:$option";
1002 list( $show, $value ) = explode( ':', $option );
1006 if ( $a && $includeOther ) {
1007 // if options exist, add other to the end instead of the begining (which
1008 // is what happens by default).
1009 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
1016 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1017 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
1019 * @todo strtotime() only accepts English strings. This means the expiry input
1020 * can only be specified in English.
1021 * @see https://secure.php.net/manual/en/function.strtotime.php
1023 * @param string $expiry Whatever was typed into the form
1024 * @return string|bool Timestamp or 'infinity' or false on error.
1026 public static function parseExpiryInput( $expiry ) {
1027 if ( wfIsInfinity( $expiry ) ) {
1031 $expiry = strtotime( $expiry );
1033 if ( $expiry < 0 ||
$expiry === false ) {
1037 return wfTimestamp( TS_MW
, $expiry );
1041 * Can we do an email block?
1042 * @param User $user The sysop wanting to make a block
1045 public static function canBlockEmail( $user ) {
1046 global $wgEnableUserEmail, $wgSysopEmailBans;
1048 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1052 * T17810: blocked admins should not be able to block/unblock
1053 * others, and probably shouldn't be able to unblock themselves
1056 * Exception: Users can block the user who blocked them, to reduce
1057 * advantage of a malicious account blocking all admins (T150826)
1059 * @param User|int|string|null $target Target to block or unblock; could be a User object,
1060 * or a user ID or username, or null when the target is not known yet (e.g. when
1061 * displaying Special:Block)
1062 * @param User $performer User doing the request
1063 * @return bool|string True or error message key
1065 public static function checkUnblockSelf( $target, User
$performer ) {
1066 if ( is_int( $target ) ) {
1067 $target = User
::newFromId( $target );
1068 } elseif ( is_string( $target ) ) {
1069 $target = User
::newFromName( $target );
1071 if ( $performer->isBlocked() ) {
1072 if ( $target instanceof User
&& $target->getId() == $performer->getId() ) {
1073 # User is trying to unblock themselves
1074 if ( $performer->isAllowed( 'unblockself' ) ) {
1076 # User blocked themselves and is now trying to reverse it
1077 } elseif ( $performer->blockedBy() === $performer->getName() ) {
1080 return 'ipbnounblockself';
1083 $target instanceof User
&&
1084 $performer->getBlock() instanceof Block
&&
1085 $performer->getBlock()->getBy() &&
1086 $performer->getBlock()->getBy() === $target->getId()
1088 // Allow users to block the user that blocked them.
1089 // This is to prevent a situation where a malicious user
1090 // blocks all other users. This way, the non-malicious
1091 // user can block the malicious user back, resulting
1096 # User is trying to block/unblock someone else
1097 return 'ipbblocked';
1105 * Return a comma-delimited list of "flags" to be passed to the log
1106 * reader for this block, to provide more information in the logs
1107 * @param array $data From HTMLForm data
1108 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
1111 protected static function blockLogFlags( array $data, $type ) {
1112 $config = RequestContext
::getMain()->getConfig();
1114 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1118 # when blocking a user the option 'anononly' is not available/has no effect
1119 # -> do not write this into log
1120 if ( !$data['HardBlock'] && $type != Block
::TYPE_USER
) {
1121 // For grepping: message block-log-flags-anononly
1122 $flags[] = 'anononly';
1125 if ( $data['CreateAccount'] ) {
1126 // For grepping: message block-log-flags-nocreate
1127 $flags[] = 'nocreate';
1130 # Same as anononly, this is not displayed when blocking an IP address
1131 if ( !$data['AutoBlock'] && $type == Block
::TYPE_USER
) {
1132 // For grepping: message block-log-flags-noautoblock
1133 $flags[] = 'noautoblock';
1136 if ( $data['DisableEmail'] ) {
1137 // For grepping: message block-log-flags-noemail
1138 $flags[] = 'noemail';
1141 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1142 // For grepping: message block-log-flags-nousertalk
1143 $flags[] = 'nousertalk';
1146 if ( $data['HideUser'] ) {
1147 // For grepping: message block-log-flags-hiddenname
1148 $flags[] = 'hiddenname';
1151 return implode( ',', $flags );
1155 * Process the form on POST submission.
1156 * @param array $data
1157 * @param HTMLForm|null $form
1158 * @return bool|array True for success, false for didn't-try, array of errors on failure
1160 public function onSubmit( array $data, HTMLForm
$form = null ) {
1161 return self
::processForm( $data, $form->getContext() );
1165 * Do something exciting on successful processing of the form, most likely to show a
1166 * confirmation message
1168 public function onSuccess() {
1169 $out = $this->getOutput();
1170 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1171 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target
) );
1175 * Return an array of subpages beginning with $search that this special page will accept.
1177 * @param string $search Prefix to search for
1178 * @param int $limit Maximum number of results to return (usually 10)
1179 * @param int $offset Number of results to skip (usually 0)
1180 * @return string[] Matching subpages
1182 public function prefixSearchSubpages( $search, $limit, $offset ) {
1183 $user = User
::newFromName( $search );
1185 // No prefix suggestion for invalid user
1188 // Autocomplete subpage as user list - public to allow caching
1189 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
1192 protected function getGroupName() {