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