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