Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / specials / SpecialBlock.php
blobef49416494fa5d3e3d9c803f27d7a72cda8e2484
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
21 namespace MediaWiki\Specials;
23 use ErrorPageError;
24 use HtmlArmor;
25 use LogEventsList;
26 use MediaWiki\Block\BlockActionInfo;
27 use MediaWiki\Block\BlockPermissionCheckerFactory;
28 use MediaWiki\Block\BlockUser;
29 use MediaWiki\Block\BlockUserFactory;
30 use MediaWiki\Block\BlockUtils;
31 use MediaWiki\Block\DatabaseBlock;
32 use MediaWiki\Block\DatabaseBlockStore;
33 use MediaWiki\Block\Restriction\ActionRestriction;
34 use MediaWiki\Block\Restriction\NamespaceRestriction;
35 use MediaWiki\Block\Restriction\PageRestriction;
36 use MediaWiki\CommentStore\CommentStore;
37 use MediaWiki\Context\IContextSource;
38 use MediaWiki\Html\Html;
39 use MediaWiki\HTMLForm\HTMLForm;
40 use MediaWiki\Language\Language;
41 use MediaWiki\MainConfigNames;
42 use MediaWiki\MediaWikiServices;
43 use MediaWiki\Message\Message;
44 use MediaWiki\Page\PageReference;
45 use MediaWiki\Page\PageReferenceValue;
46 use MediaWiki\Permissions\Authority;
47 use MediaWiki\Request\WebRequest;
48 use MediaWiki\SpecialPage\FormSpecialPage;
49 use MediaWiki\SpecialPage\SpecialPage;
50 use MediaWiki\Status\Status;
51 use MediaWiki\Title\NamespaceInfo;
52 use MediaWiki\Title\Title;
53 use MediaWiki\Title\TitleFormatter;
54 use MediaWiki\User\User;
55 use MediaWiki\User\UserIdentity;
56 use MediaWiki\User\UserNamePrefixSearch;
57 use MediaWiki\User\UserNameUtils;
58 use OOUI\FieldLayout;
59 use OOUI\HtmlSnippet;
60 use OOUI\LabelWidget;
61 use OOUI\Widget;
62 use Wikimedia\IPUtils;
63 use Wikimedia\Message\MessageSpecifier;
65 /**
66 * Allow users with 'block' user right to block IPs and user accounts from
67 * editing pages and other actions.
69 * @ingroup SpecialPage
71 class SpecialBlock extends FormSpecialPage {
73 private BlockUtils $blockUtils;
74 private BlockPermissionCheckerFactory $blockPermissionCheckerFactory;
75 private BlockUserFactory $blockUserFactory;
76 private DatabaseBlockStore $blockStore;
77 private UserNameUtils $userNameUtils;
78 private UserNamePrefixSearch $userNamePrefixSearch;
79 private BlockActionInfo $blockActionInfo;
80 private TitleFormatter $titleFormatter;
82 /** @var UserIdentity|string|null User to be blocked, as passed either by parameter
83 * (url?wpTarget=Foo) or as subpage (Special:Block/Foo)
85 protected $target;
87 /** @var int DatabaseBlock::TYPE_ constant */
88 protected $type;
90 /** @var User|string The previous block target */
91 protected $previousTarget;
93 /** @var bool Whether the previous submission of the form asked for HideUser */
94 protected $requestedHideUser;
96 /** @var bool */
97 protected $alreadyBlocked;
99 /**
100 * @var MessageSpecifier[]
102 protected $preErrors = [];
104 /** @var bool */
105 protected bool $useCodex = false;
107 /** @var bool */
108 protected bool $useMultiblocks = false;
111 * @var array <mixed,mixed> An associative array used to pass vars to Codex form
113 protected array $codexFormData = [];
115 private NamespaceInfo $namespaceInfo;
118 * @param BlockUtils $blockUtils
119 * @param BlockPermissionCheckerFactory $blockPermissionCheckerFactory
120 * @param BlockUserFactory $blockUserFactory
121 * @param DatabaseBlockStore $blockStore
122 * @param UserNameUtils $userNameUtils
123 * @param UserNamePrefixSearch $userNamePrefixSearch
124 * @param BlockActionInfo $blockActionInfo
125 * @param TitleFormatter $titleFormatter
126 * @param NamespaceInfo $namespaceInfo
128 public function __construct(
129 BlockUtils $blockUtils,
130 BlockPermissionCheckerFactory $blockPermissionCheckerFactory,
131 BlockUserFactory $blockUserFactory,
132 DatabaseBlockStore $blockStore,
133 UserNameUtils $userNameUtils,
134 UserNamePrefixSearch $userNamePrefixSearch,
135 BlockActionInfo $blockActionInfo,
136 TitleFormatter $titleFormatter,
137 NamespaceInfo $namespaceInfo
139 parent::__construct( 'Block', 'block' );
141 $this->blockUtils = $blockUtils;
142 $this->blockPermissionCheckerFactory = $blockPermissionCheckerFactory;
143 $this->blockUserFactory = $blockUserFactory;
144 $this->blockStore = $blockStore;
145 $this->userNameUtils = $userNameUtils;
146 $this->userNamePrefixSearch = $userNamePrefixSearch;
147 $this->blockActionInfo = $blockActionInfo;
148 $this->titleFormatter = $titleFormatter;
149 $this->namespaceInfo = $namespaceInfo;
150 $this->useCodex = $this->getConfig()->get( MainConfigNames::UseCodexSpecialBlock ) ||
151 $this->getRequest()->getBool( 'usecodex' );
152 $this->useMultiblocks = $this->getConfig()->get( MainConfigNames::EnableMultiBlocks ) ||
153 $this->getRequest()->getBool( 'multiblocks' );
156 public function getDescription(): Message {
157 return $this->msg( $this->useMultiblocks ? 'block-manage-blocks' : 'block' );
161 * @inheritDoc
163 public function execute( $par ) {
164 parent::execute( $par );
166 if ( $this->useCodex ) {
167 $this->codexFormData[ 'blockEnableMultiblocks' ] = $this->useMultiblocks;
168 $this->codexFormData[ 'blockTargetUser' ] = $this->target instanceof UserIdentity ?
169 $this->target->getName() :
170 $this->target ?? null;
171 $authority = $this->getAuthority();
172 $this->codexFormData[ 'blockShowSuppressLog' ] = $authority->isAllowed( 'suppressionlog' );
173 $this->codexFormData[ 'canDeleteLogEntry' ] = $authority->isAllowed( 'deletelogentry' );
174 $this->getOutput()->addJsConfigVars( $this->codexFormData );
179 * @inheritDoc
181 public function doesWrites() {
182 return true;
186 * Check that the user can unblock themselves if they are trying to do so
188 * @param User $user
189 * @throws ErrorPageError
191 protected function checkExecutePermissions( User $user ) {
192 parent::checkExecutePermissions( $user );
193 // T17810: blocked admins should have limited access here
194 $status = $this->blockPermissionCheckerFactory
195 ->newBlockPermissionChecker( $this->target, $user )
196 ->checkBlockPermissions();
197 if ( $status !== true ) {
198 throw new ErrorPageError( 'badaccess', $status );
203 * We allow certain special cases where user is blocked
205 * @return bool
207 public function requiresUnblock() {
208 return false;
212 * Handle some magic here
214 * @param string $par
216 protected function setParameter( $par ) {
217 // Extract variables from the request. Try not to get into a situation where we
218 // need to extract *every* variable from the form just for processing here, but
219 // there are legitimate uses for some variables
220 $request = $this->getRequest();
221 [ $this->target, $this->type ] = $this->getTargetAndTypeInternal( $par, $request );
222 if ( $this->target instanceof UserIdentity ) {
223 // Set the 'relevant user' in the skin, so it displays links like Contributions,
224 // User logs, UserRights, etc.
225 $this->getSkin()->setRelevantUser( $this->target );
228 [ $this->previousTarget, /*...*/ ] = $this->blockUtils
229 ->parseBlockTarget( $request->getVal( 'wpPreviousTarget' ) );
230 $this->requestedHideUser = $request->getBool( 'wpHideUser' );
232 if ( $this->useCodex ) {
233 // Parse wpExpiry param
234 $givenExpiry = $request->getVal( 'wpExpiry', '' );
235 if ( wfIsInfinity( $givenExpiry ) ) {
236 $this->codexFormData[ 'blockExpiryPreset' ] = 'infinite';
237 } else {
238 $expiry = date_parse( $givenExpiry );
239 $this->codexFormData[ 'blockExpiryPreset' ] = isset( $expiry[ 'relative' ] ) ?
240 // Relative expiry (e.g. '1 week')
241 $givenExpiry :
242 // Absolute expiry, formatted for <input type="datetime-local">
243 $this->formatExpiryForHtml( $request->getVal( 'wpExpiry', '' ) );
246 $this->codexFormData[ 'blockTypePreset' ] =
247 $request->getRawVal( 'wpEditingRestriction' ) === 'partial' ?
248 'partial' :
249 'sitewide';
250 $this->codexFormData[ 'blockReasonPreset' ] = $request->getVal( 'wpReason' );
251 $this->codexFormData[ 'blockReasonOtherPreset' ] = $request->getVal( 'wpReason-other' );
252 $blockAdditionalDetailsPreset = $blockDetailsPreset = [];
254 // Default is to always block account creation.
255 if ( $request->getBool( 'wpCreateAccount', true ) ) {
256 $blockDetailsPreset[] = 'wpCreateAccount';
259 if ( $request->getBool( 'wpDisableEmail' ) ) {
260 $blockDetailsPreset[] = 'wpDisableEmail';
263 if ( $request->getBool( 'wpDisableUTEdit' ) ) {
264 $blockDetailsPreset[] = 'wpDisableUTEdit';
267 if ( $request->getRawVal( 'wpAutoBlock' ) !== '0' ) {
268 $blockAdditionalDetailsPreset[] = 'wpAutoBlock';
271 if ( $request->getBool( 'wpWatch' ) ) {
272 $blockAdditionalDetailsPreset[] = 'wpWatch';
275 if ( $request->getBool( 'wpHideUser' ) ) {
276 $blockAdditionalDetailsPreset[] = 'wpHideUser';
279 if ( $request->getBool( 'wpHardBlock' ) ) {
280 $blockAdditionalDetailsPreset[] = 'wpHardBlock';
283 $this->codexFormData[ 'blockDetailsPreset' ] = $blockDetailsPreset;
284 $this->codexFormData[ 'blockAdditionalDetailsPreset' ] = $blockAdditionalDetailsPreset;
285 $this->codexFormData[ 'blockPageRestrictions' ] = $request->getVal( 'wpPageRestrictions' );
286 $this->codexFormData[ 'blockNamespaceRestrictions' ] = $request->getVal( 'wpNamespaceRestrictions' );
291 * Customizes the HTMLForm a bit
293 * @param HTMLForm $form
295 protected function alterForm( HTMLForm $form ) {
296 $form->setHeaderHtml( '' );
297 $form->setSubmitDestructive();
299 $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
300 $form->setSubmitTextMsg( $msg );
302 $this->addHelpLink( 'Help:Blocking users' );
304 // Don't need to do anything if the form has been posted
305 if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
306 // Mimic error messages normally generated by the form
307 $form->addHeaderHtml( (string)new FieldLayout(
308 new Widget( [] ),
310 'align' => 'top',
311 'errors' => array_map( function ( $errMsg ) {
312 return new HtmlSnippet( $this->msg( $errMsg )->parse() );
313 }, $this->preErrors ),
315 ) );
317 if ( $this->useCodex ) {
318 $this->codexFormData[ 'blockPreErrors' ] = array_map( function ( $errMsg ) {
319 return $this->msg( $errMsg )->parse();
320 }, $this->preErrors );
326 * @inheritDoc
328 protected function getDisplayFormat() {
329 return $this->useCodex ? 'codex' : 'ooui';
333 * Get the HTMLForm descriptor array for the block form
334 * @return array
336 protected function getFormFields() {
337 $conf = $this->getConfig();
338 $blockAllowsUTEdit = $conf->get( MainConfigNames::BlockAllowsUTEdit );
340 $this->getOutput()->enableOOUI();
342 $user = $this->getUser();
344 $suggestedDurations = $this->getLanguage()->getBlockDurations();
346 $a = [];
348 $a['Target'] = [
349 'type' => 'user',
350 'ipallowed' => true,
351 'iprange' => true,
352 'id' => 'mw-bi-target',
353 'size' => '45',
354 'autofocus' => true,
355 'required' => true,
356 'placeholder' => $this->msg( 'block-target-placeholder' )->text(),
357 'validation-callback' => function ( $value, $alldata, $form ) {
358 $status = $this->blockUtils->validateTarget( $value );
359 if ( !$status->isOK() ) {
360 $errors = $status->getMessages();
361 return $form->msg( $errors[0] );
363 return true;
365 'section' => 'target',
368 $editingRestrictionOptions = $this->useCodex ?
369 // If we're using Codex, use the option-descriptions feature, which is only supported by Codex
371 'options-messages' => [
372 'ipb-sitewide' => 'sitewide',
373 'ipb-partial' => 'partial'
375 'option-descriptions-messages' => [
376 'sitewide' => 'ipb-sitewide-help',
377 'partial' => 'ipb-partial-help'
379 'option-descriptions-messages-parse' => true,
381 // Otherwise, if we're using OOUI, add the options' descriptions as part of their labels
383 'options' => [
384 $this->msg( 'ipb-sitewide' )->escaped() .
385 new LabelWidget( [
386 'classes' => [ 'oo-ui-inline-help' ],
387 'label' => new HtmlSnippet( $this->msg( 'ipb-sitewide-help' )->parse() ),
388 ] ) => 'sitewide',
389 $this->msg( 'ipb-partial' )->escaped() .
390 new LabelWidget( [
391 'classes' => [ 'oo-ui-inline-help' ],
392 'label' => new HtmlSnippet( $this->msg( 'ipb-partial-help' )->parse() ),
393 ] ) => 'partial',
397 $a['EditingRestriction'] = [
398 'type' => 'radio',
399 'cssclass' => 'mw-block-editing-restriction',
400 'default' => 'sitewide',
401 'section' => 'actions',
402 ] + $editingRestrictionOptions;
404 $a['PageRestrictions'] = [
405 'type' => 'titlesmultiselect',
406 'label' => $this->msg( 'ipb-pages-label' )->text(),
407 'exists' => true,
408 'max' => 10,
409 'cssclass' => 'mw-htmlform-checkradio-indent mw-block-partial-restriction',
410 'default' => '',
411 'showMissing' => false,
412 'excludeDynamicNamespaces' => true,
413 'input' => [
414 'autocomplete' => false
416 'section' => 'actions',
419 $a['NamespaceRestrictions'] = [
420 'type' => 'namespacesmultiselect',
421 'label' => $this->msg( 'ipb-namespaces-label' )->text(),
422 'exists' => true,
423 'cssclass' => 'mw-htmlform-checkradio-indent mw-block-partial-restriction',
424 'default' => '',
425 'input' => [
426 'autocomplete' => false
428 'section' => 'actions',
431 if ( $conf->get( MainConfigNames::EnablePartialActionBlocks ) ) {
432 $blockActions = $this->blockActionInfo->getAllBlockActions();
433 $optionMessages = array_combine(
434 array_map( static function ( $action ) {
435 return "ipb-action-$action";
436 }, array_keys( $blockActions ) ),
437 $blockActions
440 $this->codexFormData[ 'partialBlockActionOptions'] = $optionMessages;
442 $a['ActionRestrictions'] = [
443 'type' => 'multiselect',
444 'cssclass' => 'mw-htmlform-checkradio-indent mw-block-partial-restriction mw-block-action-restriction',
445 'options-messages' => $optionMessages,
446 'section' => 'actions',
450 $a['CreateAccount'] = [
451 'type' => 'check',
452 'cssclass' => 'mw-block-restriction',
453 'label-message' => 'ipbcreateaccount',
454 'default' => true,
455 'section' => 'details',
458 if ( $this->blockPermissionCheckerFactory
459 ->newBlockPermissionChecker( null, $user )
460 ->checkEmailPermissions()
462 $a['DisableEmail'] = [
463 'type' => 'check',
464 'cssclass' => 'mw-block-restriction',
465 'label-message' => 'ipbemailban',
466 'section' => 'details',
469 $this->codexFormData[ 'blockDisableEmailVisible'] = true;
472 if ( $blockAllowsUTEdit ) {
473 $a['DisableUTEdit'] = [
474 'type' => 'check',
475 'cssclass' => 'mw-block-restriction',
476 'label-message' => 'ipb-disableusertalk',
477 'default' => false,
478 'section' => 'details',
481 $this->codexFormData[ 'blockDisableUTEditVisible'] = true;
484 $defaultExpiry = $this->msg( 'ipb-default-expiry' )->inContentLanguage();
485 if ( $this->type === DatabaseBlock::TYPE_RANGE || $this->type === DatabaseBlock::TYPE_IP ) {
486 $defaultExpiryIP = $this->msg( 'ipb-default-expiry-ip' )->inContentLanguage();
487 if ( !$defaultExpiryIP->isDisabled() ) {
488 $defaultExpiry = $defaultExpiryIP;
492 $a['Expiry'] = [
493 'type' => 'expiry',
494 'required' => true,
495 'options' => $suggestedDurations,
496 'default' => $defaultExpiry->text(),
497 'section' => 'expiry',
499 $this->codexFormData[ 'blockExpiryOptions' ] = $suggestedDurations;
500 $this->codexFormData[ 'blockExpiryDefault' ] = $defaultExpiry->text();
502 $a['Reason'] = [
503 'type' => 'selectandother',
504 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
505 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
506 // Unicode codepoints.
507 'maxlength' => CommentStore::COMMENT_CHARACTER_LIMIT,
508 'maxlength-unit' => 'codepoints',
509 'options-message' => 'ipbreason-dropdown',
510 'section' => 'reason',
511 'help-message' => 'block-reason-help',
514 if ( $this->useCodex ) {
515 $blockReasonOptions = Html::listDropdownOptionsCodex(
516 Html::listDropdownOptions( $this->msg( 'ipbreason-dropdown' )->plain(),
517 [ 'other' => $this->msg( 'htmlform-selectorother-other' )->text() ]
518 ) );
519 $this->codexFormData[ 'blockReasonOptions' ] = $blockReasonOptions;
520 $this->codexFormData[ 'blockReasonMaxLength' ] = CommentStore::COMMENT_CHARACTER_LIMIT;
523 $a['AutoBlock'] = [
524 'type' => 'check',
525 'label-message' => [
526 'ipbenableautoblock',
527 Message::durationParam( $conf->get( MainConfigNames::AutoblockExpiry ) )
529 'default' => true,
530 'section' => 'options',
532 $this->codexFormData['blockAutoblockExpiry'] = $this->getLanguage()
533 ->formatDuration( $conf->get( MainConfigNames::AutoblockExpiry ) );
535 // Allow some users to hide name from block log, blocklist and listusers
536 if ( $this->getAuthority()->isAllowed( 'hideuser' ) ) {
537 $a['HideUser'] = [
538 'type' => 'check',
539 'label-message' => 'ipbhidename',
540 'cssclass' => 'mw-block-hideuser',
541 'section' => 'options',
544 $this->codexFormData['blockHideUser'] = true;
547 // Watchlist their user page? (Only if user is logged in)
548 if ( $user->isRegistered() ) {
549 $a['Watch'] = [
550 'type' => 'check',
551 'label-message' => 'ipbwatchuser',
552 'section' => 'options',
556 $a['HardBlock'] = [
557 'type' => 'check',
558 'label-message' => 'ipb-hardblock',
559 'default' => false,
560 'section' => 'options',
563 // This is basically a copy of the Target field, but the user can't change it, so we
564 // can see if the warnings we maybe showed to the user before still apply
565 $a['PreviousTarget'] = [
566 'type' => 'hidden',
567 'default' => false,
570 // We'll turn this into a checkbox if we need to
571 $a['Confirm'] = [
572 'type' => 'hidden',
573 'default' => '',
574 'label-message' => 'ipb-confirm',
575 'cssclass' => 'mw-block-confirm',
578 $this->maybeAlterFormDefaults( $a );
580 // Allow extensions to add more fields
581 $this->getHookRunner()->onSpecialBlockModifyFormFields( $this, $a );
583 return $a;
587 * If the user has already been blocked with similar settings, load that block
588 * and change the defaults for the form fields to match the existing settings.
589 * @param array &$fields HTMLForm descriptor array
591 protected function maybeAlterFormDefaults( &$fields ) {
592 // This will be overwritten by request data
593 $fields['Target']['default'] = (string)$this->target;
595 if ( $this->target ) {
596 $status = $this->blockUtils->validateTarget( $this->target );
597 if ( !$status->isOK() ) {
598 $errors = $status->getMessages( 'error' );
599 $this->preErrors = array_merge( $this->preErrors, $errors );
603 // This won't be
604 $fields['PreviousTarget']['default'] = (string)$this->target;
606 $block = $this->blockStore->newFromTarget( $this->target );
608 // Populate fields if there is a block that is not an autoblock; if it is a range
609 // block, only populate the fields if the range is the same as $this->target
610 if ( $block instanceof DatabaseBlock && $block->getType() !== DatabaseBlock::TYPE_AUTO
611 && ( $this->type != DatabaseBlock::TYPE_RANGE
612 || ( $this->target && $block->isBlocking( $this->target ) ) )
614 $fields['HardBlock']['default'] = $block->isHardblock();
615 $fields['CreateAccount']['default'] = $block->isCreateAccountBlocked();
616 $fields['AutoBlock']['default'] = $block->isAutoblocking();
618 if ( isset( $fields['DisableEmail'] ) ) {
619 $fields['DisableEmail']['default'] = $block->isEmailBlocked();
622 if ( isset( $fields['HideUser'] ) ) {
623 $fields['HideUser']['default'] = $block->getHideName();
626 if ( isset( $fields['DisableUTEdit'] ) ) {
627 $fields['DisableUTEdit']['default'] = !$block->isUsertalkEditAllowed();
630 // If the username was hidden (bl_deleted == 1), don't show the reason
631 // unless this user also has rights to hideuser: T37839
632 if ( !$block->getHideName() || $this->getAuthority()->isAllowed( 'hideuser' ) ) {
633 $fields['Reason']['default'] = $block->getReasonComment()->text;
634 } else {
635 $fields['Reason']['default'] = '';
638 if ( $this->getRequest()->wasPosted() ) {
639 // Ok, so we got a POST submission asking us to reblock a user. So show the
640 // confirm checkbox; the user will only see it if they haven't previously
641 $fields['Confirm']['type'] = 'check';
642 } else {
643 // We got a target, but it wasn't a POST request, so the user must have gone
644 // to a link like [[Special:Block/User]]. We don't need to show the checkbox
645 // as long as they go ahead and block *that* user
646 $fields['Confirm']['default'] = 1;
649 if ( $block->getExpiry() == 'infinity' ) {
650 $fields['Expiry']['default'] = $this->codexFormData[ 'blockExpiryDefault' ] = 'infinite';
651 } else {
652 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->getExpiry() );
654 // Don't overwrite if expiry was specified in the URL
655 if ( !isset( $this->codexFormData[ 'blockExpiryPreset' ] ) ) {
656 $this->codexFormData[ 'blockExpiryPreset' ] = $this->formatExpiryForHtml( $block->getExpiry() );
660 if ( !$block->isSitewide() ) {
661 $fields['EditingRestriction']['default'] =
662 $this->codexFormData[ 'blockTypePreset' ] = 'partial';
664 $pageRestrictions = [];
665 $namespaceRestrictions = [];
666 foreach ( $block->getRestrictions() as $restriction ) {
667 if ( $restriction instanceof PageRestriction && $restriction->getTitle() ) {
668 $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
669 } elseif ( $restriction instanceof NamespaceRestriction &&
670 $this->namespaceInfo->exists( $restriction->getValue() )
672 $namespaceRestrictions[] = $restriction->getValue();
676 // Sort the restrictions so they are in alphabetical order.
677 sort( $pageRestrictions );
678 $fields['PageRestrictions']['default'] =
679 $this->codexFormData[ 'blockPageRestrictions' ] = implode( "\n", $pageRestrictions );
680 sort( $namespaceRestrictions );
681 $fields['NamespaceRestrictions']['default'] =
682 $this->codexFormData[ 'blockNamespaceRestrictions' ] = implode( "\n", $namespaceRestrictions );
684 if ( $this->getConfig()->get( MainConfigNames::EnablePartialActionBlocks ) ) {
685 $actionRestrictions = [];
686 foreach ( $block->getRestrictions() as $restriction ) {
687 if ( $restriction instanceof ActionRestriction ) {
688 $actionRestrictions[] = $restriction->getValue();
691 $fields['ActionRestrictions']['default'] = $actionRestrictions;
695 $this->alreadyBlocked = true;
696 $this->codexFormData[ 'blockAlreadyBlocked' ] = $this->alreadyBlocked;
697 $this->preErrors[] = $this->msg( 'ipb-needreblock', wfEscapeWikiText( $block->getTargetName() ) );
700 if ( $this->alreadyBlocked || $this->getRequest()->wasPosted()
701 || $this->getRequest()->getCheck( 'wpCreateAccount' )
703 $this->getOutput()->addJsConfigVars( 'wgCreateAccountDirty', true );
706 // We always need confirmation to do HideUser
707 if ( $this->requestedHideUser && $this->getAuthority()->isAllowed( 'hideuser' ) ) {
708 $fields['Confirm']['type'] = 'check';
709 unset( $fields['Confirm']['default'] );
710 $this->preErrors[] = $this->msg( 'ipb-confirmhideuser', 'ipb-confirmaction' );
713 // Or if the user is trying to block themselves
714 if ( (string)$this->target === $this->getUser()->getName() ) {
715 $fields['Confirm']['type'] = 'check';
716 unset( $fields['Confirm']['default'] );
717 $this->preErrors[] = $this->msg( 'ipb-blockingself', 'ipb-confirmaction' );
722 * Format a date string for use by <input type="datetime-local">
724 * @param string $expiry
725 * @return string Formatted as YYYY-MM-DDTHH:mm
727 private function formatExpiryForHtml( string $expiry ): string {
728 if ( preg_match( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/', $expiry ) === 1 ) {
729 // YYYY-MM-DDTHH:mm which is accepted by <input type="datetime-local">, but not by MediaWiki.
730 return substr( $expiry, 0, 16 );
731 } elseif ( $expiry === '' ) {
732 // No expiry specified
733 return '';
735 return substr( wfTimestamp( TS_ISO_8601, $expiry ), 0, 16 );
739 * Add header elements like block log entries, etc.
740 * @return string
742 protected function preHtml() {
743 $this->getOutput()->addModuleStyles( [ 'mediawiki.special' ] );
744 if ( $this->useCodex ) {
745 $this->getOutput()->addModules( [ 'mediawiki.special.block.codex' ] );
746 } else {
747 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
750 $blockCIDRLimit = $this->getConfig()->get( MainConfigNames::BlockCIDRLimit );
751 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
753 $otherBlockMessages = [];
754 if ( $this->target !== null ) {
755 $targetName = $this->target;
756 if ( $this->target instanceof UserIdentity ) {
757 $targetName = $this->target->getName();
759 // Get other blocks, i.e. from GlobalBlocking or TorBlock extension
760 $this->getHookRunner()->onOtherBlockLogLink(
761 $otherBlockMessages, $targetName );
763 if ( count( $otherBlockMessages ) ) {
764 $s = Html::rawElement(
765 'h2',
767 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
768 ) . "\n";
770 $list = '';
772 foreach ( $otherBlockMessages as $link ) {
773 $list .= Html::rawElement( 'li', [], $link ) . "\n";
776 $s .= Html::rawElement(
777 'ul',
778 [ 'class' => 'mw-blockip-alreadyblocked' ],
779 $list
780 ) . "\n";
782 $text .= $s;
786 return $text;
790 * Add footer elements to the form
791 * @return string
793 protected function postHtml() {
794 $links = [];
796 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
798 $linkRenderer = $this->getLinkRenderer();
799 // Link to the user's contributions, if applicable
800 if ( $this->target instanceof UserIdentity ) {
801 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
802 $links[] = $linkRenderer->makeLink(
803 $contribsPage,
804 $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->text()
808 // Link to unblock the specified user, or to a blank unblock form
809 if ( $this->target instanceof UserIdentity ) {
810 $message = $this->msg(
811 'ipb-unblock-addr',
812 wfEscapeWikiText( $this->target->getName() )
813 )->parse();
814 $list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
815 } else {
816 $message = $this->msg( 'ipb-unblock' )->parse();
817 $list = SpecialPage::getTitleFor( 'Unblock' );
819 $links[] = $linkRenderer->makeKnownLink(
820 $list,
821 new HtmlArmor( $message )
824 // Link to the block list
825 $links[] = $linkRenderer->makeKnownLink(
826 SpecialPage::getTitleFor( 'BlockList' ),
827 $this->msg( 'ipb-blocklist' )->text()
830 // Link to edit the block dropdown reasons, if applicable
831 if ( $this->getAuthority()->isAllowed( 'editinterface' ) ) {
832 $links[] = $linkRenderer->makeKnownLink(
833 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
834 $this->msg( 'ipb-edit-dropdown' )->text(),
836 [ 'action' => 'edit' ]
840 $text = Html::rawElement(
841 'p',
842 [ 'class' => 'mw-ipb-conveniencelinks' ],
843 $this->getLanguage()->pipeList( $links )
846 $userPage = self::getTargetUserTitle( $this->target );
847 if ( $userPage ) {
848 // Get relevant extracts from the block and suppression logs, if possible
849 $out = '';
851 LogEventsList::showLogExtract(
852 $out,
853 'block',
854 $userPage,
857 'lim' => 10,
858 'msgKey' => [
859 'blocklog-showlog',
860 $this->titleFormatter->getText( $userPage ),
862 'showIfEmpty' => false
865 $text .= $out;
867 // Add suppression block entries if allowed
868 if ( $this->getAuthority()->isAllowed( 'suppressionlog' ) ) {
869 LogEventsList::showLogExtract(
870 $out,
871 'suppress',
872 $userPage,
875 'lim' => 10,
876 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
877 'msgKey' => [
878 'blocklog-showsuppresslog',
879 $this->titleFormatter->getText( $userPage ),
881 'showIfEmpty' => false
885 $text .= $out;
889 return $text;
893 * Get a user page target for things like logs.
894 * This handles account and IP range targets.
895 * @param UserIdentity|string|null $target
896 * @return PageReference|null
898 protected static function getTargetUserTitle( $target ): ?PageReference {
899 if ( $target instanceof UserIdentity ) {
900 return PageReferenceValue::localReference( NS_USER, $target->getName() );
903 if ( is_string( $target ) && IPUtils::isIPAddress( $target ) ) {
904 return PageReferenceValue::localReference( NS_USER, $target );
907 return null;
911 * Get the target and type, given the request and the subpage parameter.
912 * Several parameters are handled for backwards compatability. 'wpTarget' is
913 * prioritized, since it matches the HTML form.
915 * @param string|null $par Subpage parameter passed to setup, or data value from
916 * the HTMLForm
917 * @param WebRequest $request Try and get data from a request too
918 * @return array [ UserIdentity|string|null, DatabaseBlock::TYPE_ constant|null ]
919 * @phan-return array{0:UserIdentity|string|null,1:int|null}
921 private function getTargetAndTypeInternal( ?string $par, WebRequest $request ) {
922 $possibleTargets = [
923 $request->getVal( 'wpTarget', null ),
924 $par,
925 $request->getVal( 'ip', null ),
926 // B/C @since 1.18
927 $request->getVal( 'wpBlockAddress', null ),
929 foreach ( $possibleTargets as $possibleTarget ) {
930 $targetAndType = $this->blockUtils
931 ->parseBlockTarget( $possibleTarget );
932 // If type is not null then target is valid
933 if ( $targetAndType[ 1 ] !== null ) {
934 break;
937 return $targetAndType;
941 * Given the form data, actually implement a block.
943 * @deprecated since 1.36, use BlockUserFactory service instead,
944 * hard-deprecated since 1.43
945 * @param array $data
946 * @param IContextSource $context
947 * @return bool|string|array|Status
949 public static function processForm( array $data, IContextSource $context ) {
950 wfDeprecated( __METHOD__, '1.36' );
951 $services = MediaWikiServices::getInstance();
952 return self::processFormInternal(
953 $data,
954 $context->getAuthority(),
955 $services->getBlockUserFactory(),
956 $services->getBlockUtils()
961 * Implementation details for processForm
962 * Own function to allow sharing the deprecated code with non-deprecated and service code
964 * @param array $data
965 * @param Authority $performer
966 * @param BlockUserFactory $blockUserFactory
967 * @param BlockUtils $blockUtils
968 * @return bool|string|array|Status
970 private static function processFormInternal(
971 array $data,
972 Authority $performer,
973 BlockUserFactory $blockUserFactory,
974 BlockUtils $blockUtils
976 // Temporarily access service container until the feature flag is removed: T280532
977 $enablePartialActionBlocks = MediaWikiServices::getInstance()
978 ->getMainConfig()->get( MainConfigNames::EnablePartialActionBlocks );
980 $isPartialBlock = isset( $data['EditingRestriction'] ) &&
981 $data['EditingRestriction'] === 'partial';
983 // This might have been a hidden field or a checkbox, so interesting data
984 // can come from it
985 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
987 // If the user has done the form 'properly', they won't even have been given the
988 // option to suppress-block unless they have the 'hideuser' permission
989 if ( !isset( $data['HideUser'] ) ) {
990 $data['HideUser'] = false;
993 /** @var User $target */
994 [ $target, $type ] = $blockUtils->parseBlockTarget( $data['Target'] );
995 if ( $type == DatabaseBlock::TYPE_USER ) {
996 $target = $target->getName();
998 // Give admins a heads-up before they go and block themselves. Much messier
999 // to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
1000 // permission anyway, although the code does allow for it.
1001 // Note: Important to use $target instead of $data['Target']
1002 // since both $data['PreviousTarget'] and $target are normalized
1003 // but $data['target'] gets overridden by (non-normalized) request variable
1004 // from previous request.
1005 if ( $target === $performer->getUser()->getName() &&
1006 ( $data['PreviousTarget'] !== $target || !$data['Confirm'] )
1008 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
1011 if ( $data['HideUser'] && !$data['Confirm'] ) {
1012 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
1014 } elseif ( $type == DatabaseBlock::TYPE_IP ) {
1015 $target = $target->getName();
1016 } elseif ( $type != DatabaseBlock::TYPE_RANGE ) {
1017 // This should have been caught in the form field validation
1018 return [ 'badipaddress' ];
1021 // Reason, to be passed to the block object. For default values of reason, see
1022 // HTMLSelectAndOtherField::getDefault
1023 $blockReason = $data['Reason'][0] ?? '';
1025 $pageRestrictions = [];
1026 $namespaceRestrictions = [];
1027 $actionRestrictions = [];
1028 if ( $isPartialBlock ) {
1029 if ( isset( $data['PageRestrictions'] ) && $data['PageRestrictions'] !== '' ) {
1030 $titles = explode( "\n", $data['PageRestrictions'] );
1031 foreach ( $titles as $title ) {
1032 $pageRestrictions[] = PageRestriction::newFromTitle( $title );
1035 if ( isset( $data['NamespaceRestrictions'] ) && $data['NamespaceRestrictions'] !== '' ) {
1036 $namespaceRestrictions = array_map( static function ( $id ) {
1037 return new NamespaceRestriction( 0, (int)$id );
1038 }, explode( "\n", $data['NamespaceRestrictions'] ) );
1040 if (
1041 $enablePartialActionBlocks &&
1042 isset( $data['ActionRestrictions'] ) &&
1043 $data['ActionRestrictions'] !== ''
1045 $actionRestrictions = array_map( static function ( $id ) {
1046 return new ActionRestriction( 0, $id );
1047 }, $data['ActionRestrictions'] );
1050 $restrictions = array_merge( $pageRestrictions, $namespaceRestrictions, $actionRestrictions );
1052 if ( !isset( $data['Tags'] ) ) {
1053 $data['Tags'] = [];
1056 $blockOptions = [
1057 'isCreateAccountBlocked' => $data['CreateAccount'],
1058 'isHardBlock' => $data['HardBlock'],
1059 'isAutoblocking' => $data['AutoBlock'],
1060 'isHideUser' => $data['HideUser'],
1061 'isPartial' => $isPartialBlock,
1064 if ( isset( $data['DisableUTEdit'] ) ) {
1065 $blockOptions['isUserTalkEditBlocked'] = $data['DisableUTEdit'];
1067 if ( isset( $data['DisableEmail'] ) ) {
1068 $blockOptions['isEmailBlocked'] = $data['DisableEmail'];
1071 $blockUser = $blockUserFactory->newBlockUser(
1072 $target,
1073 $performer,
1074 $data['Expiry'],
1075 $blockReason,
1076 $blockOptions,
1077 $restrictions,
1078 $data['Tags']
1081 // Indicates whether the user is confirming the block and is aware of
1082 // the conflict (did not change the block target in the meantime)
1083 $blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
1084 && $data['PreviousTarget'] !== $target );
1086 // Special case for API - T34434
1087 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
1089 $doReblock = !$blockNotConfirmed && !$reblockNotAllowed;
1091 $status = $blockUser->placeBlock( $doReblock );
1092 if ( !$status->isOK() ) {
1093 return $status;
1096 if (
1097 // Can't watch a range block
1098 $type != DatabaseBlock::TYPE_RANGE
1100 // Technically a wiki can be configured to allow anonymous users to place blocks,
1101 // in which case the 'Watch' field isn't included in the form shown, and we should
1102 // not try to access it.
1103 && array_key_exists( 'Watch', $data )
1104 && $data['Watch']
1106 MediaWikiServices::getInstance()->getWatchlistManager()->addWatchIgnoringRights(
1107 $performer->getUser(),
1108 Title::makeTitle( NS_USER, $target )
1112 return true;
1116 * Get an array of suggested block durations from MediaWiki:Ipboptions
1117 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
1118 * to the standard "**<duration>|<displayname>" format?
1119 * @deprecated since 1.42, use Language::getBlockDurations() instead,
1120 * hard-deprecated since 1.43
1121 * @param Language|null $lang The language to get the durations in, or null to use
1122 * the wiki's content language
1123 * @param bool $includeOther Whether to include the 'other' option in the list of
1124 * suggestions
1125 * @return string[]
1127 public static function getSuggestedDurations( ?Language $lang = null, $includeOther = true ) {
1128 wfDeprecated( __METHOD__, '1.42' );
1129 $lang ??= MediaWikiServices::getInstance()->getContentLanguage();
1130 return $lang->getBlockDurations( $includeOther );
1134 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1135 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
1137 * @deprecated since 1.36, use BlockUser::parseExpiryInput instead,
1138 * hard-deprecated since 1.43
1140 * @param string $expiry Whatever was typed into the form
1141 * @return string|bool Timestamp or 'infinity' or false on error.
1143 public static function parseExpiryInput( $expiry ) {
1144 wfDeprecated( __METHOD__, '1.36' );
1145 return BlockUser::parseExpiryInput( $expiry );
1149 * Can we do an email block?
1151 * @deprecated since 1.36, use BlockPermissionChecker service instead,
1152 * hard-deprecated since 1.43
1153 * @param UserIdentity $user The sysop wanting to make a block
1154 * @return bool
1156 public static function canBlockEmail( UserIdentity $user ) {
1157 wfDeprecated( __METHOD__, '1.36' );
1158 return MediaWikiServices::getInstance()
1159 ->getBlockPermissionCheckerFactory()
1160 ->newBlockPermissionChecker( null, User::newFromIdentity( $user ) )
1161 ->checkEmailPermissions();
1165 * Process the form on POST submission.
1166 * @param array $data
1167 * @param HTMLForm|null $form
1168 * @return bool|string|array|Status As documented for HTMLForm::trySubmit.
1170 public function onSubmit( array $data, ?HTMLForm $form = null ) {
1171 return self::processFormInternal(
1172 $data,
1173 $this->getAuthority(),
1174 $this->blockUserFactory,
1175 $this->blockUtils
1180 * Do something exciting on successful processing of the form, most likely to show a
1181 * confirmation message
1183 public function onSuccess() {
1184 $out = $this->getOutput();
1185 $out->setPageTitleMsg( $this->msg( 'blockipsuccesssub' ) );
1186 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
1190 * Return an array of subpages beginning with $search that this special page will accept.
1192 * @param string $search Prefix to search for
1193 * @param int $limit Maximum number of results to return (usually 10)
1194 * @param int $offset Number of results to skip (usually 0)
1195 * @return string[] Matching subpages
1197 public function prefixSearchSubpages( $search, $limit, $offset ) {
1198 $search = $this->userNameUtils->getCanonical( $search );
1199 if ( !$search ) {
1200 // No prefix suggestion for invalid user
1201 return [];
1203 // Autocomplete subpage as user list - public to allow caching
1204 return $this->userNamePrefixSearch
1205 ->search( UserNamePrefixSearch::AUDIENCE_PUBLIC, $search, $limit, $offset );
1209 * @inheritDoc
1211 protected function getGroupName() {
1212 return 'users';
1216 /** @deprecated class alias since 1.41 */
1217 class_alias( SpecialBlock::class, 'SpecialBlock' );