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