3 * Implements Special:Block
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
24 use MediaWiki\Block\BlockRestriction
;
25 use MediaWiki\Block\Restriction\PageRestriction
;
28 * A special page that allows users with 'block' right to block users from
29 * editing pages and other actions
31 * @ingroup SpecialPage
33 class SpecialBlock
extends FormSpecialPage
{
34 /** @var User|string|null User to be blocked, as passed either by parameter (url?wpTarget=Foo)
35 * or as subpage (Special:Block/Foo) */
38 /** @var int Block::TYPE_ constant */
41 /** @var User|string The previous block target */
42 protected $previousTarget;
44 /** @var bool Whether the previous submission of the form asked for HideUser */
45 protected $requestedHideUser;
48 protected $alreadyBlocked;
51 protected $preErrors = [];
53 public function __construct() {
54 parent
::__construct( 'Block', 'block' );
57 public function doesWrites() {
62 * Checks that the user can unblock themselves if they are trying to do so
65 * @throws ErrorPageError
67 protected function checkExecutePermissions( User
$user ) {
68 parent
::checkExecutePermissions( $user );
69 # T17810: blocked admins should have limited access here
70 $status = self
::checkUnblockSelf( $this->target
, $user );
71 if ( $status !== true ) {
72 throw new ErrorPageError( 'badaccess', $status );
77 * We allow certain special cases where user is blocked
81 public function requiresUnblock() {
86 * Handle some magic here
90 protected function setParameter( $par ) {
91 # Extract variables from the request. Try not to get into a situation where we
92 # need to extract *every* variable from the form just for processing here, but
93 # there are legitimate uses for some variables
94 $request = $this->getRequest();
95 list( $this->target
, $this->type
) = self
::getTargetAndType( $par, $request );
96 if ( $this->target
instanceof User
) {
97 # Set the 'relevant user' in the skin, so it displays links like Contributions,
98 # User logs, UserRights, etc.
99 $this->getSkin()->setRelevantUser( $this->target
);
102 list( $this->previousTarget
, /*...*/ ) =
103 Block
::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
104 $this->requestedHideUser
= $request->getBool( 'wpHideUser' );
108 * Customizes the HTMLForm a bit
110 * @param HTMLForm $form
112 protected function alterForm( HTMLForm
$form ) {
113 $form->setHeaderText( '' );
114 $form->setSubmitDestructive();
116 $msg = $this->alreadyBlocked ?
'ipb-change-block' : 'ipbsubmit';
117 $form->setSubmitTextMsg( $msg );
119 $this->addHelpLink( 'Help:Blocking users' );
121 # Don't need to do anything if the form has been posted
122 if ( !$this->getRequest()->wasPosted() && $this->preErrors
) {
123 $s = $form->formatErrors( $this->preErrors
);
125 $form->addHeaderText( Html
::rawElement(
127 [ 'class' => 'error' ],
134 protected function getDisplayFormat() {
139 * Get the HTMLForm descriptor array for the block form
142 protected function getFormFields() {
143 global $wgBlockAllowsUTEdit;
145 $user = $this->getUser();
147 $suggestedDurations = self
::getSuggestedDurations();
149 $conf = $this->getConfig();
150 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
151 $enablePartialBlocks = $conf->get( 'EnablePartialBlocks' );
159 'label-message' => 'ipaddressorusername',
160 'id' => 'mw-bi-target',
164 'validation-callback' => [ __CLASS__
, 'validateTargetField' ],
167 if ( $enablePartialBlocks ) {
168 $a['EditingRestriction'] = [
170 'label' => $this->msg( 'ipb-type-label' )->text(),
172 $this->msg( 'ipb-sitewide' )->text() => 'sitewide',
173 $this->msg( 'ipb-partial' )->text() => 'partial',
176 $a['PageRestrictions'] = [
177 'type' => 'titlesmultiselect',
178 'label' => $this->msg( 'ipb-pages-label' )->text(),
181 'cssclass' => 'mw-block-page-restrictions',
182 'showMissing' => false,
184 'autocomplete' => false
191 'label-message' => 'ipbexpiry',
193 'options' => $suggestedDurations,
194 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
198 'type' => 'selectandother',
199 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
200 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
201 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
202 'maxlength' => $oldCommentSchema ?
255 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
203 'maxlength-unit' => 'codepoints',
204 'label-message' => 'ipbreason',
205 'options-message' => 'ipbreason-dropdown',
208 $a['CreateAccount'] = [
210 'label-message' => 'ipbcreateaccount',
214 if ( self
::canBlockEmail( $user ) ) {
215 $a['DisableEmail'] = [
217 'label-message' => 'ipbemailban',
221 if ( $wgBlockAllowsUTEdit ) {
222 $a['DisableUTEdit'] = [
224 'label-message' => 'ipb-disableusertalk',
231 'label-message' => 'ipbenableautoblock',
235 # Allow some users to hide name from block log, blocklist and listusers
236 if ( $user->isAllowed( 'hideuser' ) ) {
239 'label-message' => 'ipbhidename',
240 'cssclass' => 'mw-block-hideuser',
244 # Watchlist their user page? (Only if user is logged in)
245 if ( $user->isLoggedIn() ) {
248 'label-message' => 'ipbwatchuser',
254 'label-message' => 'ipb-hardblock',
258 # This is basically a copy of the Target field, but the user can't change it, so we
259 # can see if the warnings we maybe showed to the user before still apply
260 $a['PreviousTarget'] = [
265 # We'll turn this into a checkbox if we need to
269 'label-message' => 'ipb-confirm',
270 'cssclass' => 'mw-block-confirm',
273 $this->maybeAlterFormDefaults( $a );
275 // Allow extensions to add more fields
276 Hooks
::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
282 * If the user has already been blocked with similar settings, load that block
283 * and change the defaults for the form fields to match the existing settings.
284 * @param array &$fields HTMLForm descriptor array
285 * @return bool Whether fields were altered (that is, whether the target is
288 protected function maybeAlterFormDefaults( &$fields ) {
289 # This will be overwritten by request data
290 $fields['Target']['default'] = (string)$this->target
;
292 if ( $this->target
) {
293 $status = self
::validateTarget( $this->target
, $this->getUser() );
294 if ( !$status->isOK() ) {
295 $errors = $status->getErrorsArray();
296 $this->preErrors
= array_merge( $this->preErrors
, $errors );
301 $fields['PreviousTarget']['default'] = (string)$this->target
;
303 $block = Block
::newFromTarget( $this->target
);
305 if ( $block instanceof Block
&& !$block->mAuto
# The block exists and isn't an autoblock
306 && ( $this->type
!= Block
::TYPE_RANGE
# The block isn't a rangeblock
307 ||
$block->getTarget() == $this->target
) # or if it is, the range is what we're about to block
309 $fields['HardBlock']['default'] = $block->isHardblock();
310 $fields['CreateAccount']['default'] = $block->prevents( 'createaccount' );
311 $fields['AutoBlock']['default'] = $block->isAutoblocking();
313 if ( isset( $fields['DisableEmail'] ) ) {
314 $fields['DisableEmail']['default'] = $block->prevents( 'sendemail' );
317 if ( isset( $fields['HideUser'] ) ) {
318 $fields['HideUser']['default'] = $block->mHideName
;
321 if ( isset( $fields['DisableUTEdit'] ) ) {
322 $fields['DisableUTEdit']['default'] = $block->prevents( 'editownusertalk' );
325 // If the username was hidden (ipb_deleted == 1), don't show the reason
326 // unless this user also has rights to hideuser: T37839
327 if ( !$block->mHideName ||
$this->getUser()->isAllowed( 'hideuser' ) ) {
328 $fields['Reason']['default'] = $block->mReason
;
330 $fields['Reason']['default'] = '';
333 if ( $this->getRequest()->wasPosted() ) {
334 # Ok, so we got a POST submission asking us to reblock a user. So show the
335 # confirm checkbox; the user will only see it if they haven't previously
336 $fields['Confirm']['type'] = 'check';
338 # We got a target, but it wasn't a POST request, so the user must have gone
339 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
340 # as long as they go ahead and block *that* user
341 $fields['Confirm']['default'] = 1;
344 if ( $block->mExpiry
== 'infinity' ) {
345 $fields['Expiry']['default'] = 'infinite';
347 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822
, $block->mExpiry
);
350 $this->alreadyBlocked
= true;
351 $this->preErrors
[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
354 # We always need confirmation to do HideUser
355 if ( $this->requestedHideUser
) {
356 $fields['Confirm']['type'] = 'check';
357 unset( $fields['Confirm']['default'] );
358 $this->preErrors
[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
361 # Or if the user is trying to block themselves
362 if ( (string)$this->target
=== $this->getUser()->getName() ) {
363 $fields['Confirm']['type'] = 'check';
364 unset( $fields['Confirm']['default'] );
365 $this->preErrors
[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
368 if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
369 if ( $block instanceof Block
&& !$block->isSitewide() ) {
370 $fields['EditingRestriction']['default'] = 'partial';
372 $fields['EditingRestriction']['default'] = 'sitewide';
375 if ( $block instanceof Block
) {
376 $pageRestrictions = [];
377 foreach ( $block->getRestrictions() as $restriction ) {
378 if ( $restriction->getType() !== 'page' ) {
382 $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
385 // Sort the restrictions so they are in alphabetical order.
386 sort( $pageRestrictions );
387 $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
393 * Add header elements like block log entries, etc.
396 protected function preText() {
397 $this->getOutput()->addModuleStyles( 'mediawiki.widgets.TitlesMultiselectWidget.styles' );
398 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
400 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
401 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
403 $otherBlockMessages = [];
404 if ( $this->target
!== null ) {
405 $targetName = $this->target
;
406 if ( $this->target
instanceof User
) {
407 $targetName = $this->target
->getName();
409 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
410 Hooks
::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
412 if ( count( $otherBlockMessages ) ) {
413 $s = Html
::rawElement(
416 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
421 foreach ( $otherBlockMessages as $link ) {
422 $list .= Html
::rawElement( 'li', [], $link ) . "\n";
425 $s .= Html
::rawElement(
427 [ 'class' => 'mw-blockip-alreadyblocked' ],
439 * Add footer elements to the form
442 protected function postText() {
445 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
447 $linkRenderer = $this->getLinkRenderer();
448 # Link to the user's contributions, if applicable
449 if ( $this->target
instanceof User
) {
450 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $this->target
->getName() );
451 $links[] = $linkRenderer->makeLink(
453 $this->msg( 'ipb-blocklist-contribs', $this->target
->getName() )->text()
457 # Link to unblock the specified user, or to a blank unblock form
458 if ( $this->target
instanceof User
) {
459 $message = $this->msg(
461 wfEscapeWikiText( $this->target
->getName() )
463 $list = SpecialPage
::getTitleFor( 'Unblock', $this->target
->getName() );
465 $message = $this->msg( 'ipb-unblock' )->parse();
466 $list = SpecialPage
::getTitleFor( 'Unblock' );
468 $links[] = $linkRenderer->makeKnownLink(
470 new HtmlArmor( $message )
473 # Link to the block list
474 $links[] = $linkRenderer->makeKnownLink(
475 SpecialPage
::getTitleFor( 'BlockList' ),
476 $this->msg( 'ipb-blocklist' )->text()
479 $user = $this->getUser();
481 # Link to edit the block dropdown reasons, if applicable
482 if ( $user->isAllowed( 'editinterface' ) ) {
483 $links[] = $linkRenderer->makeKnownLink(
484 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
485 $this->msg( 'ipb-edit-dropdown' )->text(),
487 [ 'action' => 'edit' ]
491 $text = Html
::rawElement(
493 [ 'class' => 'mw-ipb-conveniencelinks' ],
494 $this->getLanguage()->pipeList( $links )
497 $userTitle = self
::getTargetUserTitle( $this->target
);
499 # Get relevant extracts from the block and suppression logs, if possible
502 LogEventsList
::showLogExtract(
509 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
510 'showIfEmpty' => false
515 # Add suppression block entries if allowed
516 if ( $user->isAllowed( 'suppressionlog' ) ) {
517 LogEventsList
::showLogExtract(
524 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
525 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
526 'showIfEmpty' => false
538 * Get a user page target for things like logs.
539 * This handles account and IP range targets.
540 * @param User|string $target
543 protected static function getTargetUserTitle( $target ) {
544 if ( $target instanceof User
) {
545 return $target->getUserPage();
546 } elseif ( IP
::isIPAddress( $target ) ) {
547 return Title
::makeTitleSafe( NS_USER
, $target );
554 * Determine the target of the block, and the type of target
555 * @todo Should be in Block.php?
556 * @param string $par Subpage parameter passed to setup, or data value from
558 * @param WebRequest|null $request Optionally try and get data from a request too
559 * @return array [ User|string|null, Block::TYPE_ constant|null ]
561 public static function getTargetAndType( $par, WebRequest
$request = null ) {
568 # The HTMLForm will check wpTarget first and only if it doesn't get
569 # a value use the default, which will be generated from the options
570 # below; so this has to have a higher precedence here than $par, or
571 # we could end up with different values in $this->target and the HTMLForm!
572 if ( $request instanceof WebRequest
) {
573 $target = $request->getText( 'wpTarget', null );
580 if ( $request instanceof WebRequest
) {
581 $target = $request->getText( 'ip', null );
586 if ( $request instanceof WebRequest
) {
587 $target = $request->getText( 'wpBlockAddress', null );
594 list( $target, $type ) = Block
::parseTarget( $target );
596 if ( $type !== null ) {
597 return [ $target, $type ];
601 return [ null, null ];
605 * HTMLForm field validation-callback for Target field.
607 * @param string $value
608 * @param array $alldata
609 * @param HTMLForm $form
612 public static function validateTargetField( $value, $alldata, $form ) {
613 $status = self
::validateTarget( $value, $form->getUser() );
614 if ( !$status->isOK() ) {
615 $errors = $status->getErrorsArray();
617 return $form->msg( ...$errors[0] );
624 * Validate a block target.
627 * @param string $value Block target to check
628 * @param User $user Performer of the block
631 public static function validateTarget( $value, User
$user ) {
632 global $wgBlockCIDRLimit;
634 /** @var User $target */
635 list( $target, $type ) = self
::getTargetAndType( $value );
636 $status = Status
::newGood( $target );
638 if ( $type == Block
::TYPE_USER
) {
639 if ( $target->isAnon() ) {
642 wfEscapeWikiText( $target->getName() )
646 $unblockStatus = self
::checkUnblockSelf( $target, $user );
647 if ( $unblockStatus !== true ) {
648 $status->fatal( 'badaccess', $unblockStatus );
650 } elseif ( $type == Block
::TYPE_RANGE
) {
651 list( $ip, $range ) = explode( '/', $target, 2 );
654 ( IP
::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
655 ( IP
::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
657 // Range block effectively disabled
658 $status->fatal( 'range_block_disabled' );
662 ( IP
::isIPv4( $ip ) && $range > 32 ) ||
663 ( IP
::isIPv6( $ip ) && $range > 128 )
666 $status->fatal( 'ip_range_invalid' );
669 if ( IP
::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
670 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
673 if ( IP
::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
674 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
676 } elseif ( $type == Block
::TYPE_IP
) {
679 $status->fatal( 'badipaddress' );
686 * Given the form data, actually implement a block. This is also called from ApiBlock.
689 * @param IContextSource $context
690 * @return bool|string
692 public static function processForm( array $data, IContextSource
$context ) {
693 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit;
695 $performer = $context->getUser();
696 $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
698 // Handled by field validator callback
699 // self::validateTargetField( $data['Target'] );
701 # This might have been a hidden field or a checkbox, so interesting data
703 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
705 /** @var User $target */
706 list( $target, $type ) = self
::getTargetAndType( $data['Target'] );
707 if ( $type == Block
::TYPE_USER
) {
709 $target = $user->getName();
710 $userId = $user->getId();
712 # Give admins a heads-up before they go and block themselves. Much messier
713 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
714 # permission anyway, although the code does allow for it.
715 # Note: Important to use $target instead of $data['Target']
716 # since both $data['PreviousTarget'] and $target are normalized
717 # but $data['target'] gets overridden by (non-normalized) request variable
718 # from previous request.
719 if ( $target === $performer->getName() &&
720 ( $data['PreviousTarget'] !== $target ||
!$data['Confirm'] )
722 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
724 } elseif ( $type == Block
::TYPE_RANGE
) {
727 } elseif ( $type == Block
::TYPE_IP
) {
729 $target = $target->getName();
732 # This should have been caught in the form field validation
733 return [ 'badipaddress' ];
736 $expiryTime = self
::parseExpiryInput( $data['Expiry'] );
739 // an expiry time is needed
740 ( strlen( $data['Expiry'] ) == 0 ) ||
741 // can't be a larger string as 50 (it should be a time format in any way)
742 ( strlen( $data['Expiry'] ) > 50 ) ||
743 // check, if the time could be parsed
746 return [ 'ipb_expiry_invalid' ];
749 // an expiry time should be in the future, not in the
750 // past (wouldn't make any sense) - bug T123069
751 if ( $expiryTime < wfTimestampNow() ) {
752 return [ 'ipb_expiry_old' ];
755 if ( !isset( $data['DisableEmail'] ) ) {
756 $data['DisableEmail'] = false;
759 # If the user has done the form 'properly', they won't even have been given the
760 # option to suppress-block unless they have the 'hideuser' permission
761 if ( !isset( $data['HideUser'] ) ) {
762 $data['HideUser'] = false;
765 if ( $data['HideUser'] ) {
766 if ( !$performer->isAllowed( 'hideuser' ) ) {
767 # this codepath is unreachable except by a malicious user spoofing forms,
768 # or by race conditions (user has hideuser and block rights, loads block form,
769 # and loses hideuser rights before submission); so need to fail completely
770 # rather than just silently disable hiding
771 return [ 'badaccess-group0' ];
774 # Recheck params here...
775 if ( $type != Block
::TYPE_USER
) {
776 $data['HideUser'] = false; # IP users should not be hidden
777 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
779 return [ 'ipb_expiry_temp' ];
780 } elseif ( $wgHideUserContribLimit !== false
781 && $user->getEditCount() > $wgHideUserContribLimit
783 # Typically, the user should have a handful of edits.
784 # Disallow hiding users with many edits for performance.
785 return [ [ 'ipb_hide_invalid',
786 Message
::numParam( $wgHideUserContribLimit ) ] ];
787 } elseif ( !$data['Confirm'] ) {
788 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
792 # Create block object.
793 $block = new Block();
794 $block->setTarget( $target );
795 $block->setBlocker( $performer );
796 $block->mReason
= $data['Reason'][0];
797 $block->mExpiry
= $expiryTime;
798 $block->prevents( 'createaccount', $data['CreateAccount'] );
799 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit ||
$data['DisableUTEdit'] ) );
800 $block->prevents( 'sendemail', $data['DisableEmail'] );
801 $block->isHardblock( $data['HardBlock'] );
802 $block->isAutoblocking( $data['AutoBlock'] );
803 $block->mHideName
= $data['HideUser'];
806 $enablePartialBlocks &&
807 isset( $data['EditingRestriction'] ) &&
808 $data['EditingRestriction'] === 'partial'
810 $block->isSitewide( false );
813 $reason = [ 'hookaborted' ];
814 if ( !Hooks
::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
819 if ( $enablePartialBlocks ) {
820 if ( !empty( $data['PageRestrictions'] ) ) {
821 $restrictions = array_map( function ( $text ) {
822 $title = Title
::newFromText( $text );
823 // Use the link cache since the title has already been loaded when
824 // the field was validated.
825 $restriction = new PageRestriction( 0, $title->getArticleId() );
826 $restriction->setTitle( $title );
828 }, explode( "\n", $data['PageRestrictions'] ) );
831 $block->setRestrictions( $restrictions );
835 # Try to insert block. Is there a conflicting block?
836 $status = $block->insert();
838 # Indicates whether the user is confirming the block and is aware of
839 # the conflict (did not change the block target in the meantime)
840 $blockNotConfirmed = !$data['Confirm'] ||
( array_key_exists( 'PreviousTarget', $data )
841 && $data['PreviousTarget'] !== $target );
843 # Special case for API - T34434
844 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
846 # Show form unless the user is already aware of this...
847 if ( $blockNotConfirmed ||
$reblockNotAllowed ) {
848 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
849 # Otherwise, try to update the block...
851 # This returns direct blocks before autoblocks/rangeblocks, since we should
852 # be sure the user is blocked by now it should work for our purposes
853 $currentBlock = Block
::newFromTarget( $target );
854 if ( $block->equals( $currentBlock ) ) {
855 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
857 # If the name was hidden and the blocking user cannot hide
858 # names, then don't allow any block changes...
859 if ( $currentBlock->mHideName
&& !$performer->isAllowed( 'hideuser' ) ) {
860 return [ 'cant-see-hidden-user' ];
863 $priorBlock = clone $currentBlock;
864 $currentBlock->isHardblock( $block->isHardblock() );
865 $currentBlock->prevents( 'createaccount', $block->prevents( 'createaccount' ) );
866 $currentBlock->mExpiry
= $block->mExpiry
;
867 $currentBlock->isAutoblocking( $block->isAutoblocking() );
868 $currentBlock->mHideName
= $block->mHideName
;
869 $currentBlock->prevents( 'sendemail', $block->prevents( 'sendemail' ) );
870 $currentBlock->prevents( 'editownusertalk', $block->prevents( 'editownusertalk' ) );
871 $currentBlock->mReason
= $block->mReason
;
873 if ( $enablePartialBlocks ) {
874 // Maintain the sitewide status. If partial blocks is not enabled,
875 // saving the block will result in a sitewide block.
876 $currentBlock->isSitewide( $block->isSitewide() );
878 // Set the block id of the restrictions.
879 $currentBlock->setRestrictions(
880 BlockRestriction
::setBlockId( $currentBlock->getId(), $restrictions )
884 $status = $currentBlock->update();
886 $logaction = 'reblock';
888 # Unset _deleted fields if requested
889 if ( $currentBlock->mHideName
&& !$data['HideUser'] ) {
890 RevisionDeleteUser
::unsuppressUserName( $target, $userId );
893 # If hiding/unhiding a name, this should go in the private logs
894 if ( (bool)$currentBlock->mHideName
) {
895 $data['HideUser'] = true;
899 $logaction = 'block';
902 Hooks
::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
904 # Set *_deleted fields if requested
905 if ( $data['HideUser'] ) {
906 RevisionDeleteUser
::suppressUserName( $target, $userId );
909 # Can't watch a rangeblock
910 if ( $type != Block
::TYPE_RANGE
&& $data['Watch'] ) {
911 WatchAction
::doWatch(
912 Title
::makeTitle( NS_USER
, $target ),
914 User
::IGNORE_USER_RIGHTS
918 # Block constructor sanitizes certain block options on insert
919 $data['BlockEmail'] = $block->prevents( 'sendemail' );
920 $data['AutoBlock'] = $block->isAutoblocking();
922 # Prepare log parameters
924 $logParams['5::duration'] = $data['Expiry'];
925 $logParams['6::flags'] = self
::blockLogFlags( $data, $type );
926 $logParams['sitewide'] = $block->isSitewide();
928 if ( $enablePartialBlocks && !empty( $data['PageRestrictions'] ) ) {
929 $logParams['7::restrictions'] = [
930 'pages' => explode( "\n", $data['PageRestrictions'] ),
934 # Make log entry, if the name is hidden, put it in the suppression log
935 $log_type = $data['HideUser'] ?
'suppress' : 'block';
936 $logEntry = new ManualLogEntry( $log_type, $logaction );
937 $logEntry->setTarget( Title
::makeTitle( NS_USER
, $target ) );
938 $logEntry->setComment( $data['Reason'][0] );
939 $logEntry->setPerformer( $performer );
940 $logEntry->setParameters( $logParams );
941 # Relate log ID to block IDs (T27763)
942 $blockIds = array_merge( [ $status['id'] ], $status['autoIds'] );
943 $logEntry->setRelations( [ 'ipb_id' => $blockIds ] );
944 $logId = $logEntry->insert();
946 if ( !empty( $data['Tags'] ) ) {
947 $logEntry->setTags( $data['Tags'] );
950 $logEntry->publish( $logId );
956 * Get an array of suggested block durations from MediaWiki:Ipboptions
957 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
958 * to the standard "**<duration>|<displayname>" format?
959 * @param Language|null $lang The language to get the durations in, or null to use
960 * the wiki's content language
961 * @param bool $includeOther Whether to include the 'other' option in the list of
965 public static function getSuggestedDurations( Language
$lang = null, $includeOther = true ) {
967 $msg = $lang === null
968 ?
wfMessage( 'ipboptions' )->inContentLanguage()->text()
969 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
975 foreach ( explode( ',', $msg ) as $option ) {
976 if ( strpos( $option, ':' ) === false ) {
977 $option = "$option:$option";
980 list( $show, $value ) = explode( ':', $option );
984 if ( $a && $includeOther ) {
985 // if options exist, add other to the end instead of the begining (which
986 // is what happens by default).
987 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
994 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
995 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
997 * @todo strtotime() only accepts English strings. This means the expiry input
998 * can only be specified in English.
999 * @see https://secure.php.net/manual/en/function.strtotime.php
1001 * @param string $expiry Whatever was typed into the form
1002 * @return string|bool Timestamp or 'infinity' or false on error.
1004 public static function parseExpiryInput( $expiry ) {
1005 if ( wfIsInfinity( $expiry ) ) {
1009 $expiry = strtotime( $expiry );
1011 if ( $expiry < 0 ||
$expiry === false ) {
1015 return wfTimestamp( TS_MW
, $expiry );
1019 * Can we do an email block?
1020 * @param User $user The sysop wanting to make a block
1023 public static function canBlockEmail( $user ) {
1024 global $wgEnableUserEmail, $wgSysopEmailBans;
1026 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1030 * T17810: blocked admins should not be able to block/unblock
1031 * others, and probably shouldn't be able to unblock themselves
1034 * Exception: Users can block the user who blocked them, to reduce
1035 * advantage of a malicious account blocking all admins (T150826)
1037 * @param User|int|string $user Target to block or unblock
1038 * @param User $performer User doing the request
1039 * @return bool|string True or error message key
1041 public static function checkUnblockSelf( $user, User
$performer ) {
1042 if ( is_int( $user ) ) {
1043 $user = User
::newFromId( $user );
1044 } elseif ( is_string( $user ) ) {
1045 $user = User
::newFromName( $user );
1047 if ( $performer->isBlocked() ) {
1048 if ( $user instanceof User
&& $user->getId() == $performer->getId() ) {
1049 # User is trying to unblock themselves
1050 if ( $performer->isAllowed( 'unblockself' ) ) {
1052 # User blocked themselves and is now trying to reverse it
1053 } elseif ( $performer->blockedBy() === $performer->getName() ) {
1056 return 'ipbnounblockself';
1059 $user instanceof User
&&
1060 $performer->getBlock() instanceof Block
&&
1061 $performer->getBlock()->getBy() &&
1062 $performer->getBlock()->getBy() === $user->getId()
1064 // Allow users to block the user that blocked them.
1065 // This is to prevent a situation where a malicious user
1066 // blocks all other users. This way, the non-malicious
1067 // user can block the malicious user back, resulting
1072 # User is trying to block/unblock someone else
1073 return 'ipbblocked';
1081 * Return a comma-delimited list of "flags" to be passed to the log
1082 * reader for this block, to provide more information in the logs
1083 * @param array $data From HTMLForm data
1084 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
1087 protected static function blockLogFlags( array $data, $type ) {
1088 $config = RequestContext
::getMain()->getConfig();
1090 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1094 # when blocking a user the option 'anononly' is not available/has no effect
1095 # -> do not write this into log
1096 if ( !$data['HardBlock'] && $type != Block
::TYPE_USER
) {
1097 // For grepping: message block-log-flags-anononly
1098 $flags[] = 'anononly';
1101 if ( $data['CreateAccount'] ) {
1102 // For grepping: message block-log-flags-nocreate
1103 $flags[] = 'nocreate';
1106 # Same as anononly, this is not displayed when blocking an IP address
1107 if ( !$data['AutoBlock'] && $type == Block
::TYPE_USER
) {
1108 // For grepping: message block-log-flags-noautoblock
1109 $flags[] = 'noautoblock';
1112 if ( $data['DisableEmail'] ) {
1113 // For grepping: message block-log-flags-noemail
1114 $flags[] = 'noemail';
1117 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1118 // For grepping: message block-log-flags-nousertalk
1119 $flags[] = 'nousertalk';
1122 if ( $data['HideUser'] ) {
1123 // For grepping: message block-log-flags-hiddenname
1124 $flags[] = 'hiddenname';
1127 return implode( ',', $flags );
1131 * Process the form on POST submission.
1132 * @param array $data
1133 * @param HTMLForm|null $form
1134 * @return bool|array True for success, false for didn't-try, array of errors on failure
1136 public function onSubmit( array $data, HTMLForm
$form = null ) {
1137 return self
::processForm( $data, $form->getContext() );
1141 * Do something exciting on successful processing of the form, most likely to show a
1142 * confirmation message
1144 public function onSuccess() {
1145 $out = $this->getOutput();
1146 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1147 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target
) );
1151 * Return an array of subpages beginning with $search that this special page will accept.
1153 * @param string $search Prefix to search for
1154 * @param int $limit Maximum number of results to return (usually 10)
1155 * @param int $offset Number of results to skip (usually 0)
1156 * @return string[] Matching subpages
1158 public function prefixSearchSubpages( $search, $limit, $offset ) {
1159 $user = User
::newFromName( $search );
1161 // No prefix suggestion for invalid user
1164 // Autocomplete subpage as user list - public to allow caching
1165 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
1168 protected function getGroupName() {