Merge "Simplify checking for widgets on special block page"
[lhc/web/wiklou.git] / includes / specials / SpecialBlock.php
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
24 use MediaWiki\Block\BlockRestriction;
25 use MediaWiki\Block\Restriction\PageRestriction;
26 use MediaWiki\Block\Restriction\NamespaceRestriction;
27
28 /**
29 * A special page that allows users with 'block' right to block users from
30 * editing pages and other actions
31 *
32 * @ingroup SpecialPage
33 */
34 class SpecialBlock extends FormSpecialPage {
35 /** @var User|string|null User to be blocked, as passed either by parameter (url?wpTarget=Foo)
36 * or as subpage (Special:Block/Foo) */
37 protected $target;
38
39 /** @var int Block::TYPE_ constant */
40 protected $type;
41
42 /** @var User|string The previous block target */
43 protected $previousTarget;
44
45 /** @var bool Whether the previous submission of the form asked for HideUser */
46 protected $requestedHideUser;
47
48 /** @var bool */
49 protected $alreadyBlocked;
50
51 /** @var array */
52 protected $preErrors = [];
53
54 public function __construct() {
55 parent::__construct( 'Block', 'block' );
56 }
57
58 public function doesWrites() {
59 return true;
60 }
61
62 /**
63 * Checks that the user can unblock themselves if they are trying to do so
64 *
65 * @param User $user
66 * @throws ErrorPageError
67 */
68 protected function checkExecutePermissions( User $user ) {
69 parent::checkExecutePermissions( $user );
70 # T17810: blocked admins should have limited access here
71 $status = self::checkUnblockSelf( $this->target, $user );
72 if ( $status !== true ) {
73 throw new ErrorPageError( 'badaccess', $status );
74 }
75 }
76
77 /**
78 * We allow certain special cases where user is blocked
79 *
80 * @return bool
81 */
82 public function requiresUnblock() {
83 return false;
84 }
85
86 /**
87 * Handle some magic here
88 *
89 * @param string $par
90 */
91 protected function setParameter( $par ) {
92 # Extract variables from the request. Try not to get into a situation where we
93 # need to extract *every* variable from the form just for processing here, but
94 # there are legitimate uses for some variables
95 $request = $this->getRequest();
96 list( $this->target, $this->type ) = self::getTargetAndType( $par, $request );
97 if ( $this->target instanceof User ) {
98 # Set the 'relevant user' in the skin, so it displays links like Contributions,
99 # User logs, UserRights, etc.
100 $this->getSkin()->setRelevantUser( $this->target );
101 }
102
103 list( $this->previousTarget, /*...*/ ) =
104 Block::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
105 $this->requestedHideUser = $request->getBool( 'wpHideUser' );
106 }
107
108 /**
109 * Customizes the HTMLForm a bit
110 *
111 * @param HTMLForm $form
112 */
113 protected function alterForm( HTMLForm $form ) {
114 $form->setHeaderText( '' );
115 $form->setSubmitDestructive();
116
117 $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
118 $form->setSubmitTextMsg( $msg );
119
120 $this->addHelpLink( 'Help:Blocking users' );
121
122 # Don't need to do anything if the form has been posted
123 if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
124 $s = $form->formatErrors( $this->preErrors );
125 if ( $s ) {
126 $form->addHeaderText( Html::rawElement(
127 'div',
128 [ 'class' => 'error' ],
129 $s
130 ) );
131 }
132 }
133 }
134
135 protected function getDisplayFormat() {
136 return 'ooui';
137 }
138
139 /**
140 * Get the HTMLForm descriptor array for the block form
141 * @return array
142 */
143 protected function getFormFields() {
144 $conf = $this->getConfig();
145 $enablePartialBlocks = $conf->get( 'EnablePartialBlocks' );
146 $blockAllowsUTEdit = $conf->get( 'BlockAllowsUTEdit' );
147
148 $this->getOutput()->enableOOUI();
149
150 $user = $this->getUser();
151
152 $suggestedDurations = self::getSuggestedDurations();
153
154 $a = [];
155
156 $a['Target'] = [
157 'type' => 'user',
158 'ipallowed' => true,
159 'iprange' => true,
160 'id' => 'mw-bi-target',
161 'size' => '45',
162 'autofocus' => true,
163 'required' => true,
164 'validation-callback' => [ __CLASS__, 'validateTargetField' ],
165 'section' => 'target',
166 ];
167
168 $a['Editing'] = [
169 'type' => 'check',
170 'label-message' => 'block-prevent-edit',
171 'default' => true,
172 'section' => 'actions',
173 'disabled' => $enablePartialBlocks ? false : true,
174 ];
175
176 if ( $enablePartialBlocks ) {
177 $a['EditingRestriction'] = [
178 'type' => 'radio',
179 'cssclass' => 'mw-block-editing-restriction',
180 'options' => [
181 $this->msg( 'ipb-sitewide' )->escaped() .
182 new \OOUI\LabelWidget( [
183 'classes' => [ 'oo-ui-inline-help' ],
184 'label' => $this->msg( 'ipb-sitewide-help' )->text(),
185 ] ) => 'sitewide',
186 $this->msg( 'ipb-partial' )->escaped() .
187 new \OOUI\LabelWidget( [
188 'classes' => [ 'oo-ui-inline-help' ],
189 'label' => $this->msg( 'ipb-partial-help' )->text(),
190 ] ) => 'partial',
191 ],
192 'section' => 'actions',
193 ];
194 $a['PageRestrictions'] = [
195 'type' => 'titlesmultiselect',
196 'label' => $this->msg( 'ipb-pages-label' )->text(),
197 'exists' => true,
198 'max' => 10,
199 'cssclass' => 'mw-block-restriction',
200 'showMissing' => false,
201 'excludeDynamicNamespaces' => true,
202 'input' => [
203 'autocomplete' => false
204 ],
205 'section' => 'actions',
206 ];
207 $a['NamespaceRestrictions'] = [
208 'type' => 'namespacesmultiselect',
209 'label' => $this->msg( 'ipb-namespaces-label' )->text(),
210 'exists' => true,
211 'cssclass' => 'mw-block-restriction',
212 'input' => [
213 'autocomplete' => false
214 ],
215 'section' => 'actions',
216 ];
217 }
218
219 $a['CreateAccount'] = [
220 'type' => 'check',
221 'label-message' => 'ipbcreateaccount',
222 'default' => true,
223 'section' => 'actions',
224 ];
225
226 if ( self::canBlockEmail( $user ) ) {
227 $a['DisableEmail'] = [
228 'type' => 'check',
229 'label-message' => 'ipbemailban',
230 'section' => 'actions',
231 ];
232 }
233
234 if ( $blockAllowsUTEdit ) {
235 $a['DisableUTEdit'] = [
236 'type' => 'check',
237 'label-message' => 'ipb-disableusertalk',
238 'default' => false,
239 'section' => 'actions',
240 ];
241 }
242
243 $a['Expiry'] = [
244 'type' => 'expiry',
245 'required' => true,
246 'options' => $suggestedDurations,
247 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
248 'section' => 'expiry',
249 ];
250
251 $a['Reason'] = [
252 'type' => 'selectandother',
253 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
254 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
255 // Unicode codepoints.
256 'maxlength' => CommentStore::COMMENT_CHARACTER_LIMIT,
257 'maxlength-unit' => 'codepoints',
258 'options-message' => 'ipbreason-dropdown',
259 'section' => 'reason',
260 ];
261
262 $a['AutoBlock'] = [
263 'type' => 'check',
264 'label-message' => 'ipbenableautoblock',
265 'default' => true,
266 'section' => 'options',
267 ];
268
269 # Allow some users to hide name from block log, blocklist and listusers
270 if ( $user->isAllowed( 'hideuser' ) ) {
271 $a['HideUser'] = [
272 'type' => 'check',
273 'label-message' => 'ipbhidename',
274 'cssclass' => 'mw-block-hideuser',
275 'section' => 'options',
276 ];
277 }
278
279 # Watchlist their user page? (Only if user is logged in)
280 if ( $user->isLoggedIn() ) {
281 $a['Watch'] = [
282 'type' => 'check',
283 'label-message' => 'ipbwatchuser',
284 'section' => 'options',
285 ];
286 }
287
288 $a['HardBlock'] = [
289 'type' => 'check',
290 'label-message' => 'ipb-hardblock',
291 'default' => false,
292 'section' => 'options',
293 ];
294
295 # This is basically a copy of the Target field, but the user can't change it, so we
296 # can see if the warnings we maybe showed to the user before still apply
297 $a['PreviousTarget'] = [
298 'type' => 'hidden',
299 'default' => false,
300 ];
301
302 # We'll turn this into a checkbox if we need to
303 $a['Confirm'] = [
304 'type' => 'hidden',
305 'default' => '',
306 'label-message' => 'ipb-confirm',
307 'cssclass' => 'mw-block-confirm',
308 ];
309
310 $this->maybeAlterFormDefaults( $a );
311
312 // Allow extensions to add more fields
313 Hooks::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
314
315 return $a;
316 }
317
318 /**
319 * If the user has already been blocked with similar settings, load that block
320 * and change the defaults for the form fields to match the existing settings.
321 * @param array &$fields HTMLForm descriptor array
322 */
323 protected function maybeAlterFormDefaults( &$fields ) {
324 # This will be overwritten by request data
325 $fields['Target']['default'] = (string)$this->target;
326
327 if ( $this->target ) {
328 $status = self::validateTarget( $this->target, $this->getUser() );
329 if ( !$status->isOK() ) {
330 $errors = $status->getErrorsArray();
331 $this->preErrors = array_merge( $this->preErrors, $errors );
332 }
333 }
334
335 # This won't be
336 $fields['PreviousTarget']['default'] = (string)$this->target;
337
338 $block = Block::newFromTarget( $this->target );
339
340 // Populate fields if there is a block that is not an autoblock; if it is a range
341 // block, only populate the fields if the range is the same as $this->target
342 if ( $block instanceof Block && $block->getType() !== Block::TYPE_AUTO
343 && ( $this->type != Block::TYPE_RANGE
344 || $block->getTarget() == $this->target )
345 ) {
346 $fields['HardBlock']['default'] = $block->isHardblock();
347 $fields['CreateAccount']['default'] = $block->isCreateAccountBlocked();
348 $fields['AutoBlock']['default'] = $block->isAutoblocking();
349
350 if ( isset( $fields['DisableEmail'] ) ) {
351 $fields['DisableEmail']['default'] = $block->isEmailBlocked();
352 }
353
354 if ( isset( $fields['HideUser'] ) ) {
355 $fields['HideUser']['default'] = $block->getHideName();
356 }
357
358 if ( isset( $fields['DisableUTEdit'] ) ) {
359 $fields['DisableUTEdit']['default'] = !$block->isUsertalkEditAllowed();
360 }
361
362 // If the username was hidden (ipb_deleted == 1), don't show the reason
363 // unless this user also has rights to hideuser: T37839
364 if ( !$block->getHideName() || $this->getUser()->isAllowed( 'hideuser' ) ) {
365 $fields['Reason']['default'] = $block->getReason();
366 } else {
367 $fields['Reason']['default'] = '';
368 }
369
370 if ( $this->getRequest()->wasPosted() ) {
371 # Ok, so we got a POST submission asking us to reblock a user. So show the
372 # confirm checkbox; the user will only see it if they haven't previously
373 $fields['Confirm']['type'] = 'check';
374 } else {
375 # We got a target, but it wasn't a POST request, so the user must have gone
376 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
377 # as long as they go ahead and block *that* user
378 $fields['Confirm']['default'] = 1;
379 }
380
381 if ( $block->getExpiry() == 'infinity' ) {
382 $fields['Expiry']['default'] = 'infinite';
383 } else {
384 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->getExpiry() );
385 }
386
387 $this->alreadyBlocked = true;
388 $this->preErrors[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
389 }
390
391 if ( $this->alreadyBlocked || $this->getRequest()->wasPosted()
392 || $this->getRequest()->getCheck( 'wpCreateAccount' )
393 ) {
394 $this->getOutput()->addJsConfigVars( 'wgCreateAccountDirty', true );
395 }
396
397 # We always need confirmation to do HideUser
398 if ( $this->requestedHideUser ) {
399 $fields['Confirm']['type'] = 'check';
400 unset( $fields['Confirm']['default'] );
401 $this->preErrors[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
402 }
403
404 # Or if the user is trying to block themselves
405 if ( (string)$this->target === $this->getUser()->getName() ) {
406 $fields['Confirm']['type'] = 'check';
407 unset( $fields['Confirm']['default'] );
408 $this->preErrors[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
409 }
410
411 if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
412 if ( $block instanceof Block && !$block->isSitewide() ) {
413 $fields['EditingRestriction']['default'] = 'partial';
414 } else {
415 $fields['EditingRestriction']['default'] = 'sitewide';
416 }
417
418 if ( $block instanceof Block ) {
419 $pageRestrictions = [];
420 $namespaceRestrictions = [];
421 foreach ( $block->getRestrictions() as $restriction ) {
422 switch ( $restriction->getType() ) {
423 case PageRestriction::TYPE:
424 if ( $restriction->getTitle() ) {
425 $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
426 }
427 break;
428 case NamespaceRestriction::TYPE:
429 $namespaceRestrictions[] = $restriction->getValue();
430 break;
431 }
432 }
433
434 if (
435 !$block->isSitewide() &&
436 empty( $pageRestrictions ) &&
437 empty( $namespaceRestrictions )
438 ) {
439 $fields['Editing']['default'] = false;
440 }
441
442 // Sort the restrictions so they are in alphabetical order.
443 sort( $pageRestrictions );
444 $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
445 sort( $namespaceRestrictions );
446 $fields['NamespaceRestrictions']['default'] = implode( "\n", $namespaceRestrictions );
447 }
448 }
449 }
450
451 /**
452 * Add header elements like block log entries, etc.
453 * @return string
454 */
455 protected function preText() {
456 $this->getOutput()->addModuleStyles( [
457 'mediawiki.widgets.TagMultiselectWidget.styles',
458 'mediawiki.special',
459 ] );
460 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
461
462 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
463 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
464
465 $otherBlockMessages = [];
466 if ( $this->target !== null ) {
467 $targetName = $this->target;
468 if ( $this->target instanceof User ) {
469 $targetName = $this->target->getName();
470 }
471 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
472 Hooks::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
473
474 if ( count( $otherBlockMessages ) ) {
475 $s = Html::rawElement(
476 'h2',
477 [],
478 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
479 ) . "\n";
480
481 $list = '';
482
483 foreach ( $otherBlockMessages as $link ) {
484 $list .= Html::rawElement( 'li', [], $link ) . "\n";
485 }
486
487 $s .= Html::rawElement(
488 'ul',
489 [ 'class' => 'mw-blockip-alreadyblocked' ],
490 $list
491 ) . "\n";
492
493 $text .= $s;
494 }
495 }
496
497 return $text;
498 }
499
500 /**
501 * Add footer elements to the form
502 * @return string
503 */
504 protected function postText() {
505 $links = [];
506
507 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
508
509 $linkRenderer = $this->getLinkRenderer();
510 # Link to the user's contributions, if applicable
511 if ( $this->target instanceof User ) {
512 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
513 $links[] = $linkRenderer->makeLink(
514 $contribsPage,
515 $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->text()
516 );
517 }
518
519 # Link to unblock the specified user, or to a blank unblock form
520 if ( $this->target instanceof User ) {
521 $message = $this->msg(
522 'ipb-unblock-addr',
523 wfEscapeWikiText( $this->target->getName() )
524 )->parse();
525 $list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
526 } else {
527 $message = $this->msg( 'ipb-unblock' )->parse();
528 $list = SpecialPage::getTitleFor( 'Unblock' );
529 }
530 $links[] = $linkRenderer->makeKnownLink(
531 $list,
532 new HtmlArmor( $message )
533 );
534
535 # Link to the block list
536 $links[] = $linkRenderer->makeKnownLink(
537 SpecialPage::getTitleFor( 'BlockList' ),
538 $this->msg( 'ipb-blocklist' )->text()
539 );
540
541 $user = $this->getUser();
542
543 # Link to edit the block dropdown reasons, if applicable
544 if ( $user->isAllowed( 'editinterface' ) ) {
545 $links[] = $linkRenderer->makeKnownLink(
546 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
547 $this->msg( 'ipb-edit-dropdown' )->text(),
548 [],
549 [ 'action' => 'edit' ]
550 );
551 }
552
553 $text = Html::rawElement(
554 'p',
555 [ 'class' => 'mw-ipb-conveniencelinks' ],
556 $this->getLanguage()->pipeList( $links )
557 );
558
559 $userTitle = self::getTargetUserTitle( $this->target );
560 if ( $userTitle ) {
561 # Get relevant extracts from the block and suppression logs, if possible
562 $out = '';
563
564 LogEventsList::showLogExtract(
565 $out,
566 'block',
567 $userTitle,
568 '',
569 [
570 'lim' => 10,
571 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
572 'showIfEmpty' => false
573 ]
574 );
575 $text .= $out;
576
577 # Add suppression block entries if allowed
578 if ( $user->isAllowed( 'suppressionlog' ) ) {
579 LogEventsList::showLogExtract(
580 $out,
581 'suppress',
582 $userTitle,
583 '',
584 [
585 'lim' => 10,
586 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
587 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
588 'showIfEmpty' => false
589 ]
590 );
591
592 $text .= $out;
593 }
594 }
595
596 return $text;
597 }
598
599 /**
600 * Get a user page target for things like logs.
601 * This handles account and IP range targets.
602 * @param User|string $target
603 * @return Title|null
604 */
605 protected static function getTargetUserTitle( $target ) {
606 if ( $target instanceof User ) {
607 return $target->getUserPage();
608 } elseif ( IP::isIPAddress( $target ) ) {
609 return Title::makeTitleSafe( NS_USER, $target );
610 }
611
612 return null;
613 }
614
615 /**
616 * Determine the target of the block, and the type of target
617 * @todo Should be in Block.php?
618 * @param string $par Subpage parameter passed to setup, or data value from
619 * the HTMLForm
620 * @param WebRequest|null $request Optionally try and get data from a request too
621 * @return array [ User|string|null, Block::TYPE_ constant|null ]
622 * @phan-return array{0:User|string|null,1:int|null}
623 */
624 public static function getTargetAndType( $par, WebRequest $request = null ) {
625 $i = 0;
626 $target = null;
627
628 while ( true ) {
629 switch ( $i++ ) {
630 case 0:
631 # The HTMLForm will check wpTarget first and only if it doesn't get
632 # a value use the default, which will be generated from the options
633 # below; so this has to have a higher precedence here than $par, or
634 # we could end up with different values in $this->target and the HTMLForm!
635 if ( $request instanceof WebRequest ) {
636 $target = $request->getText( 'wpTarget', null );
637 }
638 break;
639 case 1:
640 $target = $par;
641 break;
642 case 2:
643 if ( $request instanceof WebRequest ) {
644 $target = $request->getText( 'ip', null );
645 }
646 break;
647 case 3:
648 # B/C @since 1.18
649 if ( $request instanceof WebRequest ) {
650 $target = $request->getText( 'wpBlockAddress', null );
651 }
652 break;
653 case 4:
654 break 2;
655 }
656
657 list( $target, $type ) = Block::parseTarget( $target );
658
659 if ( $type !== null ) {
660 return [ $target, $type ];
661 }
662 }
663
664 return [ null, null ];
665 }
666
667 /**
668 * HTMLForm field validation-callback for Target field.
669 * @since 1.18
670 * @param string $value
671 * @param array $alldata
672 * @param HTMLForm $form
673 * @return Message
674 */
675 public static function validateTargetField( $value, $alldata, $form ) {
676 $status = self::validateTarget( $value, $form->getUser() );
677 if ( !$status->isOK() ) {
678 $errors = $status->getErrorsArray();
679
680 return $form->msg( ...$errors[0] );
681 } else {
682 return true;
683 }
684 }
685
686 /**
687 * Validate a block target.
688 *
689 * @since 1.21
690 * @param string $value Block target to check
691 * @param User $user Performer of the block
692 * @return Status
693 */
694 public static function validateTarget( $value, User $user ) {
695 global $wgBlockCIDRLimit;
696
697 /** @var User $target */
698 list( $target, $type ) = self::getTargetAndType( $value );
699 $status = Status::newGood( $target );
700
701 if ( $type == Block::TYPE_USER ) {
702 if ( $target->isAnon() ) {
703 $status->fatal(
704 'nosuchusershort',
705 wfEscapeWikiText( $target->getName() )
706 );
707 }
708
709 $unblockStatus = self::checkUnblockSelf( $target, $user );
710 if ( $unblockStatus !== true ) {
711 $status->fatal( 'badaccess', $unblockStatus );
712 }
713 } elseif ( $type == Block::TYPE_RANGE ) {
714 list( $ip, $range ) = explode( '/', $target, 2 );
715
716 if (
717 ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
718 ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
719 ) {
720 // Range block effectively disabled
721 $status->fatal( 'range_block_disabled' );
722 }
723
724 if (
725 ( IP::isIPv4( $ip ) && $range > 32 ) ||
726 ( IP::isIPv6( $ip ) && $range > 128 )
727 ) {
728 // Dodgy range
729 $status->fatal( 'ip_range_invalid' );
730 }
731
732 if ( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
733 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
734 }
735
736 if ( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
737 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
738 }
739 } elseif ( $type == Block::TYPE_IP ) {
740 # All is well
741 } else {
742 $status->fatal( 'badipaddress' );
743 }
744
745 return $status;
746 }
747
748 /**
749 * Given the form data, actually implement a block. This is also called from ApiBlock.
750 *
751 * @param array $data
752 * @param IContextSource $context
753 * @return bool|string
754 */
755 public static function processForm( array $data, IContextSource $context ) {
756 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit;
757
758 $performer = $context->getUser();
759 $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
760 $isPartialBlock = $enablePartialBlocks &&
761 isset( $data['EditingRestriction'] ) &&
762 $data['EditingRestriction'] === 'partial';
763
764 // Handled by field validator callback
765 // self::validateTargetField( $data['Target'] );
766
767 # This might have been a hidden field or a checkbox, so interesting data
768 # can come from it
769 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
770
771 /** @var User $target */
772 list( $target, $type ) = self::getTargetAndType( $data['Target'] );
773 if ( $type == Block::TYPE_USER ) {
774 $user = $target;
775 $target = $user->getName();
776 $userId = $user->getId();
777
778 # Give admins a heads-up before they go and block themselves. Much messier
779 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
780 # permission anyway, although the code does allow for it.
781 # Note: Important to use $target instead of $data['Target']
782 # since both $data['PreviousTarget'] and $target are normalized
783 # but $data['target'] gets overridden by (non-normalized) request variable
784 # from previous request.
785 if ( $target === $performer->getName() &&
786 ( $data['PreviousTarget'] !== $target || !$data['Confirm'] )
787 ) {
788 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
789 }
790 } elseif ( $type == Block::TYPE_RANGE ) {
791 $user = null;
792 $userId = 0;
793 } elseif ( $type == Block::TYPE_IP ) {
794 $user = null;
795 $target = $target->getName();
796 $userId = 0;
797 } else {
798 # This should have been caught in the form field validation
799 return [ 'badipaddress' ];
800 }
801
802 $expiryTime = self::parseExpiryInput( $data['Expiry'] );
803
804 if (
805 // an expiry time is needed
806 ( strlen( $data['Expiry'] ) == 0 ) ||
807 // can't be a larger string as 50 (it should be a time format in any way)
808 ( strlen( $data['Expiry'] ) > 50 ) ||
809 // check, if the time could be parsed
810 !$expiryTime
811 ) {
812 return [ 'ipb_expiry_invalid' ];
813 }
814
815 // an expiry time should be in the future, not in the
816 // past (wouldn't make any sense) - bug T123069
817 if ( $expiryTime < wfTimestampNow() ) {
818 return [ 'ipb_expiry_old' ];
819 }
820
821 if ( !isset( $data['DisableEmail'] ) ) {
822 $data['DisableEmail'] = false;
823 }
824
825 # If the user has done the form 'properly', they won't even have been given the
826 # option to suppress-block unless they have the 'hideuser' permission
827 if ( !isset( $data['HideUser'] ) ) {
828 $data['HideUser'] = false;
829 }
830
831 if ( $data['HideUser'] ) {
832 if ( !$performer->isAllowed( 'hideuser' ) ) {
833 # this codepath is unreachable except by a malicious user spoofing forms,
834 # or by race conditions (user has hideuser and block rights, loads block form,
835 # and loses hideuser rights before submission); so need to fail completely
836 # rather than just silently disable hiding
837 return [ 'badaccess-group0' ];
838 }
839
840 if ( $isPartialBlock ) {
841 return [ 'ipb_hide_partial' ];
842 }
843
844 # Recheck params here...
845 if ( $type != Block::TYPE_USER ) {
846 $data['HideUser'] = false; # IP users should not be hidden
847 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
848 # Bad expiry.
849 return [ 'ipb_expiry_temp' ];
850 } elseif ( $wgHideUserContribLimit !== false
851 && $user->getEditCount() > $wgHideUserContribLimit
852 ) {
853 # Typically, the user should have a handful of edits.
854 # Disallow hiding users with many edits for performance.
855 return [ [ 'ipb_hide_invalid',
856 Message::numParam( $wgHideUserContribLimit ) ] ];
857 } elseif ( !$data['Confirm'] ) {
858 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
859 }
860 }
861
862 # Create block object.
863 $block = new Block();
864 $block->setTarget( $target );
865 $block->setBlocker( $performer );
866 $block->setReason( $data['Reason'][0] );
867 $block->setExpiry( $expiryTime );
868 $block->isCreateAccountBlocked( $data['CreateAccount'] );
869 $block->isUsertalkEditAllowed( !$wgBlockAllowsUTEdit || !$data['DisableUTEdit'] );
870 $block->isEmailBlocked( $data['DisableEmail'] );
871 $block->isHardblock( $data['HardBlock'] );
872 $block->isAutoblocking( $data['AutoBlock'] );
873 $block->setHideName( $data['HideUser'] );
874
875 if ( $isPartialBlock ) {
876 $block->isSitewide( false );
877 }
878
879 $reason = [ 'hookaborted' ];
880 if ( !Hooks::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
881 return $reason;
882 }
883
884 $pageRestrictions = [];
885 $namespaceRestrictions = [];
886 if ( $enablePartialBlocks ) {
887 if ( $data['PageRestrictions'] !== '' ) {
888 $pageRestrictions = array_map( function ( $text ) {
889 $title = Title::newFromText( $text );
890 // Use the link cache since the title has already been loaded when
891 // the field was validated.
892 $restriction = new PageRestriction( 0, $title->getArticleID() );
893 $restriction->setTitle( $title );
894 return $restriction;
895 }, explode( "\n", $data['PageRestrictions'] ) );
896 }
897 if ( $data['NamespaceRestrictions'] !== '' ) {
898 $namespaceRestrictions = array_map( function ( $id ) {
899 return new NamespaceRestriction( 0, $id );
900 }, explode( "\n", $data['NamespaceRestrictions'] ) );
901 }
902
903 $restrictions = ( array_merge( $pageRestrictions, $namespaceRestrictions ) );
904 $block->setRestrictions( $restrictions );
905 }
906
907 $priorBlock = null;
908 # Try to insert block. Is there a conflicting block?
909 $status = $block->insert();
910 if ( !$status ) {
911 # Indicates whether the user is confirming the block and is aware of
912 # the conflict (did not change the block target in the meantime)
913 $blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
914 && $data['PreviousTarget'] !== $target );
915
916 # Special case for API - T34434
917 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
918
919 # Show form unless the user is already aware of this...
920 if ( $blockNotConfirmed || $reblockNotAllowed ) {
921 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
922 # Otherwise, try to update the block...
923 } else {
924 # This returns direct blocks before autoblocks/rangeblocks, since we should
925 # be sure the user is blocked by now it should work for our purposes
926 $currentBlock = Block::newFromTarget( $target );
927 if ( $block->equals( $currentBlock ) ) {
928 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
929 }
930 # If the name was hidden and the blocking user cannot hide
931 # names, then don't allow any block changes...
932 if ( $currentBlock->getHideName() && !$performer->isAllowed( 'hideuser' ) ) {
933 return [ 'cant-see-hidden-user' ];
934 }
935
936 $priorBlock = clone $currentBlock;
937 $currentBlock->isHardblock( $block->isHardblock() );
938 $currentBlock->isCreateAccountBlocked( $block->isCreateAccountBlocked() );
939 $currentBlock->setExpiry( $block->getExpiry() );
940 $currentBlock->isAutoblocking( $block->isAutoblocking() );
941 $currentBlock->setHideName( $block->getHideName() );
942 $currentBlock->isEmailBlocked( $block->isEmailBlocked() );
943 $currentBlock->isUsertalkEditAllowed( $block->isUsertalkEditAllowed() );
944 $currentBlock->setReason( $block->getReason() );
945
946 if ( $enablePartialBlocks ) {
947 // Maintain the sitewide status. If partial blocks is not enabled,
948 // saving the block will result in a sitewide block.
949 $currentBlock->isSitewide( $block->isSitewide() );
950
951 // Set the block id of the restrictions.
952 $currentBlock->setRestrictions(
953 BlockRestriction::setBlockId( $currentBlock->getId(), $restrictions )
954 );
955 }
956
957 $status = $currentBlock->update();
958 // TODO handle failure
959
960 $logaction = 'reblock';
961
962 # Unset _deleted fields if requested
963 if ( $currentBlock->getHideName() && !$data['HideUser'] ) {
964 RevisionDeleteUser::unsuppressUserName( $target, $userId );
965 }
966
967 # If hiding/unhiding a name, this should go in the private logs
968 if ( (bool)$currentBlock->getHideName() ) {
969 $data['HideUser'] = true;
970 }
971
972 $block = $currentBlock;
973 }
974 } else {
975 $logaction = 'block';
976 }
977
978 Hooks::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
979
980 # Set *_deleted fields if requested
981 if ( $data['HideUser'] ) {
982 RevisionDeleteUser::suppressUserName( $target, $userId );
983 }
984
985 # Can't watch a rangeblock
986 if ( $type != Block::TYPE_RANGE && $data['Watch'] ) {
987 WatchAction::doWatch(
988 Title::makeTitle( NS_USER, $target ),
989 $performer,
990 User::IGNORE_USER_RIGHTS
991 );
992 }
993
994 # Block constructor sanitizes certain block options on insert
995 $data['BlockEmail'] = $block->isEmailBlocked();
996 $data['AutoBlock'] = $block->isAutoblocking();
997
998 # Prepare log parameters
999 $logParams = [];
1000 $logParams['5::duration'] = $data['Expiry'];
1001 $logParams['6::flags'] = self::blockLogFlags( $data, $type );
1002 $logParams['sitewide'] = $block->isSitewide();
1003
1004 if ( $enablePartialBlocks && !$block->isSitewide() ) {
1005 if ( $data['PageRestrictions'] !== '' ) {
1006 $logParams['7::restrictions']['pages'] = explode( "\n", $data['PageRestrictions'] );
1007 }
1008
1009 if ( $data['NamespaceRestrictions'] !== '' ) {
1010 $logParams['7::restrictions']['namespaces'] = explode( "\n", $data['NamespaceRestrictions'] );
1011 }
1012 }
1013
1014 # Make log entry, if the name is hidden, put it in the suppression log
1015 $log_type = $data['HideUser'] ? 'suppress' : 'block';
1016 $logEntry = new ManualLogEntry( $log_type, $logaction );
1017 $logEntry->setTarget( Title::makeTitle( NS_USER, $target ) );
1018 $logEntry->setComment( $data['Reason'][0] );
1019 $logEntry->setPerformer( $performer );
1020 $logEntry->setParameters( $logParams );
1021 # Relate log ID to block ID (T27763)
1022 $logEntry->setRelations( [ 'ipb_id' => $block->getId() ] );
1023 $logId = $logEntry->insert();
1024
1025 if ( !empty( $data['Tags'] ) ) {
1026 $logEntry->setTags( $data['Tags'] );
1027 }
1028
1029 $logEntry->publish( $logId );
1030
1031 return true;
1032 }
1033
1034 /**
1035 * Get an array of suggested block durations from MediaWiki:Ipboptions
1036 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
1037 * to the standard "**<duration>|<displayname>" format?
1038 * @param Language|null $lang The language to get the durations in, or null to use
1039 * the wiki's content language
1040 * @param bool $includeOther Whether to include the 'other' option in the list of
1041 * suggestions
1042 * @return array
1043 */
1044 public static function getSuggestedDurations( Language $lang = null, $includeOther = true ) {
1045 $a = [];
1046 $msg = $lang === null
1047 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
1048 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
1049
1050 if ( $msg == '-' ) {
1051 return [];
1052 }
1053
1054 foreach ( explode( ',', $msg ) as $option ) {
1055 if ( strpos( $option, ':' ) === false ) {
1056 $option = "$option:$option";
1057 }
1058
1059 list( $show, $value ) = explode( ':', $option );
1060 $a[$show] = $value;
1061 }
1062
1063 if ( $a && $includeOther ) {
1064 // if options exist, add other to the end instead of the begining (which
1065 // is what happens by default).
1066 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
1067 }
1068
1069 return $a;
1070 }
1071
1072 /**
1073 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1074 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
1075 *
1076 * @todo strtotime() only accepts English strings. This means the expiry input
1077 * can only be specified in English.
1078 * @see https://secure.php.net/manual/en/function.strtotime.php
1079 *
1080 * @param string $expiry Whatever was typed into the form
1081 * @return string|bool Timestamp or 'infinity' or false on error.
1082 */
1083 public static function parseExpiryInput( $expiry ) {
1084 if ( wfIsInfinity( $expiry ) ) {
1085 return 'infinity';
1086 }
1087
1088 $expiry = strtotime( $expiry );
1089
1090 if ( $expiry < 0 || $expiry === false ) {
1091 return false;
1092 }
1093
1094 return wfTimestamp( TS_MW, $expiry );
1095 }
1096
1097 /**
1098 * Can we do an email block?
1099 * @param User $user The sysop wanting to make a block
1100 * @return bool
1101 */
1102 public static function canBlockEmail( $user ) {
1103 global $wgEnableUserEmail, $wgSysopEmailBans;
1104
1105 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1106 }
1107
1108 /**
1109 * T17810: blocked admins should not be able to block/unblock
1110 * others, and probably shouldn't be able to unblock themselves
1111 * either.
1112 *
1113 * Exception: Users can block the user who blocked them, to reduce
1114 * advantage of a malicious account blocking all admins (T150826)
1115 *
1116 * @param User|int|string|null $target Target to block or unblock; could be a User object,
1117 * or a user ID or username, or null when the target is not known yet (e.g. when
1118 * displaying Special:Block)
1119 * @param User $performer User doing the request
1120 * @return bool|string True or error message key
1121 */
1122 public static function checkUnblockSelf( $target, User $performer ) {
1123 if ( is_int( $target ) ) {
1124 $target = User::newFromId( $target );
1125 } elseif ( is_string( $target ) ) {
1126 $target = User::newFromName( $target );
1127 }
1128 if ( $performer->isBlocked() ) {
1129 if ( $target instanceof User && $target->getId() == $performer->getId() ) {
1130 # User is trying to unblock themselves
1131 if ( $performer->isAllowed( 'unblockself' ) ) {
1132 return true;
1133 # User blocked themselves and is now trying to reverse it
1134 } elseif ( $performer->blockedBy() === $performer->getName() ) {
1135 return true;
1136 } else {
1137 return 'ipbnounblockself';
1138 }
1139 } elseif (
1140 $target instanceof User &&
1141 $performer->getBlock() instanceof Block &&
1142 $performer->getBlock()->getBy() &&
1143 $performer->getBlock()->getBy() === $target->getId()
1144 ) {
1145 // Allow users to block the user that blocked them.
1146 // This is to prevent a situation where a malicious user
1147 // blocks all other users. This way, the non-malicious
1148 // user can block the malicious user back, resulting
1149 // in a stalemate.
1150 return true;
1151
1152 } else {
1153 # User is trying to block/unblock someone else
1154 return 'ipbblocked';
1155 }
1156 } else {
1157 return true;
1158 }
1159 }
1160
1161 /**
1162 * Return a comma-delimited list of "flags" to be passed to the log
1163 * reader for this block, to provide more information in the logs
1164 * @param array $data From HTMLForm data
1165 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
1166 * @return string
1167 */
1168 protected static function blockLogFlags( array $data, $type ) {
1169 $config = RequestContext::getMain()->getConfig();
1170
1171 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1172
1173 $flags = [];
1174
1175 # when blocking a user the option 'anononly' is not available/has no effect
1176 # -> do not write this into log
1177 if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
1178 // For grepping: message block-log-flags-anononly
1179 $flags[] = 'anononly';
1180 }
1181
1182 if ( $data['CreateAccount'] ) {
1183 // For grepping: message block-log-flags-nocreate
1184 $flags[] = 'nocreate';
1185 }
1186
1187 # Same as anononly, this is not displayed when blocking an IP address
1188 if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
1189 // For grepping: message block-log-flags-noautoblock
1190 $flags[] = 'noautoblock';
1191 }
1192
1193 if ( $data['DisableEmail'] ) {
1194 // For grepping: message block-log-flags-noemail
1195 $flags[] = 'noemail';
1196 }
1197
1198 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1199 // For grepping: message block-log-flags-nousertalk
1200 $flags[] = 'nousertalk';
1201 }
1202
1203 if ( $data['HideUser'] ) {
1204 // For grepping: message block-log-flags-hiddenname
1205 $flags[] = 'hiddenname';
1206 }
1207
1208 return implode( ',', $flags );
1209 }
1210
1211 /**
1212 * Process the form on POST submission.
1213 * @param array $data
1214 * @param HTMLForm|null $form
1215 * @return bool|array True for success, false for didn't-try, array of errors on failure
1216 */
1217 public function onSubmit( array $data, HTMLForm $form = null ) {
1218 // If "Editing" checkbox is unchecked, the block must be a partial block affecting
1219 // actions other than editing, and there must be no restrictions.
1220 if ( isset( $data['Editing'] ) && $data['Editing'] === false ) {
1221 $data['EditingRestriction'] = 'partial';
1222 $data['PageRestrictions'] = '';
1223 $data['NamespaceRestrictions'] = '';
1224 }
1225 return self::processForm( $data, $form->getContext() );
1226 }
1227
1228 /**
1229 * Do something exciting on successful processing of the form, most likely to show a
1230 * confirmation message
1231 */
1232 public function onSuccess() {
1233 $out = $this->getOutput();
1234 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1235 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
1236 }
1237
1238 /**
1239 * Return an array of subpages beginning with $search that this special page will accept.
1240 *
1241 * @param string $search Prefix to search for
1242 * @param int $limit Maximum number of results to return (usually 10)
1243 * @param int $offset Number of results to skip (usually 0)
1244 * @return string[] Matching subpages
1245 */
1246 public function prefixSearchSubpages( $search, $limit, $offset ) {
1247 $user = User::newFromName( $search );
1248 if ( !$user ) {
1249 // No prefix suggestion for invalid user
1250 return [];
1251 }
1252 // Autocomplete subpage as user list - public to allow caching
1253 return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
1254 }
1255
1256 protected function getGroupName() {
1257 return 'users';
1258 }
1259 }