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