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