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