MediaWiki fundraising/REL1_35
SpecialBlock.php
Go to the documentation of this file.
1<?php
31use Wikimedia\IPUtils;
32
44
48 protected $target;
49
51 protected $type;
52
54 protected $previousTarget;
55
58
60 protected $alreadyBlocked;
61
63 protected $preErrors = [];
64
65 public function __construct( PermissionManager $permissionManager ) {
66 parent::__construct( 'Block', 'block' );
67
68 $this->permissionManager = $permissionManager;
69 }
70
71 public function doesWrites() {
72 return true;
73 }
74
81 protected function checkExecutePermissions( User $user ) {
82 parent::checkExecutePermissions( $user );
83 # T17810: blocked admins should have limited access here
84 $status = self::checkUnblockSelf( $this->target, $user );
85 if ( $status !== true ) {
86 throw new ErrorPageError( 'badaccess', $status );
87 }
88 }
89
95 public function requiresUnblock() {
96 return false;
97 }
98
104 protected function setParameter( $par ) {
105 # Extract variables from the request. Try not to get into a situation where we
106 # need to extract *every* variable from the form just for processing here, but
107 # there are legitimate uses for some variables
108 $request = $this->getRequest();
109 list( $this->target, $this->type ) = self::getTargetAndType( $par, $request );
110 if ( $this->target instanceof User ) {
111 # Set the 'relevant user' in the skin, so it displays links like Contributions,
112 # User logs, UserRights, etc.
113 $this->getSkin()->setRelevantUser( $this->target );
114 }
115
116 list( $this->previousTarget, /*...*/ ) =
117 DatabaseBlock::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
118 $this->requestedHideUser = $request->getBool( 'wpHideUser' );
119 }
120
126 protected function alterForm( HTMLForm $form ) {
127 $form->setHeaderText( '' );
128 $form->setSubmitDestructive();
129
130 $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
131 $form->setSubmitTextMsg( $msg );
132
133 $this->addHelpLink( 'Help:Blocking users' );
134
135 # Don't need to do anything if the form has been posted
136 if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
137 $s = $form->formatErrors( $this->preErrors );
138 if ( $s ) {
139 $form->addHeaderText( Html::rawElement(
140 'div',
141 [ 'class' => 'error' ],
142 $s
143 ) );
144 }
145 }
146 }
147
148 protected function getDisplayFormat() {
149 return 'ooui';
150 }
151
156 protected function getFormFields() {
157 $conf = $this->getConfig();
158 $blockAllowsUTEdit = $conf->get( 'BlockAllowsUTEdit' );
159
160 $this->getOutput()->enableOOUI();
161
162 $user = $this->getUser();
163
164 $suggestedDurations = self::getSuggestedDurations();
165
166 $a = [];
167
168 $a['Target'] = [
169 'type' => 'user',
170 'ipallowed' => true,
171 'iprange' => true,
172 'id' => 'mw-bi-target',
173 'size' => '45',
174 'autofocus' => true,
175 'required' => true,
176 'validation-callback' => [ __CLASS__, 'validateTargetField' ],
177 'section' => 'target',
178 ];
179
180 $a['Editing'] = [
181 'type' => 'check',
182 'label-message' => 'block-prevent-edit',
183 'default' => true,
184 'section' => 'actions',
185 ];
186
187 $a['EditingRestriction'] = [
188 'type' => 'radio',
189 'cssclass' => 'mw-block-editing-restriction',
190 'default' => 'sitewide',
191 'options' => [
192 $this->msg( 'ipb-sitewide' )->escaped() .
193 new \OOUI\LabelWidget( [
194 'classes' => [ 'oo-ui-inline-help' ],
195 'label' => $this->msg( 'ipb-sitewide-help' )->text(),
196 ] ) => 'sitewide',
197 $this->msg( 'ipb-partial' )->escaped() .
198 new \OOUI\LabelWidget( [
199 'classes' => [ 'oo-ui-inline-help' ],
200 'label' => $this->msg( 'ipb-partial-help' )->text(),
201 ] ) => 'partial',
202 ],
203 'section' => 'actions',
204 ];
205
206 $a['PageRestrictions'] = [
207 'type' => 'titlesmultiselect',
208 'label' => $this->msg( 'ipb-pages-label' )->text(),
209 'exists' => true,
210 'max' => 10,
211 'cssclass' => 'mw-block-restriction',
212 'default' => '',
213 'showMissing' => false,
214 'excludeDynamicNamespaces' => true,
215 'input' => [
216 'autocomplete' => false
217 ],
218 'section' => 'actions',
219 ];
220
221 $a['NamespaceRestrictions'] = [
222 'type' => 'namespacesmultiselect',
223 'label' => $this->msg( 'ipb-namespaces-label' )->text(),
224 'exists' => true,
225 'cssclass' => 'mw-block-restriction',
226 'default' => '',
227 'input' => [
228 'autocomplete' => false
229 ],
230 'section' => 'actions',
231 ];
232
233 $a['CreateAccount'] = [
234 'type' => 'check',
235 'label-message' => 'ipbcreateaccount',
236 'default' => true,
237 'section' => 'actions',
238 ];
239
240 if ( self::canBlockEmail( $user ) ) {
241 $a['DisableEmail'] = [
242 'type' => 'check',
243 'label-message' => 'ipbemailban',
244 'section' => 'actions',
245 ];
246 }
247
248 if ( $blockAllowsUTEdit ) {
249 $a['DisableUTEdit'] = [
250 'type' => 'check',
251 'label-message' => 'ipb-disableusertalk',
252 'default' => false,
253 'section' => 'actions',
254 ];
255 }
256
257 $defaultExpiry = $this->msg( 'ipb-default-expiry' )->inContentLanguage();
258 if ( $this->type === DatabaseBlock::TYPE_RANGE || $this->type === DatabaseBlock::TYPE_IP ) {
259 $defaultExpiryIP = $this->msg( 'ipb-default-expiry-ip' )->inContentLanguage();
260 if ( !$defaultExpiryIP->isDisabled() ) {
261 $defaultExpiry = $defaultExpiryIP;
262 }
263 }
264
265 $a['Expiry'] = [
266 'type' => 'expiry',
267 'required' => true,
268 'options' => $suggestedDurations,
269 'default' => $defaultExpiry->text(),
270 'section' => 'expiry',
271 ];
272
273 $a['Reason'] = [
274 'type' => 'selectandother',
275 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
276 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
277 // Unicode codepoints.
278 'maxlength' => CommentStore::COMMENT_CHARACTER_LIMIT,
279 'maxlength-unit' => 'codepoints',
280 'options-message' => 'ipbreason-dropdown',
281 'section' => 'reason',
282 ];
283
284 $a['AutoBlock'] = [
285 'type' => 'check',
286 'label-message' => 'ipbenableautoblock',
287 'default' => true,
288 'section' => 'options',
289 ];
290
291 # Allow some users to hide name from block log, blocklist and listusers
292 if ( $this->permissionManager->userHasRight( $user, 'hideuser' ) ) {
293 $a['HideUser'] = [
294 'type' => 'check',
295 'label-message' => 'ipbhidename',
296 'cssclass' => 'mw-block-hideuser',
297 'section' => 'options',
298 ];
299 }
300
301 # Watchlist their user page? (Only if user is logged in)
302 if ( $user->isLoggedIn() ) {
303 $a['Watch'] = [
304 'type' => 'check',
305 'label-message' => 'ipbwatchuser',
306 'section' => 'options',
307 ];
308 }
309
310 $a['HardBlock'] = [
311 'type' => 'check',
312 'label-message' => 'ipb-hardblock',
313 'default' => false,
314 'section' => 'options',
315 ];
316
317 # This is basically a copy of the Target field, but the user can't change it, so we
318 # can see if the warnings we maybe showed to the user before still apply
319 $a['PreviousTarget'] = [
320 'type' => 'hidden',
321 'default' => false,
322 ];
323
324 # We'll turn this into a checkbox if we need to
325 $a['Confirm'] = [
326 'type' => 'hidden',
327 'default' => '',
328 'label-message' => 'ipb-confirm',
329 'cssclass' => 'mw-block-confirm',
330 ];
331
332 $this->maybeAlterFormDefaults( $a );
333
334 // Allow extensions to add more fields
335 $this->getHookRunner()->onSpecialBlockModifyFormFields( $this, $a );
336
337 return $a;
338 }
339
345 protected function maybeAlterFormDefaults( &$fields ) {
346 # This will be overwritten by request data
347 $fields['Target']['default'] = (string)$this->target;
348
349 if ( $this->target ) {
350 $status = self::validateTarget( $this->target, $this->getUser() );
351 if ( !$status->isOK() ) {
352 $errors = $status->getErrorsArray();
353 $this->preErrors = array_merge( $this->preErrors, $errors );
354 }
355 }
356
357 # This won't be
358 $fields['PreviousTarget']['default'] = (string)$this->target;
359
360 $block = DatabaseBlock::newFromTarget( $this->target );
361
362 // Populate fields if there is a block that is not an autoblock; if it is a range
363 // block, only populate the fields if the range is the same as $this->target
364 if ( $block instanceof DatabaseBlock && $block->getType() !== DatabaseBlock::TYPE_AUTO
365 && ( $this->type != DatabaseBlock::TYPE_RANGE
366 || $block->getTarget() == $this->target )
367 ) {
368 $fields['HardBlock']['default'] = $block->isHardblock();
369 $fields['CreateAccount']['default'] = $block->isCreateAccountBlocked();
370 $fields['AutoBlock']['default'] = $block->isAutoblocking();
371
372 if ( isset( $fields['DisableEmail'] ) ) {
373 $fields['DisableEmail']['default'] = $block->isEmailBlocked();
374 }
375
376 if ( isset( $fields['HideUser'] ) ) {
377 $fields['HideUser']['default'] = $block->getHideName();
378 }
379
380 if ( isset( $fields['DisableUTEdit'] ) ) {
381 $fields['DisableUTEdit']['default'] = !$block->isUsertalkEditAllowed();
382 }
383
384 // If the username was hidden (ipb_deleted == 1), don't show the reason
385 // unless this user also has rights to hideuser: T37839
386 if ( !$block->getHideName() || $this->permissionManager
387 ->userHasRight( $this->getUser(), 'hideuser' )
388 ) {
389 $fields['Reason']['default'] = $block->getReasonComment()->text;
390 } else {
391 $fields['Reason']['default'] = '';
392 }
393
394 if ( $this->getRequest()->wasPosted() ) {
395 # Ok, so we got a POST submission asking us to reblock a user. So show the
396 # confirm checkbox; the user will only see it if they haven't previously
397 $fields['Confirm']['type'] = 'check';
398 } else {
399 # We got a target, but it wasn't a POST request, so the user must have gone
400 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
401 # as long as they go ahead and block *that* user
402 $fields['Confirm']['default'] = 1;
403 }
404
405 if ( $block->getExpiry() == 'infinity' ) {
406 $fields['Expiry']['default'] = 'infinite';
407 } else {
408 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->getExpiry() );
409 }
410
411 if ( !$block->isSitewide() ) {
412 $fields['EditingRestriction']['default'] = 'partial';
413
414 $pageRestrictions = [];
415 $namespaceRestrictions = [];
416 foreach ( $block->getRestrictions() as $restriction ) {
417 if ( $restriction instanceof PageRestriction && $restriction->getTitle() ) {
418 $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
419 } elseif ( $restriction instanceof NamespaceRestriction ) {
420 $namespaceRestrictions[] = $restriction->getValue();
421 }
422 }
423
424 // Sort the restrictions so they are in alphabetical order.
425 sort( $pageRestrictions );
426 $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
427 sort( $namespaceRestrictions );
428 $fields['NamespaceRestrictions']['default'] = implode( "\n", $namespaceRestrictions );
429
430 if (
431 empty( $pageRestrictions ) &&
432 empty( $namespaceRestrictions )
433 ) {
434 $fields['Editing']['default'] = false;
435 }
436 }
437
438 $this->alreadyBlocked = true;
439 $this->preErrors[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
440 }
441
442 if ( $this->alreadyBlocked || $this->getRequest()->wasPosted()
443 || $this->getRequest()->getCheck( 'wpCreateAccount' )
444 ) {
445 $this->getOutput()->addJsConfigVars( 'wgCreateAccountDirty', true );
446 }
447
448 # We always need confirmation to do HideUser
449 if ( $this->requestedHideUser ) {
450 $fields['Confirm']['type'] = 'check';
451 unset( $fields['Confirm']['default'] );
452 $this->preErrors[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
453 }
454
455 # Or if the user is trying to block themselves
456 if ( (string)$this->target === $this->getUser()->getName() ) {
457 $fields['Confirm']['type'] = 'check';
458 unset( $fields['Confirm']['default'] );
459 $this->preErrors[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
460 }
461 }
462
467 protected function preText() {
468 $this->getOutput()->addModuleStyles( [
469 'mediawiki.widgets.TagMultiselectWidget.styles',
470 'mediawiki.special',
471 ] );
472 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
473
474 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
475 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
476
477 $otherBlockMessages = [];
478 if ( $this->target !== null ) {
479 $targetName = $this->target;
480 if ( $this->target instanceof User ) {
481 $targetName = $this->target->getName();
482 }
483 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
484 $this->getHookRunner()->onOtherBlockLogLink(
485 $otherBlockMessages, $targetName );
486
487 if ( count( $otherBlockMessages ) ) {
488 $s = Html::rawElement(
489 'h2',
490 [],
491 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
492 ) . "\n";
493
494 $list = '';
495
496 foreach ( $otherBlockMessages as $link ) {
497 $list .= Html::rawElement( 'li', [], $link ) . "\n";
498 }
499
500 $s .= Html::rawElement(
501 'ul',
502 [ 'class' => 'mw-blockip-alreadyblocked' ],
503 $list
504 ) . "\n";
505
506 $text .= $s;
507 }
508 }
509
510 return $text;
511 }
512
517 protected function postText() {
518 $links = [];
519
520 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
521
523 # Link to the user's contributions, if applicable
524 if ( $this->target instanceof User ) {
525 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
526 $links[] = $linkRenderer->makeLink(
527 $contribsPage,
528 $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->text()
529 );
530 }
531
532 # Link to unblock the specified user, or to a blank unblock form
533 if ( $this->target instanceof User ) {
534 $message = $this->msg(
535 'ipb-unblock-addr',
536 wfEscapeWikiText( $this->target->getName() )
537 )->parse();
538 $list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
539 } else {
540 $message = $this->msg( 'ipb-unblock' )->parse();
541 $list = SpecialPage::getTitleFor( 'Unblock' );
542 }
543 $links[] = $linkRenderer->makeKnownLink(
544 $list,
545 new HtmlArmor( $message )
546 );
547
548 # Link to the block list
549 $links[] = $linkRenderer->makeKnownLink(
550 SpecialPage::getTitleFor( 'BlockList' ),
551 $this->msg( 'ipb-blocklist' )->text()
552 );
553
554 $user = $this->getUser();
555
556 # Link to edit the block dropdown reasons, if applicable
557 if ( $this->permissionManager->userHasRight( $user, 'editinterface' ) ) {
558 $links[] = $linkRenderer->makeKnownLink(
559 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
560 $this->msg( 'ipb-edit-dropdown' )->text(),
561 [],
562 [ 'action' => 'edit' ]
563 );
564 }
565
566 $text = Html::rawElement(
567 'p',
568 [ 'class' => 'mw-ipb-conveniencelinks' ],
569 $this->getLanguage()->pipeList( $links )
570 );
571
572 $userTitle = self::getTargetUserTitle( $this->target );
573 if ( $userTitle ) {
574 # Get relevant extracts from the block and suppression logs, if possible
575 $out = '';
576
577 LogEventsList::showLogExtract(
578 $out,
579 'block',
580 $userTitle,
581 '',
582 [
583 'lim' => 10,
584 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
585 'showIfEmpty' => false
586 ]
587 );
588 $text .= $out;
589
590 # Add suppression block entries if allowed
591 if ( $this->permissionManager->userHasRight( $user, 'suppressionlog' ) ) {
592 LogEventsList::showLogExtract(
593 $out,
594 'suppress',
595 $userTitle,
596 '',
597 [
598 'lim' => 10,
599 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
600 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
601 'showIfEmpty' => false
602 ]
603 );
604
605 $text .= $out;
606 }
607 }
608
609 return $text;
610 }
611
618 protected static function getTargetUserTitle( $target ) {
619 if ( $target instanceof User ) {
620 return $target->getUserPage();
621 }
622
623 if ( is_string( $target ) && IPUtils::isIPAddress( $target ) ) {
624 return Title::makeTitleSafe( NS_USER, $target );
625 }
626
627 return null;
628 }
629
639 public static function getTargetAndType( $par, WebRequest $request = null ) {
640 $i = 0;
641 $target = null;
642
643 while ( true ) {
644 switch ( $i++ ) {
645 case 0:
646 # The HTMLForm will check wpTarget first and only if it doesn't get
647 # a value use the default, which will be generated from the options
648 # below; so this has to have a higher precedence here than $par, or
649 # we could end up with different values in $this->target and the HTMLForm!
650 if ( $request instanceof WebRequest ) {
651 $target = $request->getText( 'wpTarget', null );
652 }
653 break;
654 case 1:
655 $target = $par;
656 break;
657 case 2:
658 if ( $request instanceof WebRequest ) {
659 $target = $request->getText( 'ip', null );
660 }
661 break;
662 case 3:
663 # B/C @since 1.18
664 if ( $request instanceof WebRequest ) {
665 $target = $request->getText( 'wpBlockAddress', null );
666 }
667 break;
668 case 4:
669 break 2;
670 }
671
672 list( $target, $type ) = DatabaseBlock::parseTarget( $target );
673
674 if ( $type !== null ) {
675 return [ $target, $type ];
676 }
677 }
678
679 return [ null, null ];
680 }
681
690 public static function validateTargetField( $value, $alldata, $form ) {
691 $status = self::validateTarget( $value, $form->getUser() );
692 if ( !$status->isOK() ) {
693 $errors = $status->getErrorsArray();
694
695 return $form->msg( ...$errors[0] );
696 } else {
697 return true;
698 }
699 }
700
709 public static function validateTarget( $value, User $user ) {
710 global $wgBlockCIDRLimit;
711
713 list( $target, $type ) = self::getTargetAndType( $value );
714 $status = Status::newGood( $target );
715
716 if ( $type == DatabaseBlock::TYPE_USER ) {
717 if ( $target->isAnon() ) {
718 $status->fatal(
719 'nosuchusershort',
721 );
722 }
723
724 $unblockStatus = self::checkUnblockSelf( $target, $user );
725 if ( $unblockStatus !== true ) {
726 $status->fatal( 'badaccess', $unblockStatus );
727 }
728 } elseif ( $type == DatabaseBlock::TYPE_RANGE ) {
729 list( $ip, $range ) = explode( '/', $target, 2 );
730
731 if (
732 ( IPUtils::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
733 ( IPUtils::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
734 ) {
735 // Range block effectively disabled
736 $status->fatal( 'range_block_disabled' );
737 }
738
739 if (
740 ( IPUtils::isIPv4( $ip ) && $range > 32 ) ||
741 ( IPUtils::isIPv6( $ip ) && $range > 128 )
742 ) {
743 // Dodgy range
744 $status->fatal( 'ip_range_invalid' );
745 }
746
747 if ( IPUtils::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
748 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
749 }
750
751 if ( IPUtils::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
752 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
753 }
754 } elseif ( $type == DatabaseBlock::TYPE_IP ) {
755 # All is well
756 } else {
757 $status->fatal( 'badipaddress' );
758 }
759
760 return $status;
761 }
762
770 public static function processForm( array $data, IContextSource $context ) {
771 $performer = $context->getUser();
772 $isPartialBlock = isset( $data['EditingRestriction'] ) &&
773 $data['EditingRestriction'] === 'partial';
774
775 # This might have been a hidden field or a checkbox, so interesting data
776 # can come from it
777 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
778
780 list( $target, $type ) = self::getTargetAndType( $data['Target'] );
781 if ( $type == DatabaseBlock::TYPE_USER ) {
782 $user = $target;
783 $target = $user->getName();
784 $userId = $user->getId();
785
786 # Give admins a heads-up before they go and block themselves. Much messier
787 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
788 # permission anyway, although the code does allow for it.
789 # Note: Important to use $target instead of $data['Target']
790 # since both $data['PreviousTarget'] and $target are normalized
791 # but $data['target'] gets overridden by (non-normalized) request variable
792 # from previous request.
793 if ( $target === $performer->getName() &&
794 ( $data['PreviousTarget'] !== $target || !$data['Confirm'] )
795 ) {
796 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
797 }
798 } elseif ( $type == DatabaseBlock::TYPE_RANGE ) {
799 $user = null;
800 $userId = 0;
801 } elseif ( $type == DatabaseBlock::TYPE_IP ) {
802 $user = null;
804 $userId = 0;
805 } else {
806 # This should have been caught in the form field validation
807 return [ 'badipaddress' ];
808 }
809
810 // Reason, to be passed to the block object. For default values of reason, see
811 // HTMLSelectAndOtherField::getDefault
812 // @phan-suppress-next-line PhanPluginDuplicateConditionalNullCoalescing
813 $blockReason = isset( $data['Reason'][0] ) ? $data['Reason'][0] : '';
814
815 $expiryTime = self::parseExpiryInput( $data['Expiry'] );
816
817 if (
818 // an expiry time is needed
819 ( strlen( $data['Expiry'] ) == 0 ) ||
820 // can't be a larger string as 50 (it should be a time format in any way)
821 ( strlen( $data['Expiry'] ) > 50 ) ||
822 // check, if the time could be parsed
823 !$expiryTime
824 ) {
825 return [ 'ipb_expiry_invalid' ];
826 }
827
828 // an expiry time should be in the future, not in the
829 // past (wouldn't make any sense) - bug T123069
830 if ( $expiryTime < wfTimestampNow() ) {
831 return [ 'ipb_expiry_old' ];
832 }
833
834 if ( !isset( $data['DisableEmail'] ) ) {
835 $data['DisableEmail'] = false;
836 }
837
838 # If the user has done the form 'properly', they won't even have been given the
839 # option to suppress-block unless they have the 'hideuser' permission
840 if ( !isset( $data['HideUser'] ) ) {
841 $data['HideUser'] = false;
842 }
843
844 if ( $data['HideUser'] ) {
845 if ( !MediaWikiServices::getInstance()
847 ->userHasRight( $performer, 'hideuser' )
848 ) {
849 # this codepath is unreachable except by a malicious user spoofing forms,
850 # or by race conditions (user has hideuser and block rights, loads block form,
851 # and loses hideuser rights before submission); so need to fail completely
852 # rather than just silently disable hiding
853 return [ 'badaccess-group0' ];
854 }
855
856 if ( $isPartialBlock ) {
857 return [ 'ipb_hide_partial' ];
858 }
859
860 # Recheck params here...
861 $hideUserContribLimit = $context->getConfig()->get( 'HideUserContribLimit' );
862 if ( $type != DatabaseBlock::TYPE_USER ) {
863 $data['HideUser'] = false; # IP users should not be hidden
864 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
865 # Bad expiry.
866 return [ 'ipb_expiry_temp' ];
867 } elseif ( $hideUserContribLimit !== false
868 && $user->getEditCount() > $hideUserContribLimit
869 ) {
870 # Typically, the user should have a handful of edits.
871 # Disallow hiding users with many edits for performance.
872 return [ [ 'ipb_hide_invalid',
873 Message::numParam( $hideUserContribLimit ) ] ];
874 } elseif ( !$data['Confirm'] ) {
875 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
876 }
877 }
878
879 // Check whether the user can edit their own user talk page.
880 $blockAllowsUTEdit = $context->getConfig()->get( 'BlockAllowsUTEdit' );
881 $isUserTalkNamespaceBlock = !$isPartialBlock ||
882 in_array( NS_USER_TALK, explode( "\n", $data['NamespaceRestrictions'] ) );
883 if ( $isUserTalkNamespaceBlock ) {
884 // If the block blocks the user talk namespace, disallow own user talk edit if
885 // the global config disallows it; otherwise use the form field value.
886 $userTalkEditAllowed = $blockAllowsUTEdit ? !$data['DisableUTEdit'] : false;
887 } else {
888 // If the block doesn't block the user talk namespace, then it can't block own
889 // user talk edit, regardless of the config or field (T210475). Return error
890 // message if the field tries to disallow own user talk edit.
891 if ( isset( $data['DisableUTEdit'] ) && $data['DisableUTEdit'] ) {
892 return [ 'ipb-prevent-user-talk-edit' ];
893 }
894 $userTalkEditAllowed = true;
895 }
896
897 // A block is empty if it is a partial block, the page restrictions are empty, the
898 // namespace restrictions are empty, and none of the actions are enabled
899 if ( $isPartialBlock &&
900 !( isset( $data['PageRestrictions'] ) && $data['PageRestrictions'] !== '' ) &&
901 !( isset( $data['NamespaceRestrictions'] ) && $data['NamespaceRestrictions'] !== '' ) &&
902 $data['DisableEmail'] === false &&
903 ( $userTalkEditAllowed || !$blockAllowsUTEdit ) &&
904 !$data['CreateAccount']
905 ) {
906 return [ 'ipb-empty-block' ];
907 }
908
909 # Create block object.
910 $block = new DatabaseBlock();
911 $block->setTarget( $target );
912 $block->setBlocker( $performer );
913 $block->setReason( $blockReason );
914 $block->setExpiry( $expiryTime );
915 $block->isCreateAccountBlocked( $data['CreateAccount'] );
916 $block->isUsertalkEditAllowed( $userTalkEditAllowed );
917 $block->isEmailBlocked( $data['DisableEmail'] );
918 $block->isHardblock( $data['HardBlock'] );
919 $block->isAutoblocking( $data['AutoBlock'] );
920 $block->setHideName( $data['HideUser'] );
921
922 if ( $isPartialBlock ) {
923 $block->isSitewide( false );
924 }
925
926 $reason = [ 'hookaborted' ];
927 if ( !Hooks::runner()->onBlockIp( $block, $performer, $reason ) ) {
928 return $reason;
929 }
930
931 $pageRestrictions = [];
932 $namespaceRestrictions = [];
933 if ( isset( $data['PageRestrictions'] ) && $data['PageRestrictions'] !== '' ) {
934 $pageRestrictions = array_map( function ( $text ) {
935 $title = Title::newFromText( $text );
936 // Use the link cache since the title has already been loaded when
937 // the field was validated.
938 $restriction = new PageRestriction( 0, $title->getArticleID() );
939 $restriction->setTitle( $title );
940 return $restriction;
941 }, explode( "\n", $data['PageRestrictions'] ) );
942 }
943 if ( isset( $data['NamespaceRestrictions'] ) && $data['NamespaceRestrictions'] !== '' ) {
944 $namespaceRestrictions = array_map( function ( $id ) {
945 return new NamespaceRestriction( 0, $id );
946 }, explode( "\n", $data['NamespaceRestrictions'] ) );
947 }
948
949 $restrictions = ( array_merge( $pageRestrictions, $namespaceRestrictions ) );
950 $block->setRestrictions( $restrictions );
951
952 $priorBlock = null;
953 # Try to insert block. Is there a conflicting block?
954 $status = $block->insert();
955 if ( !$status ) {
956 # Indicates whether the user is confirming the block and is aware of
957 # the conflict (did not change the block target in the meantime)
958 $blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
959 && $data['PreviousTarget'] !== $target );
960
961 # Special case for API - T34434
962 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
963
964 # Show form unless the user is already aware of this...
965 if ( $blockNotConfirmed || $reblockNotAllowed ) {
966 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
967 # Otherwise, try to update the block...
968 } else {
969 # This returns direct blocks before autoblocks/rangeblocks, since we should
970 # be sure the user is blocked by now it should work for our purposes
971 $currentBlock = DatabaseBlock::newFromTarget( $target );
972 if ( !$currentBlock instanceof DatabaseBlock ) {
973 $logger = LoggerFactory::getInstance( 'BlockManager' );
974 $logger->warning( 'Block could not be inserted. No existing block was found.' );
975 return [ [ 'ipb-block-not-found', $block->getTarget() ] ];
976 }
977 if ( $block->equals( $currentBlock ) ) {
978 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
979 }
980 # If the name was hidden and the blocking user cannot hide
981 # names, then don't allow any block changes...
982 if ( $currentBlock->getHideName() && !MediaWikiServices::getInstance()
983 ->getPermissionManager()
984 ->userHasRight( $performer, 'hideuser' )
985 ) {
986 return [ 'cant-see-hidden-user' ];
987 }
988
989 $priorBlock = clone $currentBlock;
990 $currentBlock->setBlocker( $performer );
991 $currentBlock->isHardblock( $block->isHardblock() );
992 $currentBlock->isCreateAccountBlocked( $block->isCreateAccountBlocked() );
993 $currentBlock->setExpiry( $block->getExpiry() );
994 $currentBlock->isAutoblocking( $block->isAutoblocking() );
995 $currentBlock->setHideName( $block->getHideName() );
996 $currentBlock->isEmailBlocked( $block->isEmailBlocked() );
997 $currentBlock->isUsertalkEditAllowed( $block->isUsertalkEditAllowed() );
998 $currentBlock->setReason( $block->getReasonComment() );
999
1000 // Maintain the sitewide status. If partial blocks is not enabled,
1001 // saving the block will result in a sitewide block.
1002 $currentBlock->isSitewide( $block->isSitewide() );
1003
1004 // Set the block id of the restrictions.
1005 $blockRestrictionStore = MediaWikiServices::getInstance()->getBlockRestrictionStore();
1006 $currentBlock->setRestrictions(
1007 $blockRestrictionStore->setBlockId( $currentBlock->getId(), $restrictions )
1008 );
1009
1010 $status = $currentBlock->update();
1011 // TODO handle failure
1012
1013 $logaction = 'reblock';
1014
1015 # Unset _deleted fields if requested
1016 if ( $currentBlock->getHideName() && !$data['HideUser'] ) {
1018 }
1019
1020 # If hiding/unhiding a name, this should go in the private logs
1021 if ( (bool)$currentBlock->getHideName() ) {
1022 $data['HideUser'] = true;
1023 }
1024
1025 $block = $currentBlock;
1026 }
1027 } else {
1028 $logaction = 'block';
1029 }
1030
1031 Hooks::runner()->onBlockIpComplete( $block, $performer, $priorBlock );
1032
1033 # Set *_deleted fields if requested
1034 if ( $data['HideUser'] ) {
1036 }
1037
1038 # Can't watch a rangeblock
1039 if ( $type != DatabaseBlock::TYPE_RANGE && $data['Watch'] ) {
1041 Title::makeTitle( NS_USER, $target ),
1042 $performer,
1043 User::IGNORE_USER_RIGHTS
1044 );
1045 }
1046
1047 # DatabaseBlock constructor sanitizes certain block options on insert
1048 $data['BlockEmail'] = $block->isEmailBlocked();
1049 $data['AutoBlock'] = $block->isAutoblocking();
1050
1051 # Prepare log parameters
1052 $logParams = [];
1053
1054 $rawExpiry = $data['Expiry'];
1055 $logExpiry = wfIsInfinity( $rawExpiry ) ? 'infinity' : $rawExpiry;
1056
1057 $logParams['5::duration'] = $logExpiry;
1058 $logParams['6::flags'] = self::blockLogFlags( $data, $type );
1059 $logParams['sitewide'] = $block->isSitewide();
1060
1061 if ( !$block->isSitewide() ) {
1062 if ( $data['PageRestrictions'] !== '' ) {
1063 $logParams['7::restrictions']['pages'] = explode( "\n", $data['PageRestrictions'] );
1064 }
1065
1066 if ( $data['NamespaceRestrictions'] !== '' ) {
1067 $logParams['7::restrictions']['namespaces'] = explode( "\n", $data['NamespaceRestrictions'] );
1068 }
1069 }
1070
1071 # Make log entry, if the name is hidden, put it in the suppression log
1072 $log_type = $data['HideUser'] ? 'suppress' : 'block';
1073 $logEntry = new ManualLogEntry( $log_type, $logaction );
1074 $logEntry->setTarget( Title::makeTitle( NS_USER, $target ) );
1075 $logEntry->setComment( $blockReason );
1076 $logEntry->setPerformer( $performer );
1077 $logEntry->setParameters( $logParams );
1078 # Relate log ID to block ID (T27763)
1079 $logEntry->setRelations( [ 'ipb_id' => $block->getId() ] );
1080 $logId = $logEntry->insert();
1081
1082 if ( !empty( $data['Tags'] ) ) {
1083 $logEntry->addTags( $data['Tags'] );
1084 }
1085
1086 $logEntry->publish( $logId );
1087
1088 return true;
1089 }
1090
1101 public static function getSuggestedDurations( Language $lang = null, $includeOther = true ) {
1102 $msg = $lang === null
1103 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
1104 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
1105
1106 if ( $msg == '-' ) {
1107 return [];
1108 }
1109
1110 $a = XmlSelect::parseOptionsMessage( $msg );
1111
1112 if ( $a && $includeOther ) {
1113 // if options exist, add other to the end instead of the begining (which
1114 // is what happens by default).
1115 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
1116 }
1117
1118 return $a;
1119 }
1120
1132 public static function parseExpiryInput( $expiry ) {
1133 if ( wfIsInfinity( $expiry ) ) {
1134 return 'infinity';
1135 }
1136
1137 $expiry = strtotime( $expiry );
1138
1139 if ( $expiry < 0 || $expiry === false ) {
1140 return false;
1141 }
1142
1143 return wfTimestamp( TS_MW, $expiry );
1144 }
1145
1151 public static function canBlockEmail( UserIdentity $user ) {
1152 global $wgEnableUserEmail;
1153
1154 return ( $wgEnableUserEmail && MediaWikiServices::getInstance()
1156 ->userHasRight( $user, 'blockemail' ) );
1157 }
1158
1172 public static function checkUnblockSelf( $target, User $performer ) {
1173 return MediaWikiServices::getInstance()
1174 ->getBlockPermissionCheckerFactory()
1175 ->newBlockPermissionChecker( $target, $performer )
1176 ->checkBlockPermissions();
1177 }
1178
1186 protected static function blockLogFlags( array $data, $type ) {
1187 $config = RequestContext::getMain()->getConfig();
1188
1189 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1190
1191 $flags = [];
1192
1193 # when blocking a user the option 'anononly' is not available/has no effect
1194 # -> do not write this into log
1195 if ( !$data['HardBlock'] && $type != DatabaseBlock::TYPE_USER ) {
1196 // For grepping: message block-log-flags-anononly
1197 $flags[] = 'anononly';
1198 }
1199
1200 if ( $data['CreateAccount'] ) {
1201 // For grepping: message block-log-flags-nocreate
1202 $flags[] = 'nocreate';
1203 }
1204
1205 # Same as anononly, this is not displayed when blocking an IP address
1206 if ( !$data['AutoBlock'] && $type == DatabaseBlock::TYPE_USER ) {
1207 // For grepping: message block-log-flags-noautoblock
1208 $flags[] = 'noautoblock';
1209 }
1210
1211 if ( $data['DisableEmail'] ) {
1212 // For grepping: message block-log-flags-noemail
1213 $flags[] = 'noemail';
1214 }
1215
1216 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1217 // For grepping: message block-log-flags-nousertalk
1218 $flags[] = 'nousertalk';
1219 }
1220
1221 if ( $data['HideUser'] ) {
1222 // For grepping: message block-log-flags-hiddenname
1223 $flags[] = 'hiddenname';
1224 }
1225
1226 return implode( ',', $flags );
1227 }
1228
1235 public function onSubmit( array $data, HTMLForm $form = null ) {
1236 // If "Editing" checkbox is unchecked, the block must be a partial block affecting
1237 // actions other than editing, and there must be no restrictions.
1238 if ( isset( $data['Editing'] ) && $data['Editing'] === false ) {
1239 $data['EditingRestriction'] = 'partial';
1240 $data['PageRestrictions'] = '';
1241 $data['NamespaceRestrictions'] = '';
1242 }
1243 return self::processForm( $data, $form->getContext() );
1244 }
1245
1250 public function onSuccess() {
1251 $out = $this->getOutput();
1252 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1253 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
1254 }
1255
1264 public function prefixSearchSubpages( $search, $limit, $offset ) {
1265 $user = User::newFromName( $search );
1266 if ( !$user ) {
1267 // No prefix suggestion for invalid user
1268 return [];
1269 }
1270 // Autocomplete subpage as user list - public to allow caching
1271 return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
1272 }
1273
1274 protected function getGroupName() {
1275 return 'users';
1276 }
1277}
getPermissionManager()
getUser()
$wgBlockCIDRLimit
Limits on the possible sizes of range blocks.
$wgEnableUserEmail
Set to true to enable user-to-user e-mail.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfIsInfinity( $str)
Determine input string is represents as infinity.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
An error page which can definitely be safely rendered using the OutputPage.
Special page which uses an HTMLForm to handle processing.
string null $par
The sub-page of the special page.
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition HTMLForm.php:135
setHeaderText( $msg, $section=null)
Set header text, inside the form.
Definition HTMLForm.php:841
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
formatErrors( $errors)
Format a stack of error messages into a single HTML string.
setSubmitDestructive()
Identify that the submit button in the form has a destructive action.
addHeaderText( $msg, $section=null)
Add HTML to the header, inside the form.
Definition HTMLForm.php:819
Marks HTML that shouldn't be escaped.
Definition HtmlArmor.php:30
Pre-librarized class name for IPUtils.
Definition IP.php:80
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition Language.php:41
Class for creating new log entries and inserting them into the database.
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
getType()
Get the type of target for this particular block.int|null AbstractBlock::TYPE_ constant,...
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
A service class for checking permissions To obtain an instance, use MediaWikiServices::getInstance()-...
static numParam( $num)
Definition Message.php:1064
static suppressUserName( $name, $userId, IDatabase $dbw=null)
static unsuppressUserName( $name, $userId, IDatabase $dbw=null)
A special page that allows users with 'block' right to block users from editing pages and other actio...
int $type
DatabaseBlock::TYPE_ constant.
requiresUnblock()
We allow certain special cases where user is blocked.
preText()
Add header elements like block log entries, etc.
static processForm(array $data, IContextSource $context)
Given the form data, actually implement a block.
onSuccess()
Do something exciting on successful processing of the form, most likely to show a confirmation messag...
static validateTarget( $value, User $user)
Validate a block target.
static parseExpiryInput( $expiry)
Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute ("24 May 2034",...
__construct(PermissionManager $permissionManager)
static getTargetAndType( $par, WebRequest $request=null)
Determine the target of the block, and the type of target.
static validateTargetField( $value, $alldata, $form)
HTMLForm field validation-callback for Target field.
bool $requestedHideUser
Whether the previous submission of the form asked for HideUser.
maybeAlterFormDefaults(&$fields)
If the user has already been blocked with similar settings, load that block and change the defaults f...
getFormFields()
Get the HTMLForm descriptor array for the block form.
postText()
Add footer elements to the form.
getDisplayFormat()
Get display format for the form.
PermissionManager $permissionManager
static checkUnblockSelf( $target, User $performer)
T17810: Sitewide blocked admins should not be able to block/unblock others with one exception; they c...
setParameter( $par)
Handle some magic here.
User string $previousTarget
The previous block target.
checkExecutePermissions(User $user)
Checks that the user can unblock themselves if they are trying to do so.
alterForm(HTMLForm $form)
Customizes the HTMLForm a bit.
static getTargetUserTitle( $target)
Get a user page target for things like logs.
User string null $target
User to be blocked, as passed either by parameter (url?wpTarget=Foo) or as subpage (Special:Block/Foo...
static canBlockEmail(UserIdentity $user)
Can we do an email block?
doesWrites()
Indicates whether this special page may perform database writes.
onSubmit(array $data, HTMLForm $form=null)
Process the form on POST submission.
static blockLogFlags(array $data, $type)
Return a comma-delimited list of "flags" to be passed to the log reader for this block,...
static getSuggestedDurations(Language $lang=null, $includeOther=true)
Get an array of suggested block durations from MediaWiki:Ipboptions.
prefixSearchSubpages( $search, $limit, $offset)
Return an array of subpages beginning with $search that this special page will accept.
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
getName()
Get the name of this Special Page.
getOutput()
Get the OutputPage being used for this instance.
getSkin()
Shortcut to get the skin being used for this instance.
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
getConfig()
Shortcut to get main config object.
getRequest()
Get the WebRequest being used for this instance.
getLanguage()
Shortcut to get user's language.
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
MediaWiki Linker LinkRenderer null $linkRenderer
static search( $audience, $search, $limit, $offset=0)
Do a prefix search of user names and return a list of matching user names.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:60
getName()
Get the user name, or the IP of an anonymous user.
Definition User.php:2150
getUserPage()
Get this user's personal page title.
Definition User.php:3802
isAnon()
Get whether the user is anonymous.
Definition User.php:3087
static doWatch(Title $title, User $user, $checkRights=User::CHECK_USER_RIGHTS, ?string $expiry=null)
Watch a page.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
static parseOptionsMessage(string $msg)
Parse labels and values out of a comma- and colon-separated list of options, such as is used for expi...
const NS_USER
Definition Defines.php:72
const NS_USER_TALK
Definition Defines.php:73
Interface for objects which can provide a MediaWiki context on request.
getConfig()
Get the site configuration.
Interface for objects representing user identity.
if(!isset( $args[0])) $lang