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