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