Merge "Update docs/hooks.txt for ShowSearchHitTitle"
[mediawiki.git] / includes / specials / SpecialBlock.php
blob82f7d0843f6dac97f910ff4c91f0a1cb608a6367
1 <?php
2 /**
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
20 * @file
21 * @ingroup SpecialPage
24 /**
25 * A special page that allows users with 'block' right to block users from
26 * editing pages and other actions
28 * @ingroup SpecialPage
30 class SpecialBlock extends FormSpecialPage {
31 /** @var User|string|null User to be blocked, as passed either by parameter (url?wpTarget=Foo)
32 * or as subpage (Special:Block/Foo) */
33 protected $target;
35 /** @var int Block::TYPE_ constant */
36 protected $type;
38 /** @var User|string The previous block target */
39 protected $previousTarget;
41 /** @var bool Whether the previous submission of the form asked for HideUser */
42 protected $requestedHideUser;
44 /** @var bool */
45 protected $alreadyBlocked;
47 /** @var array */
48 protected $preErrors = [];
50 public function __construct() {
51 parent::__construct( 'Block', 'block' );
54 public function doesWrites() {
55 return true;
58 /**
59 * Checks that the user can unblock themselves if they are trying to do so
61 * @param User $user
62 * @throws ErrorPageError
64 protected function checkExecutePermissions( User $user ) {
65 parent::checkExecutePermissions( $user );
67 # bug 15810: blocked admins should have limited access here
68 $status = self::checkUnblockSelf( $this->target, $user );
69 if ( $status !== true ) {
70 throw new ErrorPageError( 'badaccess', $status );
74 /**
75 * Handle some magic here
77 * @param string $par
79 protected function setParameter( $par ) {
80 # Extract variables from the request. Try not to get into a situation where we
81 # need to extract *every* variable from the form just for processing here, but
82 # there are legitimate uses for some variables
83 $request = $this->getRequest();
84 list( $this->target, $this->type ) = self::getTargetAndType( $par, $request );
85 if ( $this->target instanceof User ) {
86 # Set the 'relevant user' in the skin, so it displays links like Contributions,
87 # User logs, UserRights, etc.
88 $this->getSkin()->setRelevantUser( $this->target );
91 list( $this->previousTarget, /*...*/ ) =
92 Block::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
93 $this->requestedHideUser = $request->getBool( 'wpHideUser' );
96 /**
97 * Customizes the HTMLForm a bit
99 * @param HTMLForm $form
101 protected function alterForm( HTMLForm $form ) {
102 $form->setWrapperLegendMsg( 'blockip-legend' );
103 $form->setHeaderText( '' );
104 $form->setSubmitDestructive();
106 $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
107 $form->setSubmitTextMsg( $msg );
109 $this->addHelpLink( 'Help:Blocking users' );
111 # Don't need to do anything if the form has been posted
112 if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
113 $s = $form->formatErrors( $this->preErrors );
114 if ( $s ) {
115 $form->addHeaderText( Html::rawElement(
116 'div',
117 [ 'class' => 'error' ],
119 ) );
125 * Get the HTMLForm descriptor array for the block form
126 * @return array
128 protected function getFormFields() {
129 global $wgBlockAllowsUTEdit;
130 if ( !wfMessage( 'ipbreason-dropdown' )->inContentLanguage()->isDisabled() ) {
131 $reasonsList = Xml::getArrayFromWikiTextList(
132 wfMessage( 'ipbreason-dropdown' )->inContentLanguage()->text()
134 $this->getOutput()->addModules( 'mediawiki.reasonSuggest' );
135 $this->getOutput()->addJsConfigVars( [
136 'reasons' => $reasonsList
137 ] );
139 $user = $this->getUser();
141 $suggestedDurations = self::getSuggestedDurations();
143 $a = [
144 'Target' => [
145 'type' => 'text',
146 'label-message' => 'ipaddressorusername',
147 'id' => 'mw-bi-target',
148 'size' => '45',
149 'autofocus' => true,
150 'required' => true,
151 'validation-callback' => [ __CLASS__, 'validateTargetField' ],
152 'cssclass' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
154 'Expiry' => [
155 'type' => !count( $suggestedDurations ) ? 'text' : 'selectorother',
156 'label-message' => 'ipbexpiry',
157 'required' => true,
158 'options' => $suggestedDurations,
159 'other' => $this->msg( 'ipbother' )->text(),
160 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
162 'Reason' => [
163 'type' => 'selectandother',
164 'maxlength' => 255,
165 'label-message' => 'ipbreason',
166 'options-message' => 'ipbreason-dropdown',
168 'CreateAccount' => [
169 'type' => 'check',
170 'label-message' => 'ipbcreateaccount',
171 'default' => true,
175 if ( self::canBlockEmail( $user ) ) {
176 $a['DisableEmail'] = [
177 'type' => 'check',
178 'label-message' => 'ipbemailban',
182 if ( $wgBlockAllowsUTEdit ) {
183 $a['DisableUTEdit'] = [
184 'type' => 'check',
185 'label-message' => 'ipb-disableusertalk',
186 'default' => false,
190 $a['AutoBlock'] = [
191 'type' => 'check',
192 'label-message' => 'ipbenableautoblock',
193 'default' => true,
196 # Allow some users to hide name from block log, blocklist and listusers
197 if ( $user->isAllowed( 'hideuser' ) ) {
198 $a['HideUser'] = [
199 'type' => 'check',
200 'label-message' => 'ipbhidename',
201 'cssclass' => 'mw-block-hideuser',
205 # Watchlist their user page? (Only if user is logged in)
206 if ( $user->isLoggedIn() ) {
207 $a['Watch'] = [
208 'type' => 'check',
209 'label-message' => 'ipbwatchuser',
213 $a['HardBlock'] = [
214 'type' => 'check',
215 'label-message' => 'ipb-hardblock',
216 'default' => false,
219 # This is basically a copy of the Target field, but the user can't change it, so we
220 # can see if the warnings we maybe showed to the user before still apply
221 $a['PreviousTarget'] = [
222 'type' => 'hidden',
223 'default' => false,
226 # We'll turn this into a checkbox if we need to
227 $a['Confirm'] = [
228 'type' => 'hidden',
229 'default' => '',
230 'label-message' => 'ipb-confirm',
233 $this->maybeAlterFormDefaults( $a );
235 // Allow extensions to add more fields
236 Hooks::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
238 return $a;
242 * If the user has already been blocked with similar settings, load that block
243 * and change the defaults for the form fields to match the existing settings.
244 * @param array $fields HTMLForm descriptor array
245 * @return bool Whether fields were altered (that is, whether the target is
246 * already blocked)
248 protected function maybeAlterFormDefaults( &$fields ) {
249 # This will be overwritten by request data
250 $fields['Target']['default'] = (string)$this->target;
252 if ( $this->target ) {
253 $status = self::validateTarget( $this->target, $this->getUser() );
254 if ( !$status->isOK() ) {
255 $errors = $status->getErrorsArray();
256 $this->preErrors = array_merge( $this->preErrors, $errors );
260 # This won't be
261 $fields['PreviousTarget']['default'] = (string)$this->target;
263 $block = Block::newFromTarget( $this->target );
265 if ( $block instanceof Block && !$block->mAuto # The block exists and isn't an autoblock
266 && ( $this->type != Block::TYPE_RANGE # The block isn't a rangeblock
267 || $block->getTarget() == $this->target ) # or if it is, the range is what we're about to block
269 $fields['HardBlock']['default'] = $block->isHardblock();
270 $fields['CreateAccount']['default'] = $block->prevents( 'createaccount' );
271 $fields['AutoBlock']['default'] = $block->isAutoblocking();
273 if ( isset( $fields['DisableEmail'] ) ) {
274 $fields['DisableEmail']['default'] = $block->prevents( 'sendemail' );
277 if ( isset( $fields['HideUser'] ) ) {
278 $fields['HideUser']['default'] = $block->mHideName;
281 if ( isset( $fields['DisableUTEdit'] ) ) {
282 $fields['DisableUTEdit']['default'] = $block->prevents( 'editownusertalk' );
285 // If the username was hidden (ipb_deleted == 1), don't show the reason
286 // unless this user also has rights to hideuser: Bug 35839
287 if ( !$block->mHideName || $this->getUser()->isAllowed( 'hideuser' ) ) {
288 $fields['Reason']['default'] = $block->mReason;
289 } else {
290 $fields['Reason']['default'] = '';
293 if ( $this->getRequest()->wasPosted() ) {
294 # Ok, so we got a POST submission asking us to reblock a user. So show the
295 # confirm checkbox; the user will only see it if they haven't previously
296 $fields['Confirm']['type'] = 'check';
297 } else {
298 # We got a target, but it wasn't a POST request, so the user must have gone
299 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
300 # as long as they go ahead and block *that* user
301 $fields['Confirm']['default'] = 1;
304 if ( $block->mExpiry == 'infinity' ) {
305 $fields['Expiry']['default'] = 'infinite';
306 } else {
307 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->mExpiry );
310 $this->alreadyBlocked = true;
311 $this->preErrors[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
314 # We always need confirmation to do HideUser
315 if ( $this->requestedHideUser ) {
316 $fields['Confirm']['type'] = 'check';
317 unset( $fields['Confirm']['default'] );
318 $this->preErrors[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
321 # Or if the user is trying to block themselves
322 if ( (string)$this->target === $this->getUser()->getName() ) {
323 $fields['Confirm']['type'] = 'check';
324 unset( $fields['Confirm']['default'] );
325 $this->preErrors[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
330 * Add header elements like block log entries, etc.
331 * @return string
333 protected function preText() {
334 $this->getOutput()->addModules( [ 'mediawiki.special.block', 'mediawiki.userSuggest' ] );
336 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
337 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
339 $otherBlockMessages = [];
340 if ( $this->target !== null ) {
341 $targetName = $this->target;
342 if ( $this->target instanceof User ) {
343 $targetName = $this->target->getName();
345 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
346 Hooks::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
348 if ( count( $otherBlockMessages ) ) {
349 $s = Html::rawElement(
350 'h2',
352 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
353 ) . "\n";
355 $list = '';
357 foreach ( $otherBlockMessages as $link ) {
358 $list .= Html::rawElement( 'li', [], $link ) . "\n";
361 $s .= Html::rawElement(
362 'ul',
363 [ 'class' => 'mw-blockip-alreadyblocked' ],
364 $list
365 ) . "\n";
367 $text .= $s;
371 return $text;
375 * Add footer elements to the form
376 * @return string
378 protected function postText() {
379 $links = [];
381 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
383 $linkRenderer = $this->getLinkRenderer();
384 # Link to the user's contributions, if applicable
385 if ( $this->target instanceof User ) {
386 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
387 $links[] = $linkRenderer->makeLink(
388 $contribsPage,
389 $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->text()
393 # Link to unblock the specified user, or to a blank unblock form
394 if ( $this->target instanceof User ) {
395 $message = $this->msg(
396 'ipb-unblock-addr',
397 wfEscapeWikiText( $this->target->getName() )
398 )->parse();
399 $list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
400 } else {
401 $message = $this->msg( 'ipb-unblock' )->parse();
402 $list = SpecialPage::getTitleFor( 'Unblock' );
404 $links[] = $linkRenderer->makeKnownLink(
405 $list,
406 new HtmlArmor( $message )
409 # Link to the block list
410 $links[] = $linkRenderer->makeKnownLink(
411 SpecialPage::getTitleFor( 'BlockList' ),
412 $this->msg( 'ipb-blocklist' )->text()
415 $user = $this->getUser();
417 # Link to edit the block dropdown reasons, if applicable
418 if ( $user->isAllowed( 'editinterface' ) ) {
419 $links[] = $linkRenderer->makeKnownLink(
420 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
421 $this->msg( 'ipb-edit-dropdown' )->text(),
423 [ 'action' => 'edit' ]
427 $text = Html::rawElement(
428 'p',
429 [ 'class' => 'mw-ipb-conveniencelinks' ],
430 $this->getLanguage()->pipeList( $links )
433 $userTitle = self::getTargetUserTitle( $this->target );
434 if ( $userTitle ) {
435 # Get relevant extracts from the block and suppression logs, if possible
436 $out = '';
438 LogEventsList::showLogExtract(
439 $out,
440 'block',
441 $userTitle,
444 'lim' => 10,
445 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
446 'showIfEmpty' => false
449 $text .= $out;
451 # Add suppression block entries if allowed
452 if ( $user->isAllowed( 'suppressionlog' ) ) {
453 LogEventsList::showLogExtract(
454 $out,
455 'suppress',
456 $userTitle,
459 'lim' => 10,
460 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
461 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
462 'showIfEmpty' => false
466 $text .= $out;
470 return $text;
474 * Get a user page target for things like logs.
475 * This handles account and IP range targets.
476 * @param User|string $target
477 * @return Title|null
479 protected static function getTargetUserTitle( $target ) {
480 if ( $target instanceof User ) {
481 return $target->getUserPage();
482 } elseif ( IP::isIPAddress( $target ) ) {
483 return Title::makeTitleSafe( NS_USER, $target );
486 return null;
490 * Determine the target of the block, and the type of target
491 * @todo Should be in Block.php?
492 * @param string $par Subpage parameter passed to setup, or data value from
493 * the HTMLForm
494 * @param WebRequest $request Optionally try and get data from a request too
495 * @return array( User|string|null, Block::TYPE_ constant|null )
497 public static function getTargetAndType( $par, WebRequest $request = null ) {
498 $i = 0;
499 $target = null;
501 while ( true ) {
502 switch ( $i++ ) {
503 case 0:
504 # The HTMLForm will check wpTarget first and only if it doesn't get
505 # a value use the default, which will be generated from the options
506 # below; so this has to have a higher precedence here than $par, or
507 # we could end up with different values in $this->target and the HTMLForm!
508 if ( $request instanceof WebRequest ) {
509 $target = $request->getText( 'wpTarget', null );
511 break;
512 case 1:
513 $target = $par;
514 break;
515 case 2:
516 if ( $request instanceof WebRequest ) {
517 $target = $request->getText( 'ip', null );
519 break;
520 case 3:
521 # B/C @since 1.18
522 if ( $request instanceof WebRequest ) {
523 $target = $request->getText( 'wpBlockAddress', null );
525 break;
526 case 4:
527 break 2;
530 list( $target, $type ) = Block::parseTarget( $target );
532 if ( $type !== null ) {
533 return [ $target, $type ];
537 return [ null, null ];
541 * HTMLForm field validation-callback for Target field.
542 * @since 1.18
543 * @param string $value
544 * @param array $alldata
545 * @param HTMLForm $form
546 * @return Message
548 public static function validateTargetField( $value, $alldata, $form ) {
549 $status = self::validateTarget( $value, $form->getUser() );
550 if ( !$status->isOK() ) {
551 $errors = $status->getErrorsArray();
553 return call_user_func_array( [ $form, 'msg' ], $errors[0] );
554 } else {
555 return true;
560 * Validate a block target.
562 * @since 1.21
563 * @param string $value Block target to check
564 * @param User $user Performer of the block
565 * @return Status
567 public static function validateTarget( $value, User $user ) {
568 global $wgBlockCIDRLimit;
570 /** @var User $target */
571 list( $target, $type ) = self::getTargetAndType( $value );
572 $status = Status::newGood( $target );
574 if ( $type == Block::TYPE_USER ) {
575 if ( $target->isAnon() ) {
576 $status->fatal(
577 'nosuchusershort',
578 wfEscapeWikiText( $target->getName() )
582 $unblockStatus = self::checkUnblockSelf( $target, $user );
583 if ( $unblockStatus !== true ) {
584 $status->fatal( 'badaccess', $unblockStatus );
586 } elseif ( $type == Block::TYPE_RANGE ) {
587 list( $ip, $range ) = explode( '/', $target, 2 );
589 if (
590 ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
591 ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
593 // Range block effectively disabled
594 $status->fatal( 'range_block_disabled' );
597 if (
598 ( IP::isIPv4( $ip ) && $range > 32 ) ||
599 ( IP::isIPv6( $ip ) && $range > 128 )
601 // Dodgy range
602 $status->fatal( 'ip_range_invalid' );
605 if ( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
606 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
609 if ( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
610 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
612 } elseif ( $type == Block::TYPE_IP ) {
613 # All is well
614 } else {
615 $status->fatal( 'badipaddress' );
618 return $status;
622 * Given the form data, actually implement a block. This is also called from ApiBlock.
624 * @param array $data
625 * @param IContextSource $context
626 * @return bool|string
628 public static function processForm( array $data, IContextSource $context ) {
629 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit, $wgContLang;
631 $performer = $context->getUser();
633 // Handled by field validator callback
634 // self::validateTargetField( $data['Target'] );
636 # This might have been a hidden field or a checkbox, so interesting data
637 # can come from it
638 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
640 /** @var User $target */
641 list( $target, $type ) = self::getTargetAndType( $data['Target'] );
642 if ( $type == Block::TYPE_USER ) {
643 $user = $target;
644 $target = $user->getName();
645 $userId = $user->getId();
647 # Give admins a heads-up before they go and block themselves. Much messier
648 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
649 # permission anyway, although the code does allow for it.
650 # Note: Important to use $target instead of $data['Target']
651 # since both $data['PreviousTarget'] and $target are normalized
652 # but $data['target'] gets overridden by (non-normalized) request variable
653 # from previous request.
654 if ( $target === $performer->getName() &&
655 ( $data['PreviousTarget'] !== $target || !$data['Confirm'] )
657 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
659 } elseif ( $type == Block::TYPE_RANGE ) {
660 $user = null;
661 $userId = 0;
662 } elseif ( $type == Block::TYPE_IP ) {
663 $user = null;
664 $target = $target->getName();
665 $userId = 0;
666 } else {
667 # This should have been caught in the form field validation
668 return [ 'badipaddress' ];
671 $expiryTime = self::parseExpiryInput( $data['Expiry'] );
673 if (
674 // an expiry time is needed
675 ( strlen( $data['Expiry'] ) == 0 ) ||
676 // can't be a larger string as 50 (it should be a time format in any way)
677 ( strlen( $data['Expiry'] ) > 50 ) ||
678 // check, if the time could be parsed
679 !$expiryTime
681 return [ 'ipb_expiry_invalid' ];
684 // an expiry time should be in the future, not in the
685 // past (wouldn't make any sense) - bug T123069
686 if ( $expiryTime < wfTimestampNow() ) {
687 return [ 'ipb_expiry_old' ];
690 if ( !isset( $data['DisableEmail'] ) ) {
691 $data['DisableEmail'] = false;
694 # If the user has done the form 'properly', they won't even have been given the
695 # option to suppress-block unless they have the 'hideuser' permission
696 if ( !isset( $data['HideUser'] ) ) {
697 $data['HideUser'] = false;
700 if ( $data['HideUser'] ) {
701 if ( !$performer->isAllowed( 'hideuser' ) ) {
702 # this codepath is unreachable except by a malicious user spoofing forms,
703 # or by race conditions (user has hideuser and block rights, loads block form,
704 # and loses hideuser rights before submission); so need to fail completely
705 # rather than just silently disable hiding
706 return [ 'badaccess-group0' ];
709 # Recheck params here...
710 if ( $type != Block::TYPE_USER ) {
711 $data['HideUser'] = false; # IP users should not be hidden
712 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
713 # Bad expiry.
714 return [ 'ipb_expiry_temp' ];
715 } elseif ( $wgHideUserContribLimit !== false
716 && $user->getEditCount() > $wgHideUserContribLimit
718 # Typically, the user should have a handful of edits.
719 # Disallow hiding users with many edits for performance.
720 return [ [ 'ipb_hide_invalid',
721 Message::numParam( $wgHideUserContribLimit ) ] ];
722 } elseif ( !$data['Confirm'] ) {
723 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
727 # Create block object.
728 $block = new Block();
729 $block->setTarget( $target );
730 $block->setBlocker( $performer );
731 # Truncate reason for whole multibyte characters
732 $block->mReason = $wgContLang->truncate( $data['Reason'][0], 255 );
733 $block->mExpiry = $expiryTime;
734 $block->prevents( 'createaccount', $data['CreateAccount'] );
735 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit || $data['DisableUTEdit'] ) );
736 $block->prevents( 'sendemail', $data['DisableEmail'] );
737 $block->isHardblock( $data['HardBlock'] );
738 $block->isAutoblocking( $data['AutoBlock'] );
739 $block->mHideName = $data['HideUser'];
741 $reason = [ 'hookaborted' ];
742 if ( !Hooks::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
743 return $reason;
746 $priorBlock = null;
747 # Try to insert block. Is there a conflicting block?
748 $status = $block->insert();
749 if ( !$status ) {
750 # Indicates whether the user is confirming the block and is aware of
751 # the conflict (did not change the block target in the meantime)
752 $blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
753 && $data['PreviousTarget'] !== $target );
755 # Special case for API - bug 32434
756 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
758 # Show form unless the user is already aware of this...
759 if ( $blockNotConfirmed || $reblockNotAllowed ) {
760 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
761 # Otherwise, try to update the block...
762 } else {
763 # This returns direct blocks before autoblocks/rangeblocks, since we should
764 # be sure the user is blocked by now it should work for our purposes
765 $currentBlock = Block::newFromTarget( $target );
766 if ( $block->equals( $currentBlock ) ) {
767 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
769 # If the name was hidden and the blocking user cannot hide
770 # names, then don't allow any block changes...
771 if ( $currentBlock->mHideName && !$performer->isAllowed( 'hideuser' ) ) {
772 return [ 'cant-see-hidden-user' ];
775 $priorBlock = clone $currentBlock;
776 $currentBlock->isHardblock( $block->isHardblock() );
777 $currentBlock->prevents( 'createaccount', $block->prevents( 'createaccount' ) );
778 $currentBlock->mExpiry = $block->mExpiry;
779 $currentBlock->isAutoblocking( $block->isAutoblocking() );
780 $currentBlock->mHideName = $block->mHideName;
781 $currentBlock->prevents( 'sendemail', $block->prevents( 'sendemail' ) );
782 $currentBlock->prevents( 'editownusertalk', $block->prevents( 'editownusertalk' ) );
783 $currentBlock->mReason = $block->mReason;
785 $status = $currentBlock->update();
787 $logaction = 'reblock';
789 # Unset _deleted fields if requested
790 if ( $currentBlock->mHideName && !$data['HideUser'] ) {
791 RevisionDeleteUser::unsuppressUserName( $target, $userId );
794 # If hiding/unhiding a name, this should go in the private logs
795 if ( (bool)$currentBlock->mHideName ) {
796 $data['HideUser'] = true;
799 } else {
800 $logaction = 'block';
803 Hooks::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
805 # Set *_deleted fields if requested
806 if ( $data['HideUser'] ) {
807 RevisionDeleteUser::suppressUserName( $target, $userId );
810 # Can't watch a rangeblock
811 if ( $type != Block::TYPE_RANGE && $data['Watch'] ) {
812 WatchAction::doWatch(
813 Title::makeTitle( NS_USER, $target ),
814 $performer,
815 User::IGNORE_USER_RIGHTS
819 # Block constructor sanitizes certain block options on insert
820 $data['BlockEmail'] = $block->prevents( 'sendemail' );
821 $data['AutoBlock'] = $block->isAutoblocking();
823 # Prepare log parameters
824 $logParams = [];
825 $logParams['5::duration'] = $data['Expiry'];
826 $logParams['6::flags'] = self::blockLogFlags( $data, $type );
828 # Make log entry, if the name is hidden, put it in the suppression log
829 $log_type = $data['HideUser'] ? 'suppress' : 'block';
830 $logEntry = new ManualLogEntry( $log_type, $logaction );
831 $logEntry->setTarget( Title::makeTitle( NS_USER, $target ) );
832 $logEntry->setComment( $data['Reason'][0] );
833 $logEntry->setPerformer( $performer );
834 $logEntry->setParameters( $logParams );
835 # Relate log ID to block IDs (bug 25763)
836 $blockIds = array_merge( [ $status['id'] ], $status['autoIds'] );
837 $logEntry->setRelations( [ 'ipb_id' => $blockIds ] );
838 $logId = $logEntry->insert();
840 if ( count( $data['Tags'] ) ) {
841 $logEntry->setTags( $data['Tags'] );
844 $logEntry->publish( $logId );
846 return true;
850 * Get an array of suggested block durations from MediaWiki:Ipboptions
851 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
852 * to the standard "**<duration>|<displayname>" format?
853 * @param Language|null $lang The language to get the durations in, or null to use
854 * the wiki's content language
855 * @return array
857 public static function getSuggestedDurations( $lang = null ) {
858 $a = [];
859 $msg = $lang === null
860 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
861 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
863 if ( $msg == '-' ) {
864 return [];
867 foreach ( explode( ',', $msg ) as $option ) {
868 if ( strpos( $option, ':' ) === false ) {
869 $option = "$option:$option";
872 list( $show, $value ) = explode( ':', $option );
873 $a[$show] = $value;
876 return $a;
880 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
881 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
882 * @param string $expiry Whatever was typed into the form
883 * @return string Timestamp or 'infinity'
885 public static function parseExpiryInput( $expiry ) {
886 if ( wfIsInfinity( $expiry ) ) {
887 $expiry = 'infinity';
888 } else {
889 $expiry = strtotime( $expiry );
891 if ( $expiry < 0 || $expiry === false ) {
892 return false;
895 $expiry = wfTimestamp( TS_MW, $expiry );
898 return $expiry;
902 * Can we do an email block?
903 * @param User $user The sysop wanting to make a block
904 * @return bool
906 public static function canBlockEmail( $user ) {
907 global $wgEnableUserEmail, $wgSysopEmailBans;
909 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
913 * bug 15810: blocked admins should not be able to block/unblock
914 * others, and probably shouldn't be able to unblock themselves
915 * either.
916 * @param User|int|string $user
917 * @param User $performer User doing the request
918 * @return bool|string True or error message key
920 public static function checkUnblockSelf( $user, User $performer ) {
921 if ( is_int( $user ) ) {
922 $user = User::newFromId( $user );
923 } elseif ( is_string( $user ) ) {
924 $user = User::newFromName( $user );
927 if ( $performer->isBlocked() ) {
928 if ( $user instanceof User && $user->getId() == $performer->getId() ) {
929 # User is trying to unblock themselves
930 if ( $performer->isAllowed( 'unblockself' ) ) {
931 return true;
932 # User blocked themselves and is now trying to reverse it
933 } elseif ( $performer->blockedBy() === $performer->getName() ) {
934 return true;
935 } else {
936 return 'ipbnounblockself';
938 } else {
939 # User is trying to block/unblock someone else
940 return 'ipbblocked';
942 } else {
943 return true;
948 * Return a comma-delimited list of "flags" to be passed to the log
949 * reader for this block, to provide more information in the logs
950 * @param array $data From HTMLForm data
951 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
952 * @return string
954 protected static function blockLogFlags( array $data, $type ) {
955 global $wgBlockAllowsUTEdit;
956 $flags = [];
958 # when blocking a user the option 'anononly' is not available/has no effect
959 # -> do not write this into log
960 if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
961 // For grepping: message block-log-flags-anononly
962 $flags[] = 'anononly';
965 if ( $data['CreateAccount'] ) {
966 // For grepping: message block-log-flags-nocreate
967 $flags[] = 'nocreate';
970 # Same as anononly, this is not displayed when blocking an IP address
971 if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
972 // For grepping: message block-log-flags-noautoblock
973 $flags[] = 'noautoblock';
976 if ( $data['DisableEmail'] ) {
977 // For grepping: message block-log-flags-noemail
978 $flags[] = 'noemail';
981 if ( $wgBlockAllowsUTEdit && $data['DisableUTEdit'] ) {
982 // For grepping: message block-log-flags-nousertalk
983 $flags[] = 'nousertalk';
986 if ( $data['HideUser'] ) {
987 // For grepping: message block-log-flags-hiddenname
988 $flags[] = 'hiddenname';
991 return implode( ',', $flags );
995 * Process the form on POST submission.
996 * @param array $data
997 * @param HTMLForm $form
998 * @return bool|array True for success, false for didn't-try, array of errors on failure
1000 public function onSubmit( array $data, HTMLForm $form = null ) {
1001 return self::processForm( $data, $form->getContext() );
1005 * Do something exciting on successful processing of the form, most likely to show a
1006 * confirmation message
1008 public function onSuccess() {
1009 $out = $this->getOutput();
1010 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1011 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
1015 * Return an array of subpages beginning with $search that this special page will accept.
1017 * @param string $search Prefix to search for
1018 * @param int $limit Maximum number of results to return (usually 10)
1019 * @param int $offset Number of results to skip (usually 0)
1020 * @return string[] Matching subpages
1022 public function prefixSearchSubpages( $search, $limit, $offset ) {
1023 $user = User::newFromName( $search );
1024 if ( !$user ) {
1025 // No prefix suggestion for invalid user
1026 return [];
1028 // Autocomplete subpage as user list - public to allow caching
1029 return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
1032 protected function getGroupName() {
1033 return 'users';