1<?php
2/**
3 * Implements Special:Block
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24use MediaWiki\Block\AbstractBlock;
25use MediaWiki\Block\BlockPermissionCheckerFactory;
26use MediaWiki\Block\BlockUser;
27use MediaWiki\Block\BlockUserFactory;
28use MediaWiki\Block\BlockUtils;
29use MediaWiki\Block\DatabaseBlock;
30use MediaWiki\Block\Restriction\NamespaceRestriction;
31use MediaWiki\Block\Restriction\PageRestriction;
32use MediaWiki\MediaWikiServices;
33use MediaWiki\Permissions\Authority;
34use MediaWiki\User\UserIdentity;
35use MediaWiki\User\UserNamePrefixSearch;
36use MediaWiki\User\UserNameUtils;
37use Wikimedia\IPUtils;
38
39/**
40 * A special page that allows users with 'block' right to block users from
41 * editing pages and other actions
42 *
43 * @ingroup SpecialPage
44 */
45class SpecialBlock extends FormSpecialPage {
46
47	/** @var BlockUtils */
48	private $blockUtils;
49
50	/** @var BlockPermissionCheckerFactory */
51	private $blockPermissionCheckerFactory;
52
53	/** @var BlockUserFactory */
54	private $blockUserFactory;
55
56	/** @var UserNameUtils */
57	private $userNameUtils;
58
59	/** @var UserNamePrefixSearch */
60	private $userNamePrefixSearch;
61
62	/** @var User|string|null User to be blocked, as passed either by parameter (url?wpTarget=Foo)
63	 * or as subpage (Special:Block/Foo)
64	 */
65	protected $target;
66
67	/** @var int DatabaseBlock::TYPE_ constant */
68	protected $type;
69
70	/** @var User|string The previous block target */
71	protected $previousTarget;
72
73	/** @var bool Whether the previous submission of the form asked for HideUser */
74	protected $requestedHideUser;
75
76	/** @var bool */
77	protected $alreadyBlocked;
78
79	/** @var array */
80	protected $preErrors = [];
81
82	/**
83	 * @param BlockUtils $blockUtils
84	 * @param BlockPermissionCheckerFactory $blockPermissionCheckerFactory
85	 * @param BlockUserFactory $blockUserFactory
86	 * @param UserNameUtils $userNameUtils
87	 * @param UserNamePrefixSearch $userNamePrefixSearch
88	 */
89	public function __construct(
90		BlockUtils $blockUtils,
91		BlockPermissionCheckerFactory $blockPermissionCheckerFactory,
92		BlockUserFactory $blockUserFactory,
93		UserNameUtils $userNameUtils,
94		UserNamePrefixSearch $userNamePrefixSearch
95	) {
96		parent::__construct( 'Block', 'block' );
97
98		$this->blockUtils = $blockUtils;
99		$this->blockPermissionCheckerFactory = $blockPermissionCheckerFactory;
100		$this->blockUserFactory = $blockUserFactory;
101		$this->userNameUtils = $userNameUtils;
102		$this->userNamePrefixSearch = $userNamePrefixSearch;
103	}
104
105	public function doesWrites() {
106		return true;
107	}
108
109	/**
110	 * Checks that the user can unblock themselves if they are trying to do so
111	 *
112	 * @param User $user
113	 * @throws ErrorPageError
114	 */
115	protected function checkExecutePermissions( User $user ) {
116		parent::checkExecutePermissions( $user );
117		# T17810: blocked admins should have limited access here
118		$status = $this->blockPermissionCheckerFactory
119			->newBlockPermissionChecker( $this->target, $user )
120			->checkBlockPermissions();
121		if ( $status !== true ) {
122			throw new ErrorPageError( 'badaccess', $status );
123		}
124	}
125
126	/**
127	 * We allow certain special cases where user is blocked
128	 *
129	 * @return bool
130	 */
131	public function requiresUnblock() {
132		return false;
133	}
134
135	/**
136	 * Handle some magic here
137	 *
138	 * @param string $par
139	 */
140	protected function setParameter( $par ) {
141		# Extract variables from the request.  Try not to get into a situation where we
142		# need to extract *every* variable from the form just for processing here, but
143		# there are legitimate uses for some variables
144		$request = $this->getRequest();
145		list( $this->target, $this->type ) = self::getTargetAndType( $par, $request );
146		if ( $this->target instanceof User ) {
147			# Set the 'relevant user' in the skin, so it displays links like Contributions,
148			# User logs, UserRights, etc.
149			$this->getSkin()->setRelevantUser( $this->target );
150		}
151
152		list( $this->previousTarget, /*...*/ ) = $this->blockUtils
153			->parseBlockTarget( $request->getVal( 'wpPreviousTarget' ) );
154		$this->requestedHideUser = $request->getBool( 'wpHideUser' );
155	}
156
157	/**
158	 * Customizes the HTMLForm a bit
159	 *
160	 * @param HTMLForm $form
161	 */
162	protected function alterForm( HTMLForm $form ) {
163		$form->setHeaderText( '' );
164		$form->setSubmitDestructive();
165
166		$msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
167		$form->setSubmitTextMsg( $msg );
168
169		$this->addHelpLink( 'Help:Blocking users' );
170
171		# Don't need to do anything if the form has been posted
172		if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
173			$s = $form->formatErrors( $this->preErrors );
174			if ( $s ) {
175				$form->addHeaderText( Html::rawElement(
176					'div',
177					[ 'class' => 'error' ],
178					$s
179				) );
180			}
181		}
182	}
183
184	protected function getDisplayFormat() {
185		return 'ooui';
186	}
187
188	/**
189	 * Get the HTMLForm descriptor array for the block form
190	 * @return array
191	 */
192	protected function getFormFields() {
193		$conf = $this->getConfig();
194		$blockAllowsUTEdit = $conf->get( 'BlockAllowsUTEdit' );
195
196		$this->getOutput()->enableOOUI();
197
198		$user = $this->getUser();
199
200		$suggestedDurations = self::getSuggestedDurations();
201
202		$a = [];
203
204		$a['Target'] = [
205			'type' => 'user',
206			'ipallowed' => true,
207			'iprange' => true,
208			'id' => 'mw-bi-target',
209			'size' => '45',
210			'autofocus' => true,
211			'required' => true,
212			'placeholder' => $this->msg( 'block-target-placeholder' )->text(),
213			'validation-callback' => function ( $value, $alldata, $form ) {
214				$status = $this->blockUtils->validateTarget( $value );
215				if ( !$status->isOK() ) {
216					$errors = $status->getErrorsArray();
217
218					return $form->msg( ...$errors[0] );
219				}
220				return true;
221			},
222			'section' => 'target',
223		];
224
225		$a['Editing'] = [
226			'type' => 'check',
227			'label-message' => 'block-prevent-edit',
228			'default' => true,
229			'section' => 'actions',
230		];
231
232		$a['EditingRestriction'] = [
233			'type' => 'radio',
234			'cssclass' => 'mw-block-editing-restriction',
235			'default' => 'sitewide',
236			'options' => [
237				$this->msg( 'ipb-sitewide' )->escaped() .
238					new \OOUI\LabelWidget( [
239						'classes' => [ 'oo-ui-inline-help' ],
240						'label' => $this->msg( 'ipb-sitewide-help' )->text(),
241					] ) => 'sitewide',
242				$this->msg( 'ipb-partial' )->escaped() .
243					new \OOUI\LabelWidget( [
244						'classes' => [ 'oo-ui-inline-help' ],
245						'label' => $this->msg( 'ipb-partial-help' )->text(),
246					] ) => 'partial',
247			],
248			'section' => 'actions',
249		];
250
251		$a['PageRestrictions'] = [
252			'type' => 'titlesmultiselect',
253			'label' => $this->msg( 'ipb-pages-label' )->text(),
254			'exists' => true,
255			'max' => 10,
256			'cssclass' => 'mw-block-restriction',
257			'showMissing' => false,
258			'excludeDynamicNamespaces' => true,
259			'input' => [
260				'autocomplete' => false
261			],
262			'section' => 'actions',
263		];
264
265		$a['NamespaceRestrictions'] = [
266			'type' => 'namespacesmultiselect',
267			'label' => $this->msg( 'ipb-namespaces-label' )->text(),
268			'exists' => true,
269			'cssclass' => 'mw-block-restriction',
270			'input' => [
271				'autocomplete' => false
272			],
273			'section' => 'actions',
274		];
275
276		$a['CreateAccount'] = [
277			'type' => 'check',
278			'label-message' => 'ipbcreateaccount',
279			'default' => true,
280			'section' => 'actions',
281		];
282
283		if ( $this->blockPermissionCheckerFactory
284			->newBlockPermissionChecker( null, $user )
285			->checkEmailPermissions()
286		) {
287			$a['DisableEmail'] = [
288				'type' => 'check',
289				'label-message' => 'ipbemailban',
290				'section' => 'actions',
291			];
292		}
293
294		if ( $blockAllowsUTEdit ) {
295			$a['DisableUTEdit'] = [
296				'type' => 'check',
297				'label-message' => 'ipb-disableusertalk',
298				'default' => false,
299				'section' => 'actions',
300			];
301		}
302
303		$defaultExpiry = $this->msg( 'ipb-default-expiry' )->inContentLanguage();
304		if ( $this->type === DatabaseBlock::TYPE_RANGE || $this->type === DatabaseBlock::TYPE_IP ) {
305			$defaultExpiryIP = $this->msg( 'ipb-default-expiry-ip' )->inContentLanguage();
306			if ( !$defaultExpiryIP->isDisabled() ) {
307				$defaultExpiry = $defaultExpiryIP;
308			}
309		}
310
311		$a['Expiry'] = [
312			'type' => 'expiry',
313			'required' => true,
314			'options' => $suggestedDurations,
315			'default' => $defaultExpiry->text(),
316			'section' => 'expiry',
317		];
318
319		$a['Reason'] = [
320			'type' => 'selectandother',
321			// HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
322			// (e.g. emojis) count for two each. This limit is overridden in JS to instead count
323			// Unicode codepoints.
324			'maxlength' => CommentStore::COMMENT_CHARACTER_LIMIT,
325			'maxlength-unit' => 'codepoints',
326			'options-message' => 'ipbreason-dropdown',
327			'section' => 'reason',
328		];
329
330		$a['AutoBlock'] = [
331			'type' => 'check',
332			'label-message' => 'ipbenableautoblock',
333			'default' => true,
334			'section' => 'options',
335		];
336
337		# Allow some users to hide name from block log, blocklist and listusers
338		if ( $this->getAuthority()->isAllowed( 'hideuser' ) ) {
339			$a['HideUser'] = [
340				'type' => 'check',
341				'label-message' => 'ipbhidename',
342				'cssclass' => 'mw-block-hideuser',
343				'section' => 'options',
344			];
345		}
346
347		# Watchlist their user page? (Only if user is logged in)
348		if ( $user->isRegistered() ) {
349			$a['Watch'] = [
350				'type' => 'check',
351				'label-message' => 'ipbwatchuser',
352				'section' => 'options',
353			];
354		}
355
356		$a['HardBlock'] = [
357			'type' => 'check',
358			'label-message' => 'ipb-hardblock',
359			'default' => false,
360			'section' => 'options',
361		];
362
363		# This is basically a copy of the Target field, but the user can't change it, so we
364		# can see if the warnings we maybe showed to the user before still apply
365		$a['PreviousTarget'] = [
366			'type' => 'hidden',
367			'default' => false,
368		];
369
370		# We'll turn this into a checkbox if we need to
371		$a['Confirm'] = [
372			'type' => 'hidden',
373			'default' => '',
374			'label-message' => 'ipb-confirm',
375			'cssclass' => 'mw-block-confirm',
376		];
377
378		$this->maybeAlterFormDefaults( $a );
379
380		// Allow extensions to add more fields
381		$this->getHookRunner()->onSpecialBlockModifyFormFields( $this, $a );
382
383		return $a;
384	}
385
386	/**
387	 * If the user has already been blocked with similar settings, load that block
388	 * and change the defaults for the form fields to match the existing settings.
389	 * @param array &$fields HTMLForm descriptor array
390	 */
391	protected function maybeAlterFormDefaults( &$fields ) {
392		# This will be overwritten by request data
393		$fields['Target']['default'] = (string)$this->target;
394
395		if ( $this->target ) {
396			$status = $this->blockUtils->validateTarget( $this->target );
397			if ( !$status->isOK() ) {
398				$errors = $status->getErrorsArray();
399				$this->preErrors = array_merge( $this->preErrors, $errors );
400			}
401		}
402
403		# This won't be
404		$fields['PreviousTarget']['default'] = (string)$this->target;
405
406		$block = DatabaseBlock::newFromTarget( $this->target );
407
408		// Populate fields if there is a block that is not an autoblock; if it is a range
409		// block, only populate the fields if the range is the same as $this->target
410		if ( $block instanceof DatabaseBlock && $block->getType() !== DatabaseBlock::TYPE_AUTO
411			&& ( $this->type != DatabaseBlock::TYPE_RANGE
412				|| $block->getTarget() == $this->target )
413		) {
414			$fields['HardBlock']['default'] = $block->isHardblock();
415			$fields['CreateAccount']['default'] = $block->isCreateAccountBlocked();
416			$fields['AutoBlock']['default'] = $block->isAutoblocking();
417
418			if ( isset( $fields['DisableEmail'] ) ) {
419				$fields['DisableEmail']['default'] = $block->isEmailBlocked();
420			}
421
422			if ( isset( $fields['HideUser'] ) ) {
423				$fields['HideUser']['default'] = $block->getHideName();
424			}
425
426			if ( isset( $fields['DisableUTEdit'] ) ) {
427				$fields['DisableUTEdit']['default'] = !$block->isUsertalkEditAllowed();
428			}
429
430			// If the username was hidden (ipb_deleted == 1), don't show the reason
431			// unless this user also has rights to hideuser: T37839
432			if ( !$block->getHideName() || $this->getAuthority()->isAllowed( 'hideuser' ) ) {
433				$fields['Reason']['default'] = $block->getReasonComment()->text;
434			} else {
435				$fields['Reason']['default'] = '';
436			}
437
438			if ( $this->getRequest()->wasPosted() ) {
439				# Ok, so we got a POST submission asking us to reblock a user.  So show the
440				# confirm checkbox; the user will only see it if they haven't previously
441				$fields['Confirm']['type'] = 'check';
442			} else {
443				# We got a target, but it wasn't a POST request, so the user must have gone
444				# to a link like [[Special:Block/User]].  We don't need to show the checkbox
445				# as long as they go ahead and block *that* user
446				$fields['Confirm']['default'] = 1;
447			}
448
449			if ( $block->getExpiry() == 'infinity' ) {
450				$fields['Expiry']['default'] = 'infinite';
451			} else {
452				$fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->getExpiry() );
453			}
454
455			if ( !$block->isSitewide() ) {
456				$fields['EditingRestriction']['default'] = 'partial';
457
458				$pageRestrictions = [];
459				$namespaceRestrictions = [];
460				foreach ( $block->getRestrictions() as $restriction ) {
461					if ( $restriction instanceof PageRestriction && $restriction->getTitle() ) {
462						$pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
463					} elseif ( $restriction instanceof NamespaceRestriction ) {
464						$namespaceRestrictions[] = $restriction->getValue();
465					}
466				}
467
468				// Sort the restrictions so they are in alphabetical order.
469				sort( $pageRestrictions );
470				$fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
471				sort( $namespaceRestrictions );
472				$fields['NamespaceRestrictions']['default'] = implode( "\n", $namespaceRestrictions );
473
474				if (
475					empty( $pageRestrictions ) &&
476					empty( $namespaceRestrictions )
477				) {
478					$fields['Editing']['default'] = false;
479				}
480			}
481
482			$this->alreadyBlocked = true;
483			$this->preErrors[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
484		}
485
486		if ( $this->alreadyBlocked || $this->getRequest()->wasPosted()
487			|| $this->getRequest()->getCheck( 'wpCreateAccount' )
488		) {
489			$this->getOutput()->addJsConfigVars( 'wgCreateAccountDirty', true );
490		}
491
492		# We always need confirmation to do HideUser
493		if ( $this->requestedHideUser ) {
494			$fields['Confirm']['type'] = 'check';
495			unset( $fields['Confirm']['default'] );
496			$this->preErrors[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
497		}
498
499		# Or if the user is trying to block themselves
500		if ( (string)$this->target === $this->getUser()->getName() ) {
501			$fields['Confirm']['type'] = 'check';
502			unset( $fields['Confirm']['default'] );
503			$this->preErrors[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
504		}
505	}
506
507	/**
508	 * Add header elements like block log entries, etc.
509	 * @return string
510	 */
511	protected function preText() {
512		$this->getOutput()->addModuleStyles( [
513			'mediawiki.widgets.TagMultiselectWidget.styles',
514			'mediawiki.special',
515		] );
516		$this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
517
518		$blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
519		$text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
520
521		$otherBlockMessages = [];
522		if ( $this->target !== null ) {
523			$targetName = $this->target;
524			if ( $this->target instanceof User ) {
525				$targetName = $this->target->getName();
526			}
527			# Get other blocks, i.e. from GlobalBlocking or TorBlock extension
528			$this->getHookRunner()->onOtherBlockLogLink(
529				$otherBlockMessages, $targetName );
530
531			if ( count( $otherBlockMessages ) ) {
532				$s = Html::rawElement(
533					'h2',
534					[],
535					$this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
536				) . "\n";
537
538				$list = '';
539
540				foreach ( $otherBlockMessages as $link ) {
541					$list .= Html::rawElement( 'li', [], $link ) . "\n";
542				}
543
544				$s .= Html::rawElement(
545					'ul',
546					[ 'class' => 'mw-blockip-alreadyblocked' ],
547					$list
548				) . "\n";
549
550				$text .= $s;
551			}
552		}
553
554		return $text;
555	}
556
557	/**
558	 * Add footer elements to the form
559	 * @return string
560	 */
561	protected function postText() {
562		$links = [];
563
564		$this->getOutput()->addModuleStyles( 'mediawiki.special' );
565
566		$linkRenderer = $this->getLinkRenderer();
567		# Link to the user's contributions, if applicable
568		if ( $this->target instanceof User ) {
569			$contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
570			$links[] = $linkRenderer->makeLink(
571				$contribsPage,
572				$this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->text()
573			);
574		}
575
576		# Link to unblock the specified user, or to a blank unblock form
577		if ( $this->target instanceof User ) {
578			$message = $this->msg(
579				'ipb-unblock-addr',
580				wfEscapeWikiText( $this->target->getName() )
581			)->parse();
582			$list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
583		} else {
584			$message = $this->msg( 'ipb-unblock' )->parse();
585			$list = SpecialPage::getTitleFor( 'Unblock' );
586		}
587		$links[] = $linkRenderer->makeKnownLink(
588			$list,
589			new HtmlArmor( $message )
590		);
591
592		# Link to the block list
593		$links[] = $linkRenderer->makeKnownLink(
594			SpecialPage::getTitleFor( 'BlockList' ),
595			$this->msg( 'ipb-blocklist' )->text()
596		);
597
598		# Link to edit the block dropdown reasons, if applicable
599		if ( $this->getAuthority()->isAllowed( 'editinterface' ) ) {
600			$links[] = $linkRenderer->makeKnownLink(
601				$this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
602				$this->msg( 'ipb-edit-dropdown' )->text(),
603				[],
604				[ 'action' => 'edit' ]
605			);
606		}
607
608		$text = Html::rawElement(
609			'p',
610			[ 'class' => 'mw-ipb-conveniencelinks' ],
611			$this->getLanguage()->pipeList( $links )
612		);
613
614		$userTitle = self::getTargetUserTitle( $this->target );
615		if ( $userTitle ) {
616			# Get relevant extracts from the block and suppression logs, if possible
617			$out = '';
618
619			LogEventsList::showLogExtract(
620				$out,
621				'block',
622				$userTitle,
623				'',
624				[
625					'lim' => 10,
626					'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
627					'showIfEmpty' => false
628				]
629			);
630			$text .= $out;
631
632			# Add suppression block entries if allowed
633			if ( $this->getAuthority()->isAllowed( 'suppressionlog' ) ) {
634				LogEventsList::showLogExtract(
635					$out,
636					'suppress',
637					$userTitle,
638					'',
639					[
640						'lim' => 10,
641						'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
642						'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
643						'showIfEmpty' => false
644					]
645				);
646
647				$text .= $out;
648			}
649		}
650
651		return $text;
652	}
653
654	/**
655	 * Get a user page target for things like logs.
656	 * This handles account and IP range targets.
657	 * @param User|string $target
658	 * @return Title|null
659	 */
660	protected static function getTargetUserTitle( $target ) {
661		if ( $target instanceof User ) {
662			return $target->getUserPage();
663		} elseif ( IPUtils::isIPAddress( $target ) ) {
664			return Title::makeTitleSafe( NS_USER, $target );
665		}
666
667		return null;
668	}
669
670	/**
671	 * Get the target and type, given the request and the subpage parameter.
672	 * Several parameters are handled for backwards compatability. 'wpTarget' is
673	 * prioritized, since it matches the HTML form.
674	 *
675	 * @deprecated since 1.36. Use BlockUtils::parseBlockTarget directly instead.
676	 *
677	 * @param string|null $par Subpage parameter passed to setup, or data value from
678	 *  the HTMLForm
679	 * @param WebRequest|null $request Optionally try and get data from a request too
680	 * @return array [ User|string|null, DatabaseBlock::TYPE_ constant|null ]
681	 * @phan-return array{0:User|string|null,1:int|null}
682	 */
683	public static function getTargetAndType( ?string $par, WebRequest $request = null ) {
684		if ( !$request instanceof WebRequest ) {
685			return MediaWikiServices::getInstance()->getBlockUtils()->parseBlockTarget( $par );
686		}
687
688		$possibleTargets = [
689			$request->getVal( 'wpTarget', null ),
690			$par,
691			$request->getVal( 'ip', null ),
692			// B/C @since 1.18
693			$request->getVal( 'wpBlockAddress', null ),
694		];
695		foreach ( $possibleTargets as $possibleTarget ) {
696			$targetAndType = MediaWikiServices::getInstance()
697				->getBlockUtils()
698				->parseBlockTarget( $possibleTarget );
699			// If type is not null then target is valid
700			if ( $targetAndType[ 1 ] !== null ) {
701				break;
702			}
703		}
704		return $targetAndType;
705	}
706
707	/**
708	 * Validate a block target.
709	 *
710	 * @since 1.21
711	 * @deprecated since 1.36, use BlockUtils service instead
712	 *             (note: service does not call BlockPermissionChecker::checkBlockPermissions)
713	 * @param string $value Block target to check
714	 * @param User $user Performer of the block
715	 * @return Status
716	 */
717	public static function validateTarget( $value, User $user ) {
718		wfDeprecated( __METHOD__, '1.36' );
719
720		$status = MediaWikiServices::getInstance()->getBlockUtils()->validateTarget( $value );
721
722		// This is here to make validateTarget to not change its behavior
723		// BlockUtils does not check checkUnblockSelf.
724		list( $target, $type ) = self::getTargetAndType( $value );
725		if ( $type === AbstractBlock::TYPE_USER ) {
726			$unblockStatus = self::checkUnblockSelf( $target, $user );
727			if ( $unblockStatus !== true ) {
728				$status->fatal( 'badaccess', $unblockStatus );
729			}
730		}
731
732		return $status;
733	}
734
735	/**
736	 * Given the form data, actually implement a block.
737	 *
738	 * @deprecated since 1.36, use BlockUserFactory service instead
739	 * @param array $data
740	 * @param IContextSource $context
741	 * @return bool|array
742	 */
743	public static function processForm( array $data, IContextSource $context ) {
744		$services = MediaWikiServices::getInstance();
745		return self::processFormInternal(
746			$data,
747			$context->getAuthority(),
748			$services->getBlockUserFactory(),
749			$services->getBlockUtils()
750		);
751	}
752
753	/**
754	 * Implementation details for processForm
755	 * Own function to allow sharing the deprecated code with non-deprecated and service code
756	 *
757	 * @param array $data
758	 * @param Authority $performer
759	 * @param BlockUserFactory $blockUserFactory
760	 * @param BlockUtils $blockUtils
761	 * @return bool|array
762	 */
763	private static function processFormInternal(
764		array $data,
765		Authority $performer,
766		BlockUserFactory $blockUserFactory,
767		BlockUtils $blockUtils
768	) {
769		$isPartialBlock = isset( $data['EditingRestriction'] ) &&
770			$data['EditingRestriction'] === 'partial';
771
772		# This might have been a hidden field or a checkbox, so interesting data
773		# can come from it
774		$data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
775
776		# If the user has done the form 'properly', they won't even have been given the
777		# option to suppress-block unless they have the 'hideuser' permission
778		if ( !isset( $data['HideUser'] ) ) {
779			$data['HideUser'] = false;
780		}
781
782		/** @var User $target */
783		list( $target, $type ) = $blockUtils->parseBlockTarget( $data['Target'] );
784		if ( $type == DatabaseBlock::TYPE_USER ) {
785			$user = $target;
786			$target = $user->getName();
787			$userId = $user->getId();
788
789			# Give admins a heads-up before they go and block themselves.  Much messier
790			# to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
791			# permission anyway, although the code does allow for it.
792			# Note: Important to use $target instead of $data['Target']
793			# since both $data['PreviousTarget'] and $target are normalized
794			# but $data['target'] gets overridden by (non-normalized) request variable
795			# from previous request.
796			if ( $target === $performer->getUser()->getName() &&
797				( $data['PreviousTarget'] !== $target || !$data['Confirm'] )
798			) {
799				return [ 'ipb-blockingself', 'ipb-confirmaction' ];
800			}
801
802			if ( $data['HideUser'] && !$data['Confirm'] ) {
803				return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
804			}
805		} elseif ( $type == DatabaseBlock::TYPE_RANGE ) {
806			$user = null;
807			$userId = 0;
808		} elseif ( $type == DatabaseBlock::TYPE_IP ) {
809			$user = null;
810			$target = $target->getName();
811			$userId = 0;
812		} else {
813			# This should have been caught in the form field validation
814			return [ 'badipaddress' ];
815		}
816
817		// Reason, to be passed to the block object. For default values of reason, see
818		// HTMLSelectAndOtherField::getDefault
819		// @phan-suppress-next-line PhanPluginDuplicateConditionalNullCoalescing
820		$blockReason = isset( $data['Reason'][0] ) ? $data['Reason'][0] : '';
821
822		$pageRestrictions = [];
823		$namespaceRestrictions = [];
824		if ( $isPartialBlock ) {
825			if ( isset( $data['PageRestrictions'] ) && $data['PageRestrictions'] !== '' ) {
826				$titles = explode( "\n", $data['PageRestrictions'] );
827				$pageRestrictions = [];
828				foreach ( $titles as $title ) {
829					$pageRestrictions[] = PageRestriction::newFromTitle( $title );
830				}
831			}
832			if ( isset( $data['NamespaceRestrictions'] ) && $data['NamespaceRestrictions'] !== '' ) {
833				$namespaceRestrictions = array_map( static function ( $id ) {
834					return new NamespaceRestriction( 0, $id );
835				}, explode( "\n", $data['NamespaceRestrictions'] ) );
836			}
837		}
838		$restrictions = ( array_merge( $pageRestrictions, $namespaceRestrictions ) );
839
840		if ( !isset( $data['Tags'] ) ) {
841			$data['Tags'] = [];
842		}
843
844		$blockOptions = [
845			'isCreateAccountBlocked' => $data['CreateAccount'],
846			'isHardBlock' => $data['HardBlock'],
847			'isAutoblocking' => $data['AutoBlock'],
848			'isHideUser' => $data['HideUser'],
849			'isPartial' => $isPartialBlock,
850		];
851
852		if ( isset( $data['DisableUTEdit'] ) ) {
853			$blockOptions['isUserTalkEditBlocked'] = $data['DisableUTEdit'];
854		}
855		if ( isset( $data['DisableEmail'] ) ) {
856			$blockOptions['isEmailBlocked'] = $data['DisableEmail'];
857		}
858
859		$blockUser = $blockUserFactory->newBlockUser(
860			$target,
861			$performer,
862			$data['Expiry'],
863			$blockReason,
864			$blockOptions,
865			$restrictions,
866			$data['Tags']
867		);
868
869		# Indicates whether the user is confirming the block and is aware of
870		# the conflict (did not change the block target in the meantime)
871		$blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
872			&& $data['PreviousTarget'] !== $target );
873
874		# Special case for API - T34434
875		$reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
876
877		$doReblock = !$blockNotConfirmed && !$reblockNotAllowed;
878
879		$status = $blockUser->placeBlock( $doReblock );
880		if ( !$status->isOK() ) {
881			return $status;
882		}
883
884		# Can't watch a rangeblock
885		if ( $type != DatabaseBlock::TYPE_RANGE && $data['Watch'] ) {
886			WatchAction::doWatch(
887				Title::makeTitle( NS_USER, $target ),
888				$performer,
889				User::IGNORE_USER_RIGHTS
890			);
891		}
892
893		return true;
894	}
895
896	/**
897	 * Get an array of suggested block durations from MediaWiki:Ipboptions
898	 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
899	 *     to the standard "**<duration>|<displayname>" format?
900	 * @param Language|null $lang The language to get the durations in, or null to use
901	 *     the wiki's content language
902	 * @param bool $includeOther Whether to include the 'other' option in the list of
903	 *     suggestions
904	 * @return string[]
905	 */
906	public static function getSuggestedDurations( Language $lang = null, $includeOther = true ) {
907		$msg = $lang === null
908			? wfMessage( 'ipboptions' )->inContentLanguage()->text()
909			: wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
910
911		if ( $msg == '-' ) {
912			return [];
913		}
914
915		$a = XmlSelect::parseOptionsMessage( $msg );
916
917		if ( $a && $includeOther ) {
918			// if options exist, add other to the end instead of the begining (which
919			// is what happens by default).
920			$a[ wfMessage( 'ipbother' )->text() ] = 'other';
921		}
922
923		return $a;
924	}
925
926	/**
927	 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
928	 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
929	 *
930	 * @deprecated since 1.36, use BlockUser::parseExpiryInput instead
931	 *
932	 * @param string $expiry Whatever was typed into the form
933	 * @return string|bool Timestamp or 'infinity' or false on error.
934	 */
935	public static function parseExpiryInput( $expiry ) {
936		return BlockUser::parseExpiryInput( $expiry );
937	}
938
939	/**
940	 * Can we do an email block?
941	 *
942	 * @deprecated since 1.36, use BlockPermissionChecker service instead
943	 * @param UserIdentity $user The sysop wanting to make a block
944	 * @return bool
945	 */
946	public static function canBlockEmail( UserIdentity $user ) {
947		return MediaWikiServices::getInstance()
948			->getBlockPermissionCheckerFactory()
949			->newBlockPermissionChecker( null, User::newFromIdentity( $user ) )
950			->checkEmailPermissions();
951	}
952
953	/**
954	 * T17810: Sitewide blocked admins should not be able to block/unblock
955	 * others with one exception; they can block the user who blocked them,
956	 * to reduce advantage of a malicious account blocking all admins (T150826).
957	 *
958	 * T208965: Partially blocked admins can block and unblock others as normal.
959	 *
960	 * @deprecated since 1.36, use BlockPermissionChecker instead
961	 * @param User|string|null $target Target to block or unblock; could be a User object,
962	 *   or username/IP address, or null when the target is not known yet (e.g. when
963	 *   displaying Special:Block)
964	 * @param Authority $performer User doing the request
965	 * @return bool|string True or error message key
966	 */
967	public static function checkUnblockSelf( $target, Authority $performer ) {
968		return MediaWikiServices::getInstance()
969			->getBlockPermissionCheckerFactory()
970			->newBlockPermissionChecker( $target, $performer )
971			->checkBlockPermissions();
972	}
973
974	/**
975	 * Process the form on POST submission.
976	 * @param array $data
977	 * @param HTMLForm|null $form
978	 * @return bool|array True for success, false for didn't-try, array of errors on failure
979	 */
980	public function onSubmit( array $data, HTMLForm $form = null ) {
981		// If "Editing" checkbox is unchecked, the block must be a partial block affecting
982		// actions other than editing, and there must be no restrictions.
983		if ( isset( $data['Editing'] ) && $data['Editing'] === false ) {
984			$data['EditingRestriction'] = 'partial';
985			$data['PageRestrictions'] = '';
986			$data['NamespaceRestrictions'] = '';
987		}
988		return self::processFormInternal(
989			$data,
990			$this->getAuthority(),
991			$this->blockUserFactory,
992			$this->blockUtils
993		);
994	}
995
996	/**
997	 * Do something exciting on successful processing of the form, most likely to show a
998	 * confirmation message
999	 */
1000	public function onSuccess() {
1001		$out = $this->getOutput();
1002		$out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1003		$out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
1004	}
1005
1006	/**
1007	 * Return an array of subpages beginning with $search that this special page will accept.
1008	 *
1009	 * @param string $search Prefix to search for
1010	 * @param int $limit Maximum number of results to return (usually 10)
1011	 * @param int $offset Number of results to skip (usually 0)
1012	 * @return string[] Matching subpages
1013	 */
1014	public function prefixSearchSubpages( $search, $limit, $offset ) {
1015		$search = $this->userNameUtils->getCanonical( $search );
1016		if ( !$search ) {
1017			// No prefix suggestion for invalid user
1018			return [];
1019		}
1020		// Autocomplete subpage as user list - public to allow caching
1021		return $this->userNamePrefixSearch
1022			->search( UserNamePrefixSearch::AUDIENCE_PUBLIC, $search, $limit, $offset );
1023	}
1024
1025	protected function getGroupName() {
1026		return 'users';
1027	}
1028}
1029