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