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