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