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