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