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