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 */
623 public static function getTargetAndType( $par, WebRequest $request = null ) {
624 $i = 0;
625 $target = null;
626
627 while ( true ) {
628 switch ( $i++ ) {
629 case 0:
630 # The HTMLForm will check wpTarget first and only if it doesn't get
631 # a value use the default, which will be generated from the options
632 # below; so this has to have a higher precedence here than $par, or
633 # we could end up with different values in $this->target and the HTMLForm!
634 if ( $request instanceof WebRequest ) {
635 $target = $request->getText( 'wpTarget', null );
636 }
637 break;
638 case 1:
639 $target = $par;
640 break;
641 case 2:
642 if ( $request instanceof WebRequest ) {
643 $target = $request->getText( 'ip', null );
644 }
645 break;
646 case 3:
647 # B/C @since 1.18
648 if ( $request instanceof WebRequest ) {
649 $target = $request->getText( 'wpBlockAddress', null );
650 }
651 break;
652 case 4:
653 break 2;
654 }
655
656 list( $target, $type ) = Block::parseTarget( $target );
657
658 if ( $type !== null ) {
659 return [ $target, $type ];
660 }
661 }
662
663 return [ null, null ];
664 }
665
666 /**
667 * HTMLForm field validation-callback for Target field.
668 * @since 1.18
669 * @param string $value
670 * @param array $alldata
671 * @param HTMLForm $form
672 * @return Message
673 */
674 public static function validateTargetField( $value, $alldata, $form ) {
675 $status = self::validateTarget( $value, $form->getUser() );
676 if ( !$status->isOK() ) {
677 $errors = $status->getErrorsArray();
678
679 return $form->msg( ...$errors[0] );
680 } else {
681 return true;
682 }
683 }
684
685 /**
686 * Validate a block target.
687 *
688 * @since 1.21
689 * @param string $value Block target to check
690 * @param User $user Performer of the block
691 * @return Status
692 */
693 public static function validateTarget( $value, User $user ) {
694 global $wgBlockCIDRLimit;
695
696 /** @var User $target */
697 list( $target, $type ) = self::getTargetAndType( $value );
698 $status = Status::newGood( $target );
699
700 if ( $type == Block::TYPE_USER ) {
701 if ( $target->isAnon() ) {
702 $status->fatal(
703 'nosuchusershort',
704 wfEscapeWikiText( $target->getName() )
705 );
706 }
707
708 $unblockStatus = self::checkUnblockSelf( $target, $user );
709 if ( $unblockStatus !== true ) {
710 $status->fatal( 'badaccess', $unblockStatus );
711 }
712 } elseif ( $type == Block::TYPE_RANGE ) {
713 list( $ip, $range ) = explode( '/', $target, 2 );
714
715 if (
716 ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
717 ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
718 ) {
719 // Range block effectively disabled
720 $status->fatal( 'range_block_disabled' );
721 }
722
723 if (
724 ( IP::isIPv4( $ip ) && $range > 32 ) ||
725 ( IP::isIPv6( $ip ) && $range > 128 )
726 ) {
727 // Dodgy range
728 $status->fatal( 'ip_range_invalid' );
729 }
730
731 if ( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
732 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
733 }
734
735 if ( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
736 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
737 }
738 } elseif ( $type == Block::TYPE_IP ) {
739 # All is well
740 } else {
741 $status->fatal( 'badipaddress' );
742 }
743
744 return $status;
745 }
746
747 /**
748 * Given the form data, actually implement a block. This is also called from ApiBlock.
749 *
750 * @param array $data
751 * @param IContextSource $context
752 * @return bool|string
753 */
754 public static function processForm( array $data, IContextSource $context ) {
755 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit;
756
757 $performer = $context->getUser();
758 $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
759 $isPartialBlock = $enablePartialBlocks &&
760 isset( $data['EditingRestriction'] ) &&
761 $data['EditingRestriction'] === 'partial';
762
763 // Handled by field validator callback
764 // self::validateTargetField( $data['Target'] );
765
766 # This might have been a hidden field or a checkbox, so interesting data
767 # can come from it
768 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
769
770 /** @var User $target */
771 list( $target, $type ) = self::getTargetAndType( $data['Target'] );
772 if ( $type == Block::TYPE_USER ) {
773 $user = $target;
774 $target = $user->getName();
775 $userId = $user->getId();
776
777 # Give admins a heads-up before they go and block themselves. Much messier
778 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
779 # permission anyway, although the code does allow for it.
780 # Note: Important to use $target instead of $data['Target']
781 # since both $data['PreviousTarget'] and $target are normalized
782 # but $data['target'] gets overridden by (non-normalized) request variable
783 # from previous request.
784 if ( $target === $performer->getName() &&
785 ( $data['PreviousTarget'] !== $target || !$data['Confirm'] )
786 ) {
787 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
788 }
789 } elseif ( $type == Block::TYPE_RANGE ) {
790 $user = null;
791 $userId = 0;
792 } elseif ( $type == Block::TYPE_IP ) {
793 $user = null;
794 $target = $target->getName();
795 $userId = 0;
796 } else {
797 # This should have been caught in the form field validation
798 return [ 'badipaddress' ];
799 }
800
801 $expiryTime = self::parseExpiryInput( $data['Expiry'] );
802
803 if (
804 // an expiry time is needed
805 ( strlen( $data['Expiry'] ) == 0 ) ||
806 // can't be a larger string as 50 (it should be a time format in any way)
807 ( strlen( $data['Expiry'] ) > 50 ) ||
808 // check, if the time could be parsed
809 !$expiryTime
810 ) {
811 return [ 'ipb_expiry_invalid' ];
812 }
813
814 // an expiry time should be in the future, not in the
815 // past (wouldn't make any sense) - bug T123069
816 if ( $expiryTime < wfTimestampNow() ) {
817 return [ 'ipb_expiry_old' ];
818 }
819
820 if ( !isset( $data['DisableEmail'] ) ) {
821 $data['DisableEmail'] = false;
822 }
823
824 # If the user has done the form 'properly', they won't even have been given the
825 # option to suppress-block unless they have the 'hideuser' permission
826 if ( !isset( $data['HideUser'] ) ) {
827 $data['HideUser'] = false;
828 }
829
830 if ( $data['HideUser'] ) {
831 if ( !$performer->isAllowed( 'hideuser' ) ) {
832 # this codepath is unreachable except by a malicious user spoofing forms,
833 # or by race conditions (user has hideuser and block rights, loads block form,
834 # and loses hideuser rights before submission); so need to fail completely
835 # rather than just silently disable hiding
836 return [ 'badaccess-group0' ];
837 }
838
839 if ( $isPartialBlock ) {
840 return [ 'ipb_hide_partial' ];
841 }
842
843 # Recheck params here...
844 if ( $type != Block::TYPE_USER ) {
845 $data['HideUser'] = false; # IP users should not be hidden
846 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
847 # Bad expiry.
848 return [ 'ipb_expiry_temp' ];
849 } elseif ( $wgHideUserContribLimit !== false
850 && $user->getEditCount() > $wgHideUserContribLimit
851 ) {
852 # Typically, the user should have a handful of edits.
853 # Disallow hiding users with many edits for performance.
854 return [ [ 'ipb_hide_invalid',
855 Message::numParam( $wgHideUserContribLimit ) ] ];
856 } elseif ( !$data['Confirm'] ) {
857 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
858 }
859 }
860
861 # Create block object.
862 $block = new Block();
863 $block->setTarget( $target );
864 $block->setBlocker( $performer );
865 $block->setReason( $data['Reason'][0] );
866 $block->setExpiry( $expiryTime );
867 $block->isCreateAccountBlocked( $data['CreateAccount'] );
868 $block->isUsertalkEditAllowed( !$wgBlockAllowsUTEdit || !$data['DisableUTEdit'] );
869 $block->isEmailBlocked( $data['DisableEmail'] );
870 $block->isHardblock( $data['HardBlock'] );
871 $block->isAutoblocking( $data['AutoBlock'] );
872 $block->setHideName( $data['HideUser'] );
873
874 if ( $isPartialBlock ) {
875 $block->isSitewide( false );
876 }
877
878 $reason = [ 'hookaborted' ];
879 if ( !Hooks::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
880 return $reason;
881 }
882
883 $pageRestrictions = [];
884 $namespaceRestrictions = [];
885 if ( $enablePartialBlocks ) {
886 if ( $data['PageRestrictions'] !== '' ) {
887 $pageRestrictions = array_map( function ( $text ) {
888 $title = Title::newFromText( $text );
889 // Use the link cache since the title has already been loaded when
890 // the field was validated.
891 $restriction = new PageRestriction( 0, $title->getArticleID() );
892 $restriction->setTitle( $title );
893 return $restriction;
894 }, explode( "\n", $data['PageRestrictions'] ) );
895 }
896 if ( $data['NamespaceRestrictions'] !== '' ) {
897 $namespaceRestrictions = array_map( function ( $id ) {
898 return new NamespaceRestriction( 0, $id );
899 }, explode( "\n", $data['NamespaceRestrictions'] ) );
900 }
901
902 $restrictions = ( array_merge( $pageRestrictions, $namespaceRestrictions ) );
903 $block->setRestrictions( $restrictions );
904 }
905
906 $priorBlock = null;
907 # Try to insert block. Is there a conflicting block?
908 $status = $block->insert();
909 if ( !$status ) {
910 # Indicates whether the user is confirming the block and is aware of
911 # the conflict (did not change the block target in the meantime)
912 $blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
913 && $data['PreviousTarget'] !== $target );
914
915 # Special case for API - T34434
916 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
917
918 # Show form unless the user is already aware of this...
919 if ( $blockNotConfirmed || $reblockNotAllowed ) {
920 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
921 # Otherwise, try to update the block...
922 } else {
923 # This returns direct blocks before autoblocks/rangeblocks, since we should
924 # be sure the user is blocked by now it should work for our purposes
925 $currentBlock = Block::newFromTarget( $target );
926 if ( $block->equals( $currentBlock ) ) {
927 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
928 }
929 # If the name was hidden and the blocking user cannot hide
930 # names, then don't allow any block changes...
931 if ( $currentBlock->getHideName() && !$performer->isAllowed( 'hideuser' ) ) {
932 return [ 'cant-see-hidden-user' ];
933 }
934
935 $priorBlock = clone $currentBlock;
936 $currentBlock->isHardblock( $block->isHardblock() );
937 $currentBlock->isCreateAccountBlocked( $block->isCreateAccountBlocked() );
938 $currentBlock->setExpiry( $block->getExpiry() );
939 $currentBlock->isAutoblocking( $block->isAutoblocking() );
940 $currentBlock->setHideName( $block->getHideName() );
941 $currentBlock->isEmailBlocked( $block->isEmailBlocked() );
942 $currentBlock->isUsertalkEditAllowed( $block->isUsertalkEditAllowed() );
943 $currentBlock->setReason( $block->getReason() );
944
945 if ( $enablePartialBlocks ) {
946 // Maintain the sitewide status. If partial blocks is not enabled,
947 // saving the block will result in a sitewide block.
948 $currentBlock->isSitewide( $block->isSitewide() );
949
950 // Set the block id of the restrictions.
951 $currentBlock->setRestrictions(
952 BlockRestriction::setBlockId( $currentBlock->getId(), $restrictions )
953 );
954 }
955
956 $status = $currentBlock->update();
957 // TODO handle failure
958
959 $logaction = 'reblock';
960
961 # Unset _deleted fields if requested
962 if ( $currentBlock->getHideName() && !$data['HideUser'] ) {
963 RevisionDeleteUser::unsuppressUserName( $target, $userId );
964 }
965
966 # If hiding/unhiding a name, this should go in the private logs
967 if ( (bool)$currentBlock->getHideName() ) {
968 $data['HideUser'] = true;
969 }
970
971 $block = $currentBlock;
972 }
973 } else {
974 $logaction = 'block';
975 }
976
977 Hooks::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
978
979 # Set *_deleted fields if requested
980 if ( $data['HideUser'] ) {
981 RevisionDeleteUser::suppressUserName( $target, $userId );
982 }
983
984 # Can't watch a rangeblock
985 if ( $type != Block::TYPE_RANGE && $data['Watch'] ) {
986 WatchAction::doWatch(
987 Title::makeTitle( NS_USER, $target ),
988 $performer,
989 User::IGNORE_USER_RIGHTS
990 );
991 }
992
993 # Block constructor sanitizes certain block options on insert
994 $data['BlockEmail'] = $block->isEmailBlocked();
995 $data['AutoBlock'] = $block->isAutoblocking();
996
997 # Prepare log parameters
998 $logParams = [];
999 $logParams['5::duration'] = $data['Expiry'];
1000 $logParams['6::flags'] = self::blockLogFlags( $data, $type );
1001 $logParams['sitewide'] = $block->isSitewide();
1002
1003 if ( $enablePartialBlocks && !$block->isSitewide() ) {
1004 if ( $data['PageRestrictions'] !== '' ) {
1005 $logParams['7::restrictions']['pages'] = explode( "\n", $data['PageRestrictions'] );
1006 }
1007
1008 if ( $data['NamespaceRestrictions'] !== '' ) {
1009 $logParams['7::restrictions']['namespaces'] = explode( "\n", $data['NamespaceRestrictions'] );
1010 }
1011 }
1012
1013 # Make log entry, if the name is hidden, put it in the suppression log
1014 $log_type = $data['HideUser'] ? 'suppress' : 'block';
1015 $logEntry = new ManualLogEntry( $log_type, $logaction );
1016 $logEntry->setTarget( Title::makeTitle( NS_USER, $target ) );
1017 $logEntry->setComment( $data['Reason'][0] );
1018 $logEntry->setPerformer( $performer );
1019 $logEntry->setParameters( $logParams );
1020 # Relate log ID to block ID (T27763)
1021 $logEntry->setRelations( [ 'ipb_id' => $block->getId() ] );
1022 $logId = $logEntry->insert();
1023
1024 if ( !empty( $data['Tags'] ) ) {
1025 $logEntry->setTags( $data['Tags'] );
1026 }
1027
1028 $logEntry->publish( $logId );
1029
1030 return true;
1031 }
1032
1033 /**
1034 * Get an array of suggested block durations from MediaWiki:Ipboptions
1035 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
1036 * to the standard "**<duration>|<displayname>" format?
1037 * @param Language|null $lang The language to get the durations in, or null to use
1038 * the wiki's content language
1039 * @param bool $includeOther Whether to include the 'other' option in the list of
1040 * suggestions
1041 * @return array
1042 */
1043 public static function getSuggestedDurations( Language $lang = null, $includeOther = true ) {
1044 $a = [];
1045 $msg = $lang === null
1046 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
1047 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
1048
1049 if ( $msg == '-' ) {
1050 return [];
1051 }
1052
1053 foreach ( explode( ',', $msg ) as $option ) {
1054 if ( strpos( $option, ':' ) === false ) {
1055 $option = "$option:$option";
1056 }
1057
1058 list( $show, $value ) = explode( ':', $option );
1059 $a[$show] = $value;
1060 }
1061
1062 if ( $a && $includeOther ) {
1063 // if options exist, add other to the end instead of the begining (which
1064 // is what happens by default).
1065 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
1066 }
1067
1068 return $a;
1069 }
1070
1071 /**
1072 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1073 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
1074 *
1075 * @todo strtotime() only accepts English strings. This means the expiry input
1076 * can only be specified in English.
1077 * @see https://secure.php.net/manual/en/function.strtotime.php
1078 *
1079 * @param string $expiry Whatever was typed into the form
1080 * @return string|bool Timestamp or 'infinity' or false on error.
1081 */
1082 public static function parseExpiryInput( $expiry ) {
1083 if ( wfIsInfinity( $expiry ) ) {
1084 return 'infinity';
1085 }
1086
1087 $expiry = strtotime( $expiry );
1088
1089 if ( $expiry < 0 || $expiry === false ) {
1090 return false;
1091 }
1092
1093 return wfTimestamp( TS_MW, $expiry );
1094 }
1095
1096 /**
1097 * Can we do an email block?
1098 * @param User $user The sysop wanting to make a block
1099 * @return bool
1100 */
1101 public static function canBlockEmail( $user ) {
1102 global $wgEnableUserEmail, $wgSysopEmailBans;
1103
1104 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1105 }
1106
1107 /**
1108 * T17810: blocked admins should not be able to block/unblock
1109 * others, and probably shouldn't be able to unblock themselves
1110 * either.
1111 *
1112 * Exception: Users can block the user who blocked them, to reduce
1113 * advantage of a malicious account blocking all admins (T150826)
1114 *
1115 * @param User|int|string|null $target Target to block or unblock; could be a User object,
1116 * or a user ID or username, or null when the target is not known yet (e.g. when
1117 * displaying Special:Block)
1118 * @param User $performer User doing the request
1119 * @return bool|string True or error message key
1120 */
1121 public static function checkUnblockSelf( $target, User $performer ) {
1122 if ( is_int( $target ) ) {
1123 $target = User::newFromId( $target );
1124 } elseif ( is_string( $target ) ) {
1125 $target = User::newFromName( $target );
1126 }
1127 if ( $performer->isBlocked() ) {
1128 if ( $target instanceof User && $target->getId() == $performer->getId() ) {
1129 # User is trying to unblock themselves
1130 if ( $performer->isAllowed( 'unblockself' ) ) {
1131 return true;
1132 # User blocked themselves and is now trying to reverse it
1133 } elseif ( $performer->blockedBy() === $performer->getName() ) {
1134 return true;
1135 } else {
1136 return 'ipbnounblockself';
1137 }
1138 } elseif (
1139 $target instanceof User &&
1140 $performer->getBlock() instanceof Block &&
1141 $performer->getBlock()->getBy() &&
1142 $performer->getBlock()->getBy() === $target->getId()
1143 ) {
1144 // Allow users to block the user that blocked them.
1145 // This is to prevent a situation where a malicious user
1146 // blocks all other users. This way, the non-malicious
1147 // user can block the malicious user back, resulting
1148 // in a stalemate.
1149 return true;
1150
1151 } else {
1152 # User is trying to block/unblock someone else
1153 return 'ipbblocked';
1154 }
1155 } else {
1156 return true;
1157 }
1158 }
1159
1160 /**
1161 * Return a comma-delimited list of "flags" to be passed to the log
1162 * reader for this block, to provide more information in the logs
1163 * @param array $data From HTMLForm data
1164 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
1165 * @return string
1166 */
1167 protected static function blockLogFlags( array $data, $type ) {
1168 $config = RequestContext::getMain()->getConfig();
1169
1170 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1171
1172 $flags = [];
1173
1174 # when blocking a user the option 'anononly' is not available/has no effect
1175 # -> do not write this into log
1176 if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
1177 // For grepping: message block-log-flags-anononly
1178 $flags[] = 'anononly';
1179 }
1180
1181 if ( $data['CreateAccount'] ) {
1182 // For grepping: message block-log-flags-nocreate
1183 $flags[] = 'nocreate';
1184 }
1185
1186 # Same as anononly, this is not displayed when blocking an IP address
1187 if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
1188 // For grepping: message block-log-flags-noautoblock
1189 $flags[] = 'noautoblock';
1190 }
1191
1192 if ( $data['DisableEmail'] ) {
1193 // For grepping: message block-log-flags-noemail
1194 $flags[] = 'noemail';
1195 }
1196
1197 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1198 // For grepping: message block-log-flags-nousertalk
1199 $flags[] = 'nousertalk';
1200 }
1201
1202 if ( $data['HideUser'] ) {
1203 // For grepping: message block-log-flags-hiddenname
1204 $flags[] = 'hiddenname';
1205 }
1206
1207 return implode( ',', $flags );
1208 }
1209
1210 /**
1211 * Process the form on POST submission.
1212 * @param array $data
1213 * @param HTMLForm|null $form
1214 * @return bool|array True for success, false for didn't-try, array of errors on failure
1215 */
1216 public function onSubmit( array $data, HTMLForm $form = null ) {
1217 // If "Editing" checkbox is unchecked, the block must be a partial block affecting
1218 // actions other than editing, and there must be no restrictions.
1219 if ( isset( $data['Editing'] ) && $data['Editing'] === false ) {
1220 $data['EditingRestriction'] = 'partial';
1221 $data['PageRestrictions'] = '';
1222 $data['NamespaceRestrictions'] = '';
1223 }
1224 return self::processForm( $data, $form->getContext() );
1225 }
1226
1227 /**
1228 * Do something exciting on successful processing of the form, most likely to show a
1229 * confirmation message
1230 */
1231 public function onSuccess() {
1232 $out = $this->getOutput();
1233 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1234 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
1235 }
1236
1237 /**
1238 * Return an array of subpages beginning with $search that this special page will accept.
1239 *
1240 * @param string $search Prefix to search for
1241 * @param int $limit Maximum number of results to return (usually 10)
1242 * @param int $offset Number of results to skip (usually 0)
1243 * @return string[] Matching subpages
1244 */
1245 public function prefixSearchSubpages( $search, $limit, $offset ) {
1246 $user = User::newFromName( $search );
1247 if ( !$user ) {
1248 // No prefix suggestion for invalid user
1249 return [];
1250 }
1251 // Autocomplete subpage as user list - public to allow caching
1252 return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
1253 }
1254
1255 protected function getGroupName() {
1256 return 'users';
1257 }
1258 }