3 * Implements Special:Block
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
24 use MediaWiki\Block\BlockRestriction
;
25 use MediaWiki\Block\Restriction\PageRestriction
;
28 * A special page that allows users with 'block' right to block users from
29 * editing pages and other actions
31 * @ingroup SpecialPage
33 class SpecialBlock
extends FormSpecialPage
{
34 /** @var User|string|null User to be blocked, as passed either by parameter (url?wpTarget=Foo)
35 * or as subpage (Special:Block/Foo) */
38 /** @var int Block::TYPE_ constant */
41 /** @var User|string The previous block target */
42 protected $previousTarget;
44 /** @var bool Whether the previous submission of the form asked for HideUser */
45 protected $requestedHideUser;
48 protected $alreadyBlocked;
51 protected $preErrors = [];
53 public function __construct() {
54 parent
::__construct( 'Block', 'block' );
57 public function doesWrites() {
62 * Checks that the user can unblock themselves if they are trying to do so
65 * @throws ErrorPageError
67 protected function checkExecutePermissions( User
$user ) {
68 parent
::checkExecutePermissions( $user );
70 # T17810: blocked admins should have limited access here
71 $status = self
::checkUnblockSelf( $this->target
, $user );
72 if ( $status !== true ) {
73 throw new ErrorPageError( 'badaccess', $status );
78 * Handle some magic here
82 protected function setParameter( $par ) {
83 # Extract variables from the request. Try not to get into a situation where we
84 # need to extract *every* variable from the form just for processing here, but
85 # there are legitimate uses for some variables
86 $request = $this->getRequest();
87 list( $this->target
, $this->type
) = self
::getTargetAndType( $par, $request );
88 if ( $this->target
instanceof User
) {
89 # Set the 'relevant user' in the skin, so it displays links like Contributions,
90 # User logs, UserRights, etc.
91 $this->getSkin()->setRelevantUser( $this->target
);
94 list( $this->previousTarget
, /*...*/ ) =
95 Block
::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
96 $this->requestedHideUser
= $request->getBool( 'wpHideUser' );
100 * Customizes the HTMLForm a bit
102 * @param HTMLForm $form
104 protected function alterForm( HTMLForm
$form ) {
105 $form->setHeaderText( '' );
106 $form->setSubmitDestructive();
108 $msg = $this->alreadyBlocked ?
'ipb-change-block' : 'ipbsubmit';
109 $form->setSubmitTextMsg( $msg );
111 $this->addHelpLink( 'Help:Blocking users' );
113 # Don't need to do anything if the form has been posted
114 if ( !$this->getRequest()->wasPosted() && $this->preErrors
) {
115 $s = $form->formatErrors( $this->preErrors
);
117 $form->addHeaderText( Html
::rawElement(
119 [ 'class' => 'error' ],
126 protected function getDisplayFormat() {
131 * Get the HTMLForm descriptor array for the block form
134 protected function getFormFields() {
135 global $wgBlockAllowsUTEdit;
137 $user = $this->getUser();
139 $suggestedDurations = self
::getSuggestedDurations();
141 $conf = $this->getConfig();
142 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
143 $enablePartialBlocks = $conf->get( 'EnablePartialBlocks' );
151 'label-message' => 'ipaddressorusername',
152 'id' => 'mw-bi-target',
156 'validation-callback' => [ __CLASS__
, 'validateTargetField' ],
159 if ( $enablePartialBlocks ) {
160 $a['EditingRestriction'] = [
162 'label' => $this->msg( 'ipb-type-label' )->text(),
164 $this->msg( 'ipb-sitewide' )->text() => 'sitewide',
165 $this->msg( 'ipb-partial' )->text() => 'partial',
168 $a['PageRestrictions'] = [
169 'type' => 'titlesmultiselect',
170 'label' => $this->msg( 'ipb-pages-label' )->text(),
173 'cssclass' => 'mw-block-page-restrictions',
179 'label-message' => 'ipbexpiry',
181 'options' => $suggestedDurations,
182 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
186 'type' => 'selectandother',
187 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
188 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
189 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
190 'maxlength' => $oldCommentSchema ?
255 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
191 'maxlength-unit' => 'codepoints',
192 'label-message' => 'ipbreason',
193 'options-message' => 'ipbreason-dropdown',
196 $a['CreateAccount'] = [
198 'label-message' => 'ipbcreateaccount',
202 if ( self
::canBlockEmail( $user ) ) {
203 $a['DisableEmail'] = [
205 'label-message' => 'ipbemailban',
209 if ( $wgBlockAllowsUTEdit ) {
210 $a['DisableUTEdit'] = [
212 'label-message' => 'ipb-disableusertalk',
219 'label-message' => 'ipbenableautoblock',
223 # Allow some users to hide name from block log, blocklist and listusers
224 if ( $user->isAllowed( 'hideuser' ) ) {
227 'label-message' => 'ipbhidename',
228 'cssclass' => 'mw-block-hideuser',
232 # Watchlist their user page? (Only if user is logged in)
233 if ( $user->isLoggedIn() ) {
236 'label-message' => 'ipbwatchuser',
242 'label-message' => 'ipb-hardblock',
246 # This is basically a copy of the Target field, but the user can't change it, so we
247 # can see if the warnings we maybe showed to the user before still apply
248 $a['PreviousTarget'] = [
253 # We'll turn this into a checkbox if we need to
257 'label-message' => 'ipb-confirm',
258 'cssclass' => 'mw-block-confirm',
261 $this->maybeAlterFormDefaults( $a );
263 // Allow extensions to add more fields
264 Hooks
::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
270 * If the user has already been blocked with similar settings, load that block
271 * and change the defaults for the form fields to match the existing settings.
272 * @param array &$fields HTMLForm descriptor array
273 * @return bool Whether fields were altered (that is, whether the target is
276 protected function maybeAlterFormDefaults( &$fields ) {
277 # This will be overwritten by request data
278 $fields['Target']['default'] = (string)$this->target
;
280 if ( $this->target
) {
281 $status = self
::validateTarget( $this->target
, $this->getUser() );
282 if ( !$status->isOK() ) {
283 $errors = $status->getErrorsArray();
284 $this->preErrors
= array_merge( $this->preErrors
, $errors );
289 $fields['PreviousTarget']['default'] = (string)$this->target
;
291 $block = Block
::newFromTarget( $this->target
);
293 if ( $block instanceof Block
&& !$block->mAuto
# The block exists and isn't an autoblock
294 && ( $this->type
!= Block
::TYPE_RANGE
# The block isn't a rangeblock
295 ||
$block->getTarget() == $this->target
) # or if it is, the range is what we're about to block
297 $fields['HardBlock']['default'] = $block->isHardblock();
298 $fields['CreateAccount']['default'] = $block->prevents( 'createaccount' );
299 $fields['AutoBlock']['default'] = $block->isAutoblocking();
301 if ( isset( $fields['DisableEmail'] ) ) {
302 $fields['DisableEmail']['default'] = $block->prevents( 'sendemail' );
305 if ( isset( $fields['HideUser'] ) ) {
306 $fields['HideUser']['default'] = $block->mHideName
;
309 if ( isset( $fields['DisableUTEdit'] ) ) {
310 $fields['DisableUTEdit']['default'] = $block->prevents( 'editownusertalk' );
313 // If the username was hidden (ipb_deleted == 1), don't show the reason
314 // unless this user also has rights to hideuser: T37839
315 if ( !$block->mHideName ||
$this->getUser()->isAllowed( 'hideuser' ) ) {
316 $fields['Reason']['default'] = $block->mReason
;
318 $fields['Reason']['default'] = '';
321 if ( $this->getRequest()->wasPosted() ) {
322 # Ok, so we got a POST submission asking us to reblock a user. So show the
323 # confirm checkbox; the user will only see it if they haven't previously
324 $fields['Confirm']['type'] = 'check';
326 # We got a target, but it wasn't a POST request, so the user must have gone
327 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
328 # as long as they go ahead and block *that* user
329 $fields['Confirm']['default'] = 1;
332 if ( $block->mExpiry
== 'infinity' ) {
333 $fields['Expiry']['default'] = 'infinite';
335 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822
, $block->mExpiry
);
338 $this->alreadyBlocked
= true;
339 $this->preErrors
[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
342 # We always need confirmation to do HideUser
343 if ( $this->requestedHideUser
) {
344 $fields['Confirm']['type'] = 'check';
345 unset( $fields['Confirm']['default'] );
346 $this->preErrors
[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
349 # Or if the user is trying to block themselves
350 if ( (string)$this->target
=== $this->getUser()->getName() ) {
351 $fields['Confirm']['type'] = 'check';
352 unset( $fields['Confirm']['default'] );
353 $this->preErrors
[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
356 if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
357 if ( $block instanceof Block
&& !$block->isSitewide() ) {
358 $fields['EditingRestriction']['default'] = 'partial';
360 $fields['EditingRestriction']['default'] = 'sitewide';
363 if ( $block instanceof Block
) {
364 $pageRestrictions = [];
365 foreach ( $block->getRestrictions() as $restriction ) {
366 if ( $restriction->getType() !== 'page' ) {
370 $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
373 // Sort the restrictions so they are in alphabetical order.
374 sort( $pageRestrictions );
375 $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
381 * Add header elements like block log entries, etc.
384 protected function preText() {
385 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
387 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
388 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
390 $otherBlockMessages = [];
391 if ( $this->target
!== null ) {
392 $targetName = $this->target
;
393 if ( $this->target
instanceof User
) {
394 $targetName = $this->target
->getName();
396 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
397 Hooks
::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
399 if ( count( $otherBlockMessages ) ) {
400 $s = Html
::rawElement(
403 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
408 foreach ( $otherBlockMessages as $link ) {
409 $list .= Html
::rawElement( 'li', [], $link ) . "\n";
412 $s .= Html
::rawElement(
414 [ 'class' => 'mw-blockip-alreadyblocked' ],
426 * Add footer elements to the form
429 protected function postText() {
432 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
434 $linkRenderer = $this->getLinkRenderer();
435 # Link to the user's contributions, if applicable
436 if ( $this->target
instanceof User
) {
437 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $this->target
->getName() );
438 $links[] = $linkRenderer->makeLink(
440 $this->msg( 'ipb-blocklist-contribs', $this->target
->getName() )->text()
444 # Link to unblock the specified user, or to a blank unblock form
445 if ( $this->target
instanceof User
) {
446 $message = $this->msg(
448 wfEscapeWikiText( $this->target
->getName() )
450 $list = SpecialPage
::getTitleFor( 'Unblock', $this->target
->getName() );
452 $message = $this->msg( 'ipb-unblock' )->parse();
453 $list = SpecialPage
::getTitleFor( 'Unblock' );
455 $links[] = $linkRenderer->makeKnownLink(
457 new HtmlArmor( $message )
460 # Link to the block list
461 $links[] = $linkRenderer->makeKnownLink(
462 SpecialPage
::getTitleFor( 'BlockList' ),
463 $this->msg( 'ipb-blocklist' )->text()
466 $user = $this->getUser();
468 # Link to edit the block dropdown reasons, if applicable
469 if ( $user->isAllowed( 'editinterface' ) ) {
470 $links[] = $linkRenderer->makeKnownLink(
471 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
472 $this->msg( 'ipb-edit-dropdown' )->text(),
474 [ 'action' => 'edit' ]
478 $text = Html
::rawElement(
480 [ 'class' => 'mw-ipb-conveniencelinks' ],
481 $this->getLanguage()->pipeList( $links )
484 $userTitle = self
::getTargetUserTitle( $this->target
);
486 # Get relevant extracts from the block and suppression logs, if possible
489 LogEventsList
::showLogExtract(
496 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
497 'showIfEmpty' => false
502 # Add suppression block entries if allowed
503 if ( $user->isAllowed( 'suppressionlog' ) ) {
504 LogEventsList
::showLogExtract(
511 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
512 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
513 'showIfEmpty' => false
525 * Get a user page target for things like logs.
526 * This handles account and IP range targets.
527 * @param User|string $target
530 protected static function getTargetUserTitle( $target ) {
531 if ( $target instanceof User
) {
532 return $target->getUserPage();
533 } elseif ( IP
::isIPAddress( $target ) ) {
534 return Title
::makeTitleSafe( NS_USER
, $target );
541 * Determine the target of the block, and the type of target
542 * @todo Should be in Block.php?
543 * @param string $par Subpage parameter passed to setup, or data value from
545 * @param WebRequest|null $request Optionally try and get data from a request too
546 * @return array [ User|string|null, Block::TYPE_ constant|null ]
548 public static function getTargetAndType( $par, WebRequest
$request = null ) {
555 # The HTMLForm will check wpTarget first and only if it doesn't get
556 # a value use the default, which will be generated from the options
557 # below; so this has to have a higher precedence here than $par, or
558 # we could end up with different values in $this->target and the HTMLForm!
559 if ( $request instanceof WebRequest
) {
560 $target = $request->getText( 'wpTarget', null );
567 if ( $request instanceof WebRequest
) {
568 $target = $request->getText( 'ip', null );
573 if ( $request instanceof WebRequest
) {
574 $target = $request->getText( 'wpBlockAddress', null );
581 list( $target, $type ) = Block
::parseTarget( $target );
583 if ( $type !== null ) {
584 return [ $target, $type ];
588 return [ null, null ];
592 * HTMLForm field validation-callback for Target field.
594 * @param string $value
595 * @param array $alldata
596 * @param HTMLForm $form
599 public static function validateTargetField( $value, $alldata, $form ) {
600 $status = self
::validateTarget( $value, $form->getUser() );
601 if ( !$status->isOK() ) {
602 $errors = $status->getErrorsArray();
604 return $form->msg( ...$errors[0] );
611 * Validate a block target.
614 * @param string $value Block target to check
615 * @param User $user Performer of the block
618 public static function validateTarget( $value, User
$user ) {
619 global $wgBlockCIDRLimit;
621 /** @var User $target */
622 list( $target, $type ) = self
::getTargetAndType( $value );
623 $status = Status
::newGood( $target );
625 if ( $type == Block
::TYPE_USER
) {
626 if ( $target->isAnon() ) {
629 wfEscapeWikiText( $target->getName() )
633 $unblockStatus = self
::checkUnblockSelf( $target, $user );
634 if ( $unblockStatus !== true ) {
635 $status->fatal( 'badaccess', $unblockStatus );
637 } elseif ( $type == Block
::TYPE_RANGE
) {
638 list( $ip, $range ) = explode( '/', $target, 2 );
641 ( IP
::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
642 ( IP
::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
644 // Range block effectively disabled
645 $status->fatal( 'range_block_disabled' );
649 ( IP
::isIPv4( $ip ) && $range > 32 ) ||
650 ( IP
::isIPv6( $ip ) && $range > 128 )
653 $status->fatal( 'ip_range_invalid' );
656 if ( IP
::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
657 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
660 if ( IP
::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
661 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
663 } elseif ( $type == Block
::TYPE_IP
) {
666 $status->fatal( 'badipaddress' );
673 * Given the form data, actually implement a block. This is also called from ApiBlock.
676 * @param IContextSource $context
677 * @return bool|string
679 public static function processForm( array $data, IContextSource
$context ) {
680 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit;
682 $performer = $context->getUser();
683 $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
685 // Handled by field validator callback
686 // self::validateTargetField( $data['Target'] );
688 # This might have been a hidden field or a checkbox, so interesting data
690 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
692 /** @var User $target */
693 list( $target, $type ) = self
::getTargetAndType( $data['Target'] );
694 if ( $type == Block
::TYPE_USER
) {
696 $target = $user->getName();
697 $userId = $user->getId();
699 # Give admins a heads-up before they go and block themselves. Much messier
700 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
701 # permission anyway, although the code does allow for it.
702 # Note: Important to use $target instead of $data['Target']
703 # since both $data['PreviousTarget'] and $target are normalized
704 # but $data['target'] gets overridden by (non-normalized) request variable
705 # from previous request.
706 if ( $target === $performer->getName() &&
707 ( $data['PreviousTarget'] !== $target ||
!$data['Confirm'] )
709 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
711 } elseif ( $type == Block
::TYPE_RANGE
) {
714 } elseif ( $type == Block
::TYPE_IP
) {
716 $target = $target->getName();
719 # This should have been caught in the form field validation
720 return [ 'badipaddress' ];
723 $expiryTime = self
::parseExpiryInput( $data['Expiry'] );
726 // an expiry time is needed
727 ( strlen( $data['Expiry'] ) == 0 ) ||
728 // can't be a larger string as 50 (it should be a time format in any way)
729 ( strlen( $data['Expiry'] ) > 50 ) ||
730 // check, if the time could be parsed
733 return [ 'ipb_expiry_invalid' ];
736 // an expiry time should be in the future, not in the
737 // past (wouldn't make any sense) - bug T123069
738 if ( $expiryTime < wfTimestampNow() ) {
739 return [ 'ipb_expiry_old' ];
742 if ( !isset( $data['DisableEmail'] ) ) {
743 $data['DisableEmail'] = false;
746 # If the user has done the form 'properly', they won't even have been given the
747 # option to suppress-block unless they have the 'hideuser' permission
748 if ( !isset( $data['HideUser'] ) ) {
749 $data['HideUser'] = false;
752 if ( $data['HideUser'] ) {
753 if ( !$performer->isAllowed( 'hideuser' ) ) {
754 # this codepath is unreachable except by a malicious user spoofing forms,
755 # or by race conditions (user has hideuser and block rights, loads block form,
756 # and loses hideuser rights before submission); so need to fail completely
757 # rather than just silently disable hiding
758 return [ 'badaccess-group0' ];
761 # Recheck params here...
762 if ( $type != Block
::TYPE_USER
) {
763 $data['HideUser'] = false; # IP users should not be hidden
764 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
766 return [ 'ipb_expiry_temp' ];
767 } elseif ( $wgHideUserContribLimit !== false
768 && $user->getEditCount() > $wgHideUserContribLimit
770 # Typically, the user should have a handful of edits.
771 # Disallow hiding users with many edits for performance.
772 return [ [ 'ipb_hide_invalid',
773 Message
::numParam( $wgHideUserContribLimit ) ] ];
774 } elseif ( !$data['Confirm'] ) {
775 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
779 # Create block object.
780 $block = new Block();
781 $block->setTarget( $target );
782 $block->setBlocker( $performer );
783 $block->mReason
= $data['Reason'][0];
784 $block->mExpiry
= $expiryTime;
785 $block->prevents( 'createaccount', $data['CreateAccount'] );
786 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit ||
$data['DisableUTEdit'] ) );
787 $block->prevents( 'sendemail', $data['DisableEmail'] );
788 $block->isHardblock( $data['HardBlock'] );
789 $block->isAutoblocking( $data['AutoBlock'] );
790 $block->mHideName
= $data['HideUser'];
793 $enablePartialBlocks &&
794 isset( $data['EditingRestriction'] ) &&
795 $data['EditingRestriction'] === 'partial'
797 $block->isSitewide( false );
800 $reason = [ 'hookaborted' ];
801 if ( !Hooks
::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
806 if ( $enablePartialBlocks ) {
807 if ( !empty( $data['PageRestrictions'] ) ) {
808 $restrictions = array_map( function ( $text ) {
809 $title = Title
::newFromText( $text );
810 // Use the link cache since the title has already been loaded when
811 // the field was validated.
812 $restriction = new PageRestriction( 0, $title->getArticleId() );
813 $restriction->setTitle( $title );
815 }, explode( "\n", $data['PageRestrictions'] ) );
818 $block->setRestrictions( $restrictions );
822 # Try to insert block. Is there a conflicting block?
823 $status = $block->insert();
825 # Indicates whether the user is confirming the block and is aware of
826 # the conflict (did not change the block target in the meantime)
827 $blockNotConfirmed = !$data['Confirm'] ||
( array_key_exists( 'PreviousTarget', $data )
828 && $data['PreviousTarget'] !== $target );
830 # Special case for API - T34434
831 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
833 # Show form unless the user is already aware of this...
834 if ( $blockNotConfirmed ||
$reblockNotAllowed ) {
835 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
836 # Otherwise, try to update the block...
838 # This returns direct blocks before autoblocks/rangeblocks, since we should
839 # be sure the user is blocked by now it should work for our purposes
840 $currentBlock = Block
::newFromTarget( $target );
841 if ( $block->equals( $currentBlock ) ) {
842 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
844 # If the name was hidden and the blocking user cannot hide
845 # names, then don't allow any block changes...
846 if ( $currentBlock->mHideName
&& !$performer->isAllowed( 'hideuser' ) ) {
847 return [ 'cant-see-hidden-user' ];
850 $priorBlock = clone $currentBlock;
851 $currentBlock->isHardblock( $block->isHardblock() );
852 $currentBlock->prevents( 'createaccount', $block->prevents( 'createaccount' ) );
853 $currentBlock->mExpiry
= $block->mExpiry
;
854 $currentBlock->isAutoblocking( $block->isAutoblocking() );
855 $currentBlock->mHideName
= $block->mHideName
;
856 $currentBlock->prevents( 'sendemail', $block->prevents( 'sendemail' ) );
857 $currentBlock->prevents( 'editownusertalk', $block->prevents( 'editownusertalk' ) );
858 $currentBlock->mReason
= $block->mReason
;
860 if ( $enablePartialBlocks ) {
861 // Maintain the sitewide status. If partial blocks is not enabled,
862 // saving the block will result in a sitewide block.
863 $currentBlock->isSitewide( $block->isSitewide() );
865 // Set the block id of the restrictions.
866 $currentBlock->setRestrictions(
867 BlockRestriction
::setBlockId( $currentBlock->getId(), $restrictions )
871 $status = $currentBlock->update();
873 $logaction = 'reblock';
875 # Unset _deleted fields if requested
876 if ( $currentBlock->mHideName
&& !$data['HideUser'] ) {
877 RevisionDeleteUser
::unsuppressUserName( $target, $userId );
880 # If hiding/unhiding a name, this should go in the private logs
881 if ( (bool)$currentBlock->mHideName
) {
882 $data['HideUser'] = true;
886 $logaction = 'block';
889 Hooks
::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
891 # Set *_deleted fields if requested
892 if ( $data['HideUser'] ) {
893 RevisionDeleteUser
::suppressUserName( $target, $userId );
896 # Can't watch a rangeblock
897 if ( $type != Block
::TYPE_RANGE
&& $data['Watch'] ) {
898 WatchAction
::doWatch(
899 Title
::makeTitle( NS_USER
, $target ),
901 User
::IGNORE_USER_RIGHTS
905 # Block constructor sanitizes certain block options on insert
906 $data['BlockEmail'] = $block->prevents( 'sendemail' );
907 $data['AutoBlock'] = $block->isAutoblocking();
909 # Prepare log parameters
911 $logParams['5::duration'] = $data['Expiry'];
912 $logParams['6::flags'] = self
::blockLogFlags( $data, $type );
913 $logParams['sitewide'] = $block->isSitewide();
915 if ( $enablePartialBlocks && !empty( $data['PageRestrictions'] ) ) {
916 $logParams['7::restrictions'] = [
917 'pages' => explode( "\n", $data['PageRestrictions'] ),
921 # Make log entry, if the name is hidden, put it in the suppression log
922 $log_type = $data['HideUser'] ?
'suppress' : 'block';
923 $logEntry = new ManualLogEntry( $log_type, $logaction );
924 $logEntry->setTarget( Title
::makeTitle( NS_USER
, $target ) );
925 $logEntry->setComment( $data['Reason'][0] );
926 $logEntry->setPerformer( $performer );
927 $logEntry->setParameters( $logParams );
928 # Relate log ID to block IDs (T27763)
929 $blockIds = array_merge( [ $status['id'] ], $status['autoIds'] );
930 $logEntry->setRelations( [ 'ipb_id' => $blockIds ] );
931 $logId = $logEntry->insert();
933 if ( !empty( $data['Tags'] ) ) {
934 $logEntry->setTags( $data['Tags'] );
937 $logEntry->publish( $logId );
943 * Get an array of suggested block durations from MediaWiki:Ipboptions
944 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
945 * to the standard "**<duration>|<displayname>" format?
946 * @param Language|null $lang The language to get the durations in, or null to use
947 * the wiki's content language
948 * @param bool $includeOther Whether to include the 'other' option in the list of
952 public static function getSuggestedDurations( Language
$lang = null, $includeOther = true ) {
954 $msg = $lang === null
955 ?
wfMessage( 'ipboptions' )->inContentLanguage()->text()
956 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
962 foreach ( explode( ',', $msg ) as $option ) {
963 if ( strpos( $option, ':' ) === false ) {
964 $option = "$option:$option";
967 list( $show, $value ) = explode( ':', $option );
971 if ( $a && $includeOther ) {
972 // if options exist, add other to the end instead of the begining (which
973 // is what happens by default).
974 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
981 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
982 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
984 * @todo strtotime() only accepts English strings. This means the expiry input
985 * can only be specified in English.
986 * @see https://secure.php.net/manual/en/function.strtotime.php
988 * @param string $expiry Whatever was typed into the form
989 * @return string|bool Timestamp or 'infinity' or false on error.
991 public static function parseExpiryInput( $expiry ) {
992 if ( wfIsInfinity( $expiry ) ) {
996 $expiry = strtotime( $expiry );
998 if ( $expiry < 0 ||
$expiry === false ) {
1002 return wfTimestamp( TS_MW
, $expiry );
1006 * Can we do an email block?
1007 * @param User $user The sysop wanting to make a block
1010 public static function canBlockEmail( $user ) {
1011 global $wgEnableUserEmail, $wgSysopEmailBans;
1013 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1017 * T17810: blocked admins should not be able to block/unblock
1018 * others, and probably shouldn't be able to unblock themselves
1020 * @param User|int|string $user
1021 * @param User $performer User doing the request
1022 * @return bool|string True or error message key
1024 public static function checkUnblockSelf( $user, User
$performer ) {
1025 if ( is_int( $user ) ) {
1026 $user = User
::newFromId( $user );
1027 } elseif ( is_string( $user ) ) {
1028 $user = User
::newFromName( $user );
1031 if ( $performer->isBlocked() ) {
1032 if ( $user instanceof User
&& $user->getId() == $performer->getId() ) {
1033 # User is trying to unblock themselves
1034 if ( $performer->isAllowed( 'unblockself' ) ) {
1036 # User blocked themselves and is now trying to reverse it
1037 } elseif ( $performer->blockedBy() === $performer->getName() ) {
1040 return 'ipbnounblockself';
1043 # User is trying to block/unblock someone else
1044 return 'ipbblocked';
1052 * Return a comma-delimited list of "flags" to be passed to the log
1053 * reader for this block, to provide more information in the logs
1054 * @param array $data From HTMLForm data
1055 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
1058 protected static function blockLogFlags( array $data, $type ) {
1059 $config = RequestContext
::getMain()->getConfig();
1061 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1065 # when blocking a user the option 'anononly' is not available/has no effect
1066 # -> do not write this into log
1067 if ( !$data['HardBlock'] && $type != Block
::TYPE_USER
) {
1068 // For grepping: message block-log-flags-anononly
1069 $flags[] = 'anononly';
1072 if ( $data['CreateAccount'] ) {
1073 // For grepping: message block-log-flags-nocreate
1074 $flags[] = 'nocreate';
1077 # Same as anononly, this is not displayed when blocking an IP address
1078 if ( !$data['AutoBlock'] && $type == Block
::TYPE_USER
) {
1079 // For grepping: message block-log-flags-noautoblock
1080 $flags[] = 'noautoblock';
1083 if ( $data['DisableEmail'] ) {
1084 // For grepping: message block-log-flags-noemail
1085 $flags[] = 'noemail';
1088 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1089 // For grepping: message block-log-flags-nousertalk
1090 $flags[] = 'nousertalk';
1093 if ( $data['HideUser'] ) {
1094 // For grepping: message block-log-flags-hiddenname
1095 $flags[] = 'hiddenname';
1098 return implode( ',', $flags );
1102 * Process the form on POST submission.
1103 * @param array $data
1104 * @param HTMLForm|null $form
1105 * @return bool|array True for success, false for didn't-try, array of errors on failure
1107 public function onSubmit( array $data, HTMLForm
$form = null ) {
1108 return self
::processForm( $data, $form->getContext() );
1112 * Do something exciting on successful processing of the form, most likely to show a
1113 * confirmation message
1115 public function onSuccess() {
1116 $out = $this->getOutput();
1117 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1118 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target
) );
1122 * Return an array of subpages beginning with $search that this special page will accept.
1124 * @param string $search Prefix to search for
1125 * @param int $limit Maximum number of results to return (usually 10)
1126 * @param int $offset Number of results to skip (usually 0)
1127 * @return string[] Matching subpages
1129 public function prefixSearchSubpages( $search, $limit, $offset ) {
1130 $user = User
::newFromName( $search );
1132 // No prefix suggestion for invalid user
1135 // Autocomplete subpage as user list - public to allow caching
1136 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
1139 protected function getGroupName() {