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