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