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\DatabaseBlock
;
25 use MediaWiki\Block\Restriction\PageRestriction
;
26 use MediaWiki\Block\Restriction\NamespaceRestriction
;
27 use MediaWiki\MediaWikiServices
;
28 use MediaWiki\User\UserIdentity
;
31 * A special page that allows users with 'block' right to block users from
32 * editing pages and other actions
34 * @ingroup SpecialPage
36 class SpecialBlock
extends FormSpecialPage
{
37 /** @var User|string|null User to be blocked, as passed either by parameter (url?wpTarget=Foo)
38 * or as subpage (Special:Block/Foo)
42 /** @var int DatabaseBlock::TYPE_ constant */
45 /** @var User|string The previous block target */
46 protected $previousTarget;
48 /** @var bool Whether the previous submission of the form asked for HideUser */
49 protected $requestedHideUser;
52 protected $alreadyBlocked;
55 protected $preErrors = [];
57 public function __construct() {
58 parent
::__construct( 'Block', 'block' );
61 public function doesWrites() {
66 * Checks that the user can unblock themselves if they are trying to do so
69 * @throws ErrorPageError
71 protected function checkExecutePermissions( User
$user ) {
72 parent
::checkExecutePermissions( $user );
73 # T17810: blocked admins should have limited access here
74 $status = self
::checkUnblockSelf( $this->target
, $user );
75 if ( $status !== true ) {
76 throw new ErrorPageError( 'badaccess', $status );
81 * We allow certain special cases where user is blocked
85 public function requiresUnblock() {
90 * Handle some magic here
94 protected function setParameter( $par ) {
95 # Extract variables from the request. Try not to get into a situation where we
96 # need to extract *every* variable from the form just for processing here, but
97 # there are legitimate uses for some variables
98 $request = $this->getRequest();
99 list( $this->target
, $this->type
) = self
::getTargetAndType( $par, $request );
100 if ( $this->target
instanceof User
) {
101 # Set the 'relevant user' in the skin, so it displays links like Contributions,
102 # User logs, UserRights, etc.
103 $this->getSkin()->setRelevantUser( $this->target
);
106 list( $this->previousTarget
, /*...*/ ) =
107 DatabaseBlock
::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
108 $this->requestedHideUser
= $request->getBool( 'wpHideUser' );
112 * Customizes the HTMLForm a bit
114 * @param HTMLForm $form
116 protected function alterForm( HTMLForm
$form ) {
117 $form->setHeaderText( '' );
118 $form->setSubmitDestructive();
120 $msg = $this->alreadyBlocked ?
'ipb-change-block' : 'ipbsubmit';
121 $form->setSubmitTextMsg( $msg );
123 $this->addHelpLink( 'Help:Blocking users' );
125 # Don't need to do anything if the form has been posted
126 if ( !$this->getRequest()->wasPosted() && $this->preErrors
) {
127 $s = $form->formatErrors( $this->preErrors
);
129 $form->addHeaderText( Html
::rawElement(
131 [ 'class' => 'error' ],
138 protected function getDisplayFormat() {
143 * Get the HTMLForm descriptor array for the block form
146 protected function getFormFields() {
147 $conf = $this->getConfig();
148 $enablePartialBlocks = $conf->get( 'EnablePartialBlocks' );
149 $blockAllowsUTEdit = $conf->get( 'BlockAllowsUTEdit' );
151 $this->getOutput()->enableOOUI();
153 $user = $this->getUser();
155 $suggestedDurations = self
::getSuggestedDurations();
163 'id' => 'mw-bi-target',
167 'validation-callback' => [ __CLASS__
, 'validateTargetField' ],
168 'section' => 'target',
173 'label-message' => 'block-prevent-edit',
175 'section' => 'actions',
176 'disabled' => $enablePartialBlocks ?
false : true,
179 if ( $enablePartialBlocks ) {
180 $a['EditingRestriction'] = [
182 'cssclass' => 'mw-block-editing-restriction',
184 $this->msg( 'ipb-sitewide' )->escaped() .
185 new \OOUI\
LabelWidget( [
186 'classes' => [ 'oo-ui-inline-help' ],
187 'label' => $this->msg( 'ipb-sitewide-help' )->text(),
189 $this->msg( 'ipb-partial' )->escaped() .
190 new \OOUI\
LabelWidget( [
191 'classes' => [ 'oo-ui-inline-help' ],
192 'label' => $this->msg( 'ipb-partial-help' )->text(),
195 'section' => 'actions',
197 $a['PageRestrictions'] = [
198 'type' => 'titlesmultiselect',
199 'label' => $this->msg( 'ipb-pages-label' )->text(),
202 'cssclass' => 'mw-block-restriction',
203 'showMissing' => false,
204 'excludeDynamicNamespaces' => true,
206 'autocomplete' => false
208 'section' => 'actions',
210 $a['NamespaceRestrictions'] = [
211 'type' => 'namespacesmultiselect',
212 'label' => $this->msg( 'ipb-namespaces-label' )->text(),
214 'cssclass' => 'mw-block-restriction',
216 'autocomplete' => false
218 'section' => 'actions',
222 $a['CreateAccount'] = [
224 'label-message' => 'ipbcreateaccount',
226 'section' => 'actions',
229 if ( self
::canBlockEmail( $user ) ) {
230 $a['DisableEmail'] = [
232 'label-message' => 'ipbemailban',
233 'section' => 'actions',
237 if ( $blockAllowsUTEdit ) {
238 $a['DisableUTEdit'] = [
240 'label-message' => 'ipb-disableusertalk',
242 'section' => 'actions',
249 'options' => $suggestedDurations,
250 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
251 'section' => 'expiry',
255 'type' => 'selectandother',
256 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
257 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
258 // Unicode codepoints.
259 'maxlength' => CommentStore
::COMMENT_CHARACTER_LIMIT
,
260 'maxlength-unit' => 'codepoints',
261 'options-message' => 'ipbreason-dropdown',
262 'section' => 'reason',
267 'label-message' => 'ipbenableautoblock',
269 'section' => 'options',
272 # Allow some users to hide name from block log, blocklist and listusers
273 if ( MediaWikiServices
::getInstance()
274 ->getPermissionManager()
275 ->userHasRight( $user, 'hideuser' )
279 'label-message' => 'ipbhidename',
280 'cssclass' => 'mw-block-hideuser',
281 'section' => 'options',
285 # Watchlist their user page? (Only if user is logged in)
286 if ( $user->isLoggedIn() ) {
289 'label-message' => 'ipbwatchuser',
290 'section' => 'options',
296 'label-message' => 'ipb-hardblock',
298 'section' => 'options',
301 # This is basically a copy of the Target field, but the user can't change it, so we
302 # can see if the warnings we maybe showed to the user before still apply
303 $a['PreviousTarget'] = [
308 # We'll turn this into a checkbox if we need to
312 'label-message' => 'ipb-confirm',
313 'cssclass' => 'mw-block-confirm',
316 $this->maybeAlterFormDefaults( $a );
318 // Allow extensions to add more fields
319 Hooks
::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
325 * If the user has already been blocked with similar settings, load that block
326 * and change the defaults for the form fields to match the existing settings.
327 * @param array &$fields HTMLForm descriptor array
329 protected function maybeAlterFormDefaults( &$fields ) {
330 # This will be overwritten by request data
331 $fields['Target']['default'] = (string)$this->target
;
333 if ( $this->target
) {
334 $status = self
::validateTarget( $this->target
, $this->getUser() );
335 if ( !$status->isOK() ) {
336 $errors = $status->getErrorsArray();
337 $this->preErrors
= array_merge( $this->preErrors
, $errors );
342 $fields['PreviousTarget']['default'] = (string)$this->target
;
344 $block = DatabaseBlock
::newFromTarget( $this->target
);
346 // Populate fields if there is a block that is not an autoblock; if it is a range
347 // block, only populate the fields if the range is the same as $this->target
348 if ( $block instanceof DatabaseBlock
&& $block->getType() !== DatabaseBlock
::TYPE_AUTO
349 && ( $this->type
!= DatabaseBlock
::TYPE_RANGE
350 ||
$block->getTarget() == $this->target
)
352 $fields['HardBlock']['default'] = $block->isHardblock();
353 $fields['CreateAccount']['default'] = $block->isCreateAccountBlocked();
354 $fields['AutoBlock']['default'] = $block->isAutoblocking();
356 if ( isset( $fields['DisableEmail'] ) ) {
357 $fields['DisableEmail']['default'] = $block->isEmailBlocked();
360 if ( isset( $fields['HideUser'] ) ) {
361 $fields['HideUser']['default'] = $block->getHideName();
364 if ( isset( $fields['DisableUTEdit'] ) ) {
365 $fields['DisableUTEdit']['default'] = !$block->isUsertalkEditAllowed();
368 // If the username was hidden (ipb_deleted == 1), don't show the reason
369 // unless this user also has rights to hideuser: T37839
370 if ( !$block->getHideName() || MediaWikiServices
::getInstance()
371 ->getPermissionManager()
372 ->userHasRight( $this->getUser(), 'hideuser' )
374 $fields['Reason']['default'] = $block->getReason();
376 $fields['Reason']['default'] = '';
379 if ( $this->getRequest()->wasPosted() ) {
380 # Ok, so we got a POST submission asking us to reblock a user. So show the
381 # confirm checkbox; the user will only see it if they haven't previously
382 $fields['Confirm']['type'] = 'check';
384 # We got a target, but it wasn't a POST request, so the user must have gone
385 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
386 # as long as they go ahead and block *that* user
387 $fields['Confirm']['default'] = 1;
390 if ( $block->getExpiry() == 'infinity' ) {
391 $fields['Expiry']['default'] = 'infinite';
393 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822
, $block->getExpiry() );
396 $this->alreadyBlocked
= true;
397 $this->preErrors
[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
400 if ( $this->alreadyBlocked ||
$this->getRequest()->wasPosted()
401 ||
$this->getRequest()->getCheck( 'wpCreateAccount' )
403 $this->getOutput()->addJsConfigVars( 'wgCreateAccountDirty', true );
406 # We always need confirmation to do HideUser
407 if ( $this->requestedHideUser
) {
408 $fields['Confirm']['type'] = 'check';
409 unset( $fields['Confirm']['default'] );
410 $this->preErrors
[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
413 # Or if the user is trying to block themselves
414 if ( (string)$this->target
=== $this->getUser()->getName() ) {
415 $fields['Confirm']['type'] = 'check';
416 unset( $fields['Confirm']['default'] );
417 $this->preErrors
[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
420 if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
421 if ( $block instanceof DatabaseBlock
&& !$block->isSitewide() ) {
422 $fields['EditingRestriction']['default'] = 'partial';
424 $fields['EditingRestriction']['default'] = 'sitewide';
427 if ( $block instanceof DatabaseBlock
) {
428 $pageRestrictions = [];
429 $namespaceRestrictions = [];
430 foreach ( $block->getRestrictions() as $restriction ) {
431 switch ( $restriction->getType() ) {
432 case PageRestriction
::TYPE
:
433 /** @var PageRestriction $restriction */
434 '@phan-var PageRestriction $restriction';
435 if ( $restriction->getTitle() ) {
436 $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
439 case NamespaceRestriction
::TYPE
:
440 $namespaceRestrictions[] = $restriction->getValue();
446 !$block->isSitewide() &&
447 empty( $pageRestrictions ) &&
448 empty( $namespaceRestrictions )
450 $fields['Editing']['default'] = false;
453 // Sort the restrictions so they are in alphabetical order.
454 sort( $pageRestrictions );
455 $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
456 sort( $namespaceRestrictions );
457 $fields['NamespaceRestrictions']['default'] = implode( "\n", $namespaceRestrictions );
463 * Add header elements like block log entries, etc.
466 protected function preText() {
467 $this->getOutput()->addModuleStyles( [
468 'mediawiki.widgets.TagMultiselectWidget.styles',
471 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
473 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
474 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
476 $otherBlockMessages = [];
477 if ( $this->target
!== null ) {
478 $targetName = $this->target
;
479 if ( $this->target
instanceof User
) {
480 $targetName = $this->target
->getName();
482 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
483 Hooks
::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
485 if ( count( $otherBlockMessages ) ) {
486 $s = Html
::rawElement(
489 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
494 foreach ( $otherBlockMessages as $link ) {
495 $list .= Html
::rawElement( 'li', [], $link ) . "\n";
498 $s .= Html
::rawElement(
500 [ 'class' => 'mw-blockip-alreadyblocked' ],
512 * Add footer elements to the form
515 protected function postText() {
518 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
520 $linkRenderer = $this->getLinkRenderer();
521 # Link to the user's contributions, if applicable
522 if ( $this->target
instanceof User
) {
523 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $this->target
->getName() );
524 $links[] = $linkRenderer->makeLink(
526 $this->msg( 'ipb-blocklist-contribs', $this->target
->getName() )->text()
530 # Link to unblock the specified user, or to a blank unblock form
531 if ( $this->target
instanceof User
) {
532 $message = $this->msg(
534 wfEscapeWikiText( $this->target
->getName() )
536 $list = SpecialPage
::getTitleFor( 'Unblock', $this->target
->getName() );
538 $message = $this->msg( 'ipb-unblock' )->parse();
539 $list = SpecialPage
::getTitleFor( 'Unblock' );
541 $links[] = $linkRenderer->makeKnownLink(
543 new HtmlArmor( $message )
546 # Link to the block list
547 $links[] = $linkRenderer->makeKnownLink(
548 SpecialPage
::getTitleFor( 'BlockList' ),
549 $this->msg( 'ipb-blocklist' )->text()
552 $user = $this->getUser();
554 # Link to edit the block dropdown reasons, if applicable
555 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
556 if ( $permissionManager->userHasRight( $user, 'editinterface' ) ) {
557 $links[] = $linkRenderer->makeKnownLink(
558 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
559 $this->msg( 'ipb-edit-dropdown' )->text(),
561 [ 'action' => 'edit' ]
565 $text = Html
::rawElement(
567 [ 'class' => 'mw-ipb-conveniencelinks' ],
568 $this->getLanguage()->pipeList( $links )
571 $userTitle = self
::getTargetUserTitle( $this->target
);
573 # Get relevant extracts from the block and suppression logs, if possible
576 LogEventsList
::showLogExtract(
583 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
584 'showIfEmpty' => false
589 # Add suppression block entries if allowed
590 if ( $permissionManager->userHasRight( $user, 'suppressionlog' ) ) {
591 LogEventsList
::showLogExtract(
598 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
599 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
600 'showIfEmpty' => false
612 * Get a user page target for things like logs.
613 * This handles account and IP range targets.
614 * @param User|string $target
617 protected static function getTargetUserTitle( $target ) {
618 if ( $target instanceof User
) {
619 return $target->getUserPage();
620 } elseif ( IP
::isIPAddress( $target ) ) {
621 return Title
::makeTitleSafe( NS_USER
, $target );
628 * Determine the target of the block, and the type of target
629 * @todo Should be in DatabaseBlock.php?
630 * @param string $par Subpage parameter passed to setup, or data value from
632 * @param WebRequest|null $request Optionally try and get data from a request too
633 * @return array [ User|string|null, DatabaseBlock::TYPE_ constant|null ]
634 * @phan-return array{0:User|string|null,1:int|null}
636 public static function getTargetAndType( $par, WebRequest
$request = null ) {
643 # The HTMLForm will check wpTarget first and only if it doesn't get
644 # a value use the default, which will be generated from the options
645 # below; so this has to have a higher precedence here than $par, or
646 # we could end up with different values in $this->target and the HTMLForm!
647 if ( $request instanceof WebRequest
) {
648 $target = $request->getText( 'wpTarget', null );
655 if ( $request instanceof WebRequest
) {
656 $target = $request->getText( 'ip', null );
661 if ( $request instanceof WebRequest
) {
662 $target = $request->getText( 'wpBlockAddress', null );
669 list( $target, $type ) = DatabaseBlock
::parseTarget( $target );
671 if ( $type !== null ) {
672 return [ $target, $type ];
676 return [ null, null ];
680 * HTMLForm field validation-callback for Target field.
682 * @param string $value
683 * @param array $alldata
684 * @param HTMLForm $form
687 public static function validateTargetField( $value, $alldata, $form ) {
688 $status = self
::validateTarget( $value, $form->getUser() );
689 if ( !$status->isOK() ) {
690 $errors = $status->getErrorsArray();
692 return $form->msg( ...$errors[0] );
699 * Validate a block target.
702 * @param string $value Block target to check
703 * @param User $user Performer of the block
706 public static function validateTarget( $value, User
$user ) {
707 global $wgBlockCIDRLimit;
709 /** @var User $target */
710 list( $target, $type ) = self
::getTargetAndType( $value );
711 $status = Status
::newGood( $target );
713 if ( $type == DatabaseBlock
::TYPE_USER
) {
714 if ( $target->isAnon() ) {
717 wfEscapeWikiText( $target->getName() )
721 $unblockStatus = self
::checkUnblockSelf( $target, $user );
722 if ( $unblockStatus !== true ) {
723 $status->fatal( 'badaccess', $unblockStatus );
725 } elseif ( $type == DatabaseBlock
::TYPE_RANGE
) {
726 list( $ip, $range ) = explode( '/', $target, 2 );
729 ( IP
::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
730 ( IP
::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
732 // Range block effectively disabled
733 $status->fatal( 'range_block_disabled' );
737 ( IP
::isIPv4( $ip ) && $range > 32 ) ||
738 ( IP
::isIPv6( $ip ) && $range > 128 )
741 $status->fatal( 'ip_range_invalid' );
744 if ( IP
::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
745 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
748 if ( IP
::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
749 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
751 } elseif ( $type == DatabaseBlock
::TYPE_IP
) {
754 $status->fatal( 'badipaddress' );
761 * Given the form data, actually implement a block. This is also called from ApiBlock.
764 * @param IContextSource $context
767 public static function processForm( array $data, IContextSource
$context ) {
768 $performer = $context->getUser();
769 $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
770 $isPartialBlock = $enablePartialBlocks &&
771 isset( $data['EditingRestriction'] ) &&
772 $data['EditingRestriction'] === 'partial';
774 # This might have been a hidden field or a checkbox, so interesting data
776 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
778 /** @var User $target */
779 list( $target, $type ) = self
::getTargetAndType( $data['Target'] );
780 if ( $type == DatabaseBlock
::TYPE_USER
) {
782 $target = $user->getName();
783 $userId = $user->getId();
785 # Give admins a heads-up before they go and block themselves. Much messier
786 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
787 # permission anyway, although the code does allow for it.
788 # Note: Important to use $target instead of $data['Target']
789 # since both $data['PreviousTarget'] and $target are normalized
790 # but $data['target'] gets overridden by (non-normalized) request variable
791 # from previous request.
792 if ( $target === $performer->getName() &&
793 ( $data['PreviousTarget'] !== $target ||
!$data['Confirm'] )
795 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
797 } elseif ( $type == DatabaseBlock
::TYPE_RANGE
) {
800 } elseif ( $type == DatabaseBlock
::TYPE_IP
) {
802 $target = $target->getName();
805 # This should have been caught in the form field validation
806 return [ 'badipaddress' ];
809 $expiryTime = self
::parseExpiryInput( $data['Expiry'] );
812 // an expiry time is needed
813 ( strlen( $data['Expiry'] ) == 0 ) ||
814 // can't be a larger string as 50 (it should be a time format in any way)
815 ( strlen( $data['Expiry'] ) > 50 ) ||
816 // check, if the time could be parsed
819 return [ 'ipb_expiry_invalid' ];
822 // an expiry time should be in the future, not in the
823 // past (wouldn't make any sense) - bug T123069
824 if ( $expiryTime < wfTimestampNow() ) {
825 return [ 'ipb_expiry_old' ];
828 if ( !isset( $data['DisableEmail'] ) ) {
829 $data['DisableEmail'] = false;
832 # If the user has done the form 'properly', they won't even have been given the
833 # option to suppress-block unless they have the 'hideuser' permission
834 if ( !isset( $data['HideUser'] ) ) {
835 $data['HideUser'] = false;
838 if ( $data['HideUser'] ) {
839 if ( !MediaWikiServices
::getInstance()
840 ->getPermissionManager()
841 ->userHasRight( $performer, 'hideuser' )
843 # this codepath is unreachable except by a malicious user spoofing forms,
844 # or by race conditions (user has hideuser and block rights, loads block form,
845 # and loses hideuser rights before submission); so need to fail completely
846 # rather than just silently disable hiding
847 return [ 'badaccess-group0' ];
850 if ( $isPartialBlock ) {
851 return [ 'ipb_hide_partial' ];
854 # Recheck params here...
855 $hideUserContribLimit = $context->getConfig()->get( 'HideUserContribLimit' );
856 if ( $type != DatabaseBlock
::TYPE_USER
) {
857 $data['HideUser'] = false; # IP users should not be hidden
858 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
860 return [ 'ipb_expiry_temp' ];
861 } elseif ( $hideUserContribLimit !== false
862 && $user->getEditCount() > $hideUserContribLimit
864 # Typically, the user should have a handful of edits.
865 # Disallow hiding users with many edits for performance.
866 return [ [ 'ipb_hide_invalid',
867 Message
::numParam( $hideUserContribLimit ) ] ];
868 } elseif ( !$data['Confirm'] ) {
869 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
873 $blockAllowsUTEdit = $context->getConfig()->get( 'BlockAllowsUTEdit' );
874 $userTalkEditAllowed = !$blockAllowsUTEdit ||
!$data['DisableUTEdit'];
875 if ( !$userTalkEditAllowed &&
877 !in_array( NS_USER_TALK
, explode( "\n", $data['NamespaceRestrictions'] ) )
879 return [ 'ipb-prevent-user-talk-edit' ];
882 # Create block object.
883 $block = new DatabaseBlock();
884 $block->setTarget( $target );
885 $block->setBlocker( $performer );
886 $block->setReason( $data['Reason'][0] );
887 $block->setExpiry( $expiryTime );
888 $block->isCreateAccountBlocked( $data['CreateAccount'] );
889 $block->isUsertalkEditAllowed( $userTalkEditAllowed );
890 $block->isEmailBlocked( $data['DisableEmail'] );
891 $block->isHardblock( $data['HardBlock'] );
892 $block->isAutoblocking( $data['AutoBlock'] );
893 $block->setHideName( $data['HideUser'] );
895 if ( $isPartialBlock ) {
896 $block->isSitewide( false );
899 $reason = [ 'hookaborted' ];
900 if ( !Hooks
::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
904 $pageRestrictions = [];
905 $namespaceRestrictions = [];
906 if ( $enablePartialBlocks ) {
907 if ( $data['PageRestrictions'] !== '' ) {
908 $pageRestrictions = array_map( function ( $text ) {
909 $title = Title
::newFromText( $text );
910 // Use the link cache since the title has already been loaded when
911 // the field was validated.
912 $restriction = new PageRestriction( 0, $title->getArticleID() );
913 $restriction->setTitle( $title );
915 }, explode( "\n", $data['PageRestrictions'] ) );
917 if ( $data['NamespaceRestrictions'] !== '' ) {
918 $namespaceRestrictions = array_map( function ( $id ) {
919 return new NamespaceRestriction( 0, $id );
920 }, explode( "\n", $data['NamespaceRestrictions'] ) );
923 $restrictions = ( array_merge( $pageRestrictions, $namespaceRestrictions ) );
924 $block->setRestrictions( $restrictions );
928 # Try to insert block. Is there a conflicting block?
929 $status = $block->insert();
931 # Indicates whether the user is confirming the block and is aware of
932 # the conflict (did not change the block target in the meantime)
933 $blockNotConfirmed = !$data['Confirm'] ||
( array_key_exists( 'PreviousTarget', $data )
934 && $data['PreviousTarget'] !== $target );
936 # Special case for API - T34434
937 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
939 # Show form unless the user is already aware of this...
940 if ( $blockNotConfirmed ||
$reblockNotAllowed ) {
941 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
942 # Otherwise, try to update the block...
944 # This returns direct blocks before autoblocks/rangeblocks, since we should
945 # be sure the user is blocked by now it should work for our purposes
946 $currentBlock = DatabaseBlock
::newFromTarget( $target );
947 if ( $block->equals( $currentBlock ) ) {
948 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
950 # If the name was hidden and the blocking user cannot hide
951 # names, then don't allow any block changes...
952 if ( $currentBlock->getHideName() && !MediaWikiServices
::getInstance()
953 ->getPermissionManager()
954 ->userHasRight( $performer, 'hideuser' )
956 return [ 'cant-see-hidden-user' ];
959 $priorBlock = clone $currentBlock;
960 $currentBlock->isHardblock( $block->isHardblock() );
961 $currentBlock->isCreateAccountBlocked( $block->isCreateAccountBlocked() );
962 $currentBlock->setExpiry( $block->getExpiry() );
963 $currentBlock->isAutoblocking( $block->isAutoblocking() );
964 $currentBlock->setHideName( $block->getHideName() );
965 $currentBlock->isEmailBlocked( $block->isEmailBlocked() );
966 $currentBlock->isUsertalkEditAllowed( $block->isUsertalkEditAllowed() );
967 $currentBlock->setReason( $block->getReason() );
969 if ( $enablePartialBlocks ) {
970 // Maintain the sitewide status. If partial blocks is not enabled,
971 // saving the block will result in a sitewide block.
972 $currentBlock->isSitewide( $block->isSitewide() );
974 // Set the block id of the restrictions.
975 $blockRestrictionStore = MediaWikiServices
::getInstance()->getBlockRestrictionStore();
976 $currentBlock->setRestrictions(
977 $blockRestrictionStore->setBlockId( $currentBlock->getId(), $restrictions )
981 $status = $currentBlock->update();
982 // TODO handle failure
984 $logaction = 'reblock';
986 # Unset _deleted fields if requested
987 if ( $currentBlock->getHideName() && !$data['HideUser'] ) {
988 RevisionDeleteUser
::unsuppressUserName( $target, $userId );
991 # If hiding/unhiding a name, this should go in the private logs
992 if ( (bool)$currentBlock->getHideName() ) {
993 $data['HideUser'] = true;
996 $block = $currentBlock;
999 $logaction = 'block';
1002 Hooks
::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
1004 # Set *_deleted fields if requested
1005 if ( $data['HideUser'] ) {
1006 RevisionDeleteUser
::suppressUserName( $target, $userId );
1009 # Can't watch a rangeblock
1010 if ( $type != DatabaseBlock
::TYPE_RANGE
&& $data['Watch'] ) {
1011 WatchAction
::doWatch(
1012 Title
::makeTitle( NS_USER
, $target ),
1014 User
::IGNORE_USER_RIGHTS
1018 # DatabaseBlock constructor sanitizes certain block options on insert
1019 $data['BlockEmail'] = $block->isEmailBlocked();
1020 $data['AutoBlock'] = $block->isAutoblocking();
1022 # Prepare log parameters
1024 $logParams['5::duration'] = $data['Expiry'];
1025 $logParams['6::flags'] = self
::blockLogFlags( $data, $type );
1026 $logParams['sitewide'] = $block->isSitewide();
1028 if ( $enablePartialBlocks && !$block->isSitewide() ) {
1029 if ( $data['PageRestrictions'] !== '' ) {
1030 $logParams['7::restrictions']['pages'] = explode( "\n", $data['PageRestrictions'] );
1033 if ( $data['NamespaceRestrictions'] !== '' ) {
1034 $logParams['7::restrictions']['namespaces'] = explode( "\n", $data['NamespaceRestrictions'] );
1038 # Make log entry, if the name is hidden, put it in the suppression log
1039 $log_type = $data['HideUser'] ?
'suppress' : 'block';
1040 $logEntry = new ManualLogEntry( $log_type, $logaction );
1041 $logEntry->setTarget( Title
::makeTitle( NS_USER
, $target ) );
1042 $logEntry->setComment( $data['Reason'][0] );
1043 $logEntry->setPerformer( $performer );
1044 $logEntry->setParameters( $logParams );
1045 # Relate log ID to block ID (T27763)
1046 $logEntry->setRelations( [ 'ipb_id' => $block->getId() ] );
1047 $logId = $logEntry->insert();
1049 if ( !empty( $data['Tags'] ) ) {
1050 $logEntry->addTags( $data['Tags'] );
1053 $logEntry->publish( $logId );
1059 * Get an array of suggested block durations from MediaWiki:Ipboptions
1060 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
1061 * to the standard "**<duration>|<displayname>" format?
1062 * @param Language|null $lang The language to get the durations in, or null to use
1063 * the wiki's content language
1064 * @param bool $includeOther Whether to include the 'other' option in the list of
1068 public static function getSuggestedDurations( Language
$lang = null, $includeOther = true ) {
1070 $msg = $lang === null
1071 ?
wfMessage( 'ipboptions' )->inContentLanguage()->text()
1072 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
1074 if ( $msg == '-' ) {
1078 foreach ( explode( ',', $msg ) as $option ) {
1079 if ( strpos( $option, ':' ) === false ) {
1080 $option = "$option:$option";
1083 list( $show, $value ) = explode( ':', $option );
1087 if ( $a && $includeOther ) {
1088 // if options exist, add other to the end instead of the begining (which
1089 // is what happens by default).
1090 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
1097 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1098 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
1100 * @todo strtotime() only accepts English strings. This means the expiry input
1101 * can only be specified in English.
1102 * @see https://www.php.net/manual/en/function.strtotime.php
1104 * @param string $expiry Whatever was typed into the form
1105 * @return string|bool Timestamp or 'infinity' or false on error.
1107 public static function parseExpiryInput( $expiry ) {
1108 if ( wfIsInfinity( $expiry ) ) {
1112 $expiry = strtotime( $expiry );
1114 if ( $expiry < 0 ||
$expiry === false ) {
1118 return wfTimestamp( TS_MW
, $expiry );
1122 * Can we do an email block?
1123 * @param UserIdentity $user The sysop wanting to make a block
1126 public static function canBlockEmail( UserIdentity
$user ) {
1127 global $wgEnableUserEmail;
1129 return ( $wgEnableUserEmail && MediaWikiServices
::getInstance()
1130 ->getPermissionManager()
1131 ->userHasRight( $user, 'blockemail' ) );
1135 * T17810: blocked admins should not be able to block/unblock
1136 * others, and probably shouldn't be able to unblock themselves
1139 * Exception: Users can block the user who blocked them, to reduce
1140 * advantage of a malicious account blocking all admins (T150826)
1142 * @param User|int|string|null $target Target to block or unblock; could be a User object,
1143 * or a user ID or username, or null when the target is not known yet (e.g. when
1144 * displaying Special:Block)
1145 * @param User $performer User doing the request
1146 * @return bool|string True or error message key
1148 public static function checkUnblockSelf( $target, User
$performer ) {
1149 if ( is_int( $target ) ) {
1150 $target = User
::newFromId( $target );
1151 } elseif ( is_string( $target ) ) {
1152 $target = User
::newFromName( $target );
1154 if ( $performer->getBlock() ) {
1155 if ( $target instanceof User
&& $target->getId() == $performer->getId() ) {
1156 # User is trying to unblock themselves
1157 if ( MediaWikiServices
::getInstance()
1158 ->getPermissionManager()
1159 ->userHasRight( $performer, 'unblockself' )
1162 # User blocked themselves and is now trying to reverse it
1163 } elseif ( $performer->blockedBy() === $performer->getName() ) {
1166 return 'ipbnounblockself';
1169 $target instanceof User
&&
1170 $performer->getBlock() instanceof DatabaseBlock
&&
1171 $performer->getBlock()->getBy() &&
1172 $performer->getBlock()->getBy() === $target->getId()
1174 // Allow users to block the user that blocked them.
1175 // This is to prevent a situation where a malicious user
1176 // blocks all other users. This way, the non-malicious
1177 // user can block the malicious user back, resulting
1182 # User is trying to block/unblock someone else
1183 return 'ipbblocked';
1191 * Return a comma-delimited list of "flags" to be passed to the log
1192 * reader for this block, to provide more information in the logs
1193 * @param array $data From HTMLForm data
1194 * @param int $type DatabaseBlock::TYPE_ constant (USER, RANGE, or IP)
1197 protected static function blockLogFlags( array $data, $type ) {
1198 $config = RequestContext
::getMain()->getConfig();
1200 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1204 # when blocking a user the option 'anononly' is not available/has no effect
1205 # -> do not write this into log
1206 if ( !$data['HardBlock'] && $type != DatabaseBlock
::TYPE_USER
) {
1207 // For grepping: message block-log-flags-anononly
1208 $flags[] = 'anononly';
1211 if ( $data['CreateAccount'] ) {
1212 // For grepping: message block-log-flags-nocreate
1213 $flags[] = 'nocreate';
1216 # Same as anononly, this is not displayed when blocking an IP address
1217 if ( !$data['AutoBlock'] && $type == DatabaseBlock
::TYPE_USER
) {
1218 // For grepping: message block-log-flags-noautoblock
1219 $flags[] = 'noautoblock';
1222 if ( $data['DisableEmail'] ) {
1223 // For grepping: message block-log-flags-noemail
1224 $flags[] = 'noemail';
1227 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1228 // For grepping: message block-log-flags-nousertalk
1229 $flags[] = 'nousertalk';
1232 if ( $data['HideUser'] ) {
1233 // For grepping: message block-log-flags-hiddenname
1234 $flags[] = 'hiddenname';
1237 return implode( ',', $flags );
1241 * Process the form on POST submission.
1242 * @param array $data
1243 * @param HTMLForm|null $form
1244 * @return bool|array True for success, false for didn't-try, array of errors on failure
1246 public function onSubmit( array $data, HTMLForm
$form = null ) {
1247 // If "Editing" checkbox is unchecked, the block must be a partial block affecting
1248 // actions other than editing, and there must be no restrictions.
1249 if ( isset( $data['Editing'] ) && $data['Editing'] === false ) {
1250 $data['EditingRestriction'] = 'partial';
1251 $data['PageRestrictions'] = '';
1252 $data['NamespaceRestrictions'] = '';
1254 return self
::processForm( $data, $form->getContext() );
1258 * Do something exciting on successful processing of the form, most likely to show a
1259 * confirmation message
1261 public function onSuccess() {
1262 $out = $this->getOutput();
1263 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1264 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target
) );
1268 * Return an array of subpages beginning with $search that this special page will accept.
1270 * @param string $search Prefix to search for
1271 * @param int $limit Maximum number of results to return (usually 10)
1272 * @param int $offset Number of results to skip (usually 0)
1273 * @return string[] Matching subpages
1275 public function prefixSearchSubpages( $search, $limit, $offset ) {
1276 $user = User
::newFromName( $search );
1278 // No prefix suggestion for invalid user
1281 // Autocomplete subpage as user list - public to allow caching
1282 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
1285 protected function getGroupName() {