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