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