Update/add documentation
[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 return null;
448 }
449
450 /**
451 * Determine the target of the block, and the type of target
452 * TODO: should be in Block.php?
453 * @param string $par subpage parameter passed to setup, or data value from
454 * the HTMLForm
455 * @param $request WebRequest optionally try and get data from a request too
456 * @return array( User|string|null, Block::TYPE_ constant|null )
457 */
458 public static function getTargetAndType( $par, WebRequest $request = null ) {
459 $i = 0;
460 $target = null;
461
462 while ( true ) {
463 switch ( $i++ ) {
464 case 0:
465 # The HTMLForm will check wpTarget first and only if it doesn't get
466 # a value use the default, which will be generated from the options
467 # below; so this has to have a higher precedence here than $par, or
468 # we could end up with different values in $this->target and the HTMLForm!
469 if ( $request instanceof WebRequest ) {
470 $target = $request->getText( 'wpTarget', null );
471 }
472 break;
473 case 1:
474 $target = $par;
475 break;
476 case 2:
477 if ( $request instanceof WebRequest ) {
478 $target = $request->getText( 'ip', null );
479 }
480 break;
481 case 3:
482 # B/C @since 1.18
483 if ( $request instanceof WebRequest ) {
484 $target = $request->getText( 'wpBlockAddress', null );
485 }
486 break;
487 case 4:
488 break 2;
489 }
490
491 list( $target, $type ) = Block::parseTarget( $target );
492
493 if ( $type !== null ) {
494 return array( $target, $type );
495 }
496 }
497
498 return array( null, null );
499 }
500
501 /**
502 * HTMLForm field validation-callback for Target field.
503 * @since 1.18
504 * @param $value String
505 * @param $alldata Array
506 * @param $form HTMLForm
507 * @return Message
508 */
509 public static function validateTargetField( $value, $alldata, $form ) {
510 $status = self::validateTarget( $value, $form->getUser() );
511 if ( !$status->isOK() ) {
512 $errors = $status->getErrorsArray();
513 return call_user_func_array( array( $form, 'msg' ), $errors[0] );
514 } else {
515 return true;
516 }
517 }
518
519 /**
520 * Validate a block target.
521 *
522 * @since 1.21
523 * @param string $value Block target to check
524 * @param User $user Performer of the block
525 * @return Status
526 */
527 public static function validateTarget( $value, User $user ) {
528 global $wgBlockCIDRLimit;
529
530 /** @var User $target */
531 list( $target, $type ) = self::getTargetAndType( $value );
532 $status = Status::newGood( $target );
533
534 if ( $type == Block::TYPE_USER ) {
535 if ( $target->isAnon() ) {
536 $status->fatal(
537 'nosuchusershort',
538 wfEscapeWikiText( $target->getName() )
539 );
540 }
541
542 $unblockStatus = self::checkUnblockSelf( $target, $user );
543 if ( $unblockStatus !== true ) {
544 $status->fatal( 'badaccess', $unblockStatus );
545 }
546 } elseif ( $type == Block::TYPE_RANGE ) {
547 list( $ip, $range ) = explode( '/', $target, 2 );
548
549 if (
550 ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
551 ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
552 ) {
553 // Range block effectively disabled
554 $status->fatal( 'range_block_disabled' );
555 }
556
557 if (
558 ( IP::isIPv4( $ip ) && $range > 32 ) ||
559 ( IP::isIPv6( $ip ) && $range > 128 )
560 ) {
561 // Dodgy range
562 $status->fatal( 'ip_range_invalid' );
563 }
564
565 if ( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
566 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
567 }
568
569 if ( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
570 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
571 }
572 } elseif ( $type == Block::TYPE_IP ) {
573 # All is well
574 } else {
575 $status->fatal( 'badipaddress' );
576 }
577
578 return $status;
579 }
580
581 /**
582 * Submit callback for an HTMLForm object, will simply pass
583 * @param $data array
584 * @param $form HTMLForm
585 * @return Bool|String
586 */
587 public static function processUIForm( array $data, HTMLForm $form ) {
588 return self::processForm( $data, $form->getContext() );
589 }
590
591 /**
592 * Given the form data, actually implement a block
593 * @param $data Array
594 * @param $context IContextSource
595 * @return Bool|String
596 */
597 public static function processForm( array $data, IContextSource $context ) {
598 global $wgBlockAllowsUTEdit;
599
600 $performer = $context->getUser();
601
602 // Handled by field validator callback
603 // self::validateTargetField( $data['Target'] );
604
605 # This might have been a hidden field or a checkbox, so interesting data
606 # can come from it
607 $data['Confirm'] = !in_array( $data['Confirm'], array( '', '0', null, false ), true );
608
609 /** @var User $target */
610 list( $target, $type ) = self::getTargetAndType( $data['Target'] );
611 if ( $type == Block::TYPE_USER ) {
612 $user = $target;
613 $target = $user->getName();
614 $userId = $user->getId();
615
616 # Give admins a heads-up before they go and block themselves. Much messier
617 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
618 # permission anyway, although the code does allow for it.
619 # Note: Important to use $target instead of $data['Target']
620 # since both $data['PreviousTarget'] and $target are normalized
621 # but $data['target'] gets overriden by (non-normalized) request variable
622 # from previous request.
623 if ( $target === $performer->getName() &&
624 ( $data['PreviousTarget'] !== $target || !$data['Confirm'] )
625 ) {
626 return array( 'ipb-blockingself' );
627 }
628 } elseif ( $type == Block::TYPE_RANGE ) {
629 $userId = 0;
630 } elseif ( $type == Block::TYPE_IP ) {
631 $target = $target->getName();
632 $userId = 0;
633 } else {
634 # This should have been caught in the form field validation
635 return array( 'badipaddress' );
636 }
637
638 if ( ( strlen( $data['Expiry'] ) == 0 ) || ( strlen( $data['Expiry'] ) > 50 )
639 || !self::parseExpiryInput( $data['Expiry'] )
640 ) {
641 return array( 'ipb_expiry_invalid' );
642 }
643
644 if ( !isset( $data['DisableEmail'] ) ) {
645 $data['DisableEmail'] = false;
646 }
647
648 # If the user has done the form 'properly', they won't even have been given the
649 # option to suppress-block unless they have the 'hideuser' permission
650 if ( !isset( $data['HideUser'] ) ) {
651 $data['HideUser'] = false;
652 }
653
654 if ( $data['HideUser'] ) {
655 if ( !$performer->isAllowed( 'hideuser' ) ) {
656 # this codepath is unreachable except by a malicious user spoofing forms,
657 # or by race conditions (user has oversight and sysop, loads block form,
658 # and is de-oversighted before submission); so need to fail completely
659 # rather than just silently disable hiding
660 return array( 'badaccess-group0' );
661 }
662
663 # Recheck params here...
664 if ( $type != Block::TYPE_USER ) {
665 $data['HideUser'] = false; # IP users should not be hidden
666 } elseif ( !in_array( $data['Expiry'], array( 'infinite', 'infinity', 'indefinite' ) ) ) {
667 # Bad expiry.
668 return array( 'ipb_expiry_temp' );
669 } elseif ( $user->getEditCount() > self::HIDEUSER_CONTRIBLIMIT ) {
670 # Typically, the user should have a handful of edits.
671 # Disallow hiding users with many edits for performance.
672 return array( 'ipb_hide_invalid' );
673 } elseif ( !$data['Confirm'] ) {
674 return array( 'ipb-confirmhideuser' );
675 }
676 }
677
678 # Create block object.
679 $block = new Block();
680 $block->setTarget( $target );
681 $block->setBlocker( $performer );
682 $block->mReason = $data['Reason'][0];
683 $block->mExpiry = self::parseExpiryInput( $data['Expiry'] );
684 $block->prevents( 'createaccount', $data['CreateAccount'] );
685 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit || $data['DisableUTEdit'] ) );
686 $block->prevents( 'sendemail', $data['DisableEmail'] );
687 $block->isHardblock( $data['HardBlock'] );
688 $block->isAutoblocking( $data['AutoBlock'] );
689 $block->mHideName = $data['HideUser'];
690
691 if ( !wfRunHooks( 'BlockIp', array( &$block, &$performer ) ) ) {
692 return array( 'hookaborted' );
693 }
694
695 # Try to insert block. Is there a conflicting block?
696 $status = $block->insert();
697 if ( !$status ) {
698 # Indicates whether the user is confirming the block and is aware of
699 # the conflict (did not change the block target in the meantime)
700 $blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
701 && $data['PreviousTarget'] !== $target );
702
703 # Special case for API - bug 32434
704 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
705
706 # Show form unless the user is already aware of this...
707 if ( $blockNotConfirmed || $reblockNotAllowed ) {
708 return array( array( 'ipb_already_blocked', $block->getTarget() ) );
709 # Otherwise, try to update the block...
710 } else {
711 # This returns direct blocks before autoblocks/rangeblocks, since we should
712 # be sure the user is blocked by now it should work for our purposes
713 $currentBlock = Block::newFromTarget( $target );
714
715 if ( $block->equals( $currentBlock ) ) {
716 return array( array( 'ipb_already_blocked', $block->getTarget() ) );
717 }
718
719 # If the name was hidden and the blocking user cannot hide
720 # names, then don't allow any block changes...
721 if ( $currentBlock->mHideName && !$performer->isAllowed( 'hideuser' ) ) {
722 return array( 'cant-see-hidden-user' );
723 }
724
725 $currentBlock->delete();
726 $status = $block->insert();
727 $logaction = 'reblock';
728
729 # Unset _deleted fields if requested
730 if ( $currentBlock->mHideName && !$data['HideUser'] ) {
731 RevisionDeleteUser::unsuppressUserName( $target, $userId );
732 }
733
734 # If hiding/unhiding a name, this should go in the private logs
735 if ( (bool)$currentBlock->mHideName ) {
736 $data['HideUser'] = true;
737 }
738 }
739 } else {
740 $logaction = 'block';
741 }
742
743 wfRunHooks( 'BlockIpComplete', array( $block, $performer ) );
744
745 # Set *_deleted fields if requested
746 if ( $data['HideUser'] ) {
747 RevisionDeleteUser::suppressUserName( $target, $userId );
748 }
749
750 # Can't watch a rangeblock
751 if ( $type != Block::TYPE_RANGE && $data['Watch'] ) {
752 $performer->addWatch( Title::makeTitle( NS_USER, $target ) );
753 }
754
755 # Block constructor sanitizes certain block options on insert
756 $data['BlockEmail'] = $block->prevents( 'sendemail' );
757 $data['AutoBlock'] = $block->isAutoblocking();
758
759 # Prepare log parameters
760 $logParams = array();
761 $logParams[] = $data['Expiry'];
762 $logParams[] = self::blockLogFlags( $data, $type );
763
764 # Make log entry, if the name is hidden, put it in the oversight log
765 $log_type = $data['HideUser'] ? 'suppress' : 'block';
766 $log = new LogPage( $log_type );
767 $log_id = $log->addEntry(
768 $logaction,
769 Title::makeTitle( NS_USER, $target ),
770 $data['Reason'][0],
771 $logParams
772 );
773 # Relate log ID to block IDs (bug 25763)
774 $blockIds = array_merge( array( $status['id'] ), $status['autoIds'] );
775 $log->addRelations( 'ipb_id', $blockIds, $log_id );
776
777 # Report to the user
778 return true;
779 }
780
781 /**
782 * Get an array of suggested block durations from MediaWiki:Ipboptions
783 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
784 * to the standard "**<duration>|<displayname>" format?
785 * @param $lang Language|null the language to get the durations in, or null to use
786 * the wiki's content language
787 * @return Array
788 */
789 public static function getSuggestedDurations( $lang = null ) {
790 $a = array();
791 $msg = $lang === null
792 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
793 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
794
795 if ( $msg == '-' ) {
796 return array();
797 }
798
799 foreach ( explode( ',', $msg ) as $option ) {
800 if ( strpos( $option, ':' ) === false ) {
801 $option = "$option:$option";
802 }
803
804 list( $show, $value ) = explode( ':', $option );
805 $a[htmlspecialchars( $show )] = htmlspecialchars( $value );
806 }
807
808 return $a;
809 }
810
811 /**
812 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
813 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
814 * @param string $expiry whatever was typed into the form
815 * @return String: timestamp or "infinity" string for the DB implementation
816 */
817 public static function parseExpiryInput( $expiry ) {
818 static $infinity;
819 if ( $infinity == null ) {
820 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
821 }
822
823 if ( $expiry == 'infinite' || $expiry == 'indefinite' ) {
824 $expiry = $infinity;
825 } else {
826 $expiry = strtotime( $expiry );
827
828 if ( $expiry < 0 || $expiry === false ) {
829 return false;
830 }
831
832 $expiry = wfTimestamp( TS_MW, $expiry );
833 }
834
835 return $expiry;
836 }
837
838 /**
839 * Can we do an email block?
840 * @param $user User: the sysop wanting to make a block
841 * @return Boolean
842 */
843 public static function canBlockEmail( $user ) {
844 global $wgEnableUserEmail, $wgSysopEmailBans;
845
846 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
847 }
848
849 /**
850 * bug 15810: blocked admins should not be able to block/unblock
851 * others, and probably shouldn't be able to unblock themselves
852 * either.
853 * @param $user User|Int|String
854 * @param $performer User user doing the request
855 * @return Bool|String true or error message key
856 */
857 public static function checkUnblockSelf( $user, User $performer ) {
858 if ( is_int( $user ) ) {
859 $user = User::newFromId( $user );
860 } elseif ( is_string( $user ) ) {
861 $user = User::newFromName( $user );
862 }
863
864 if ( $performer->isBlocked() ) {
865 if ( $user instanceof User && $user->getId() == $performer->getId() ) {
866 # User is trying to unblock themselves
867 if ( $performer->isAllowed( 'unblockself' ) ) {
868 return true;
869 # User blocked themselves and is now trying to reverse it
870 } elseif ( $performer->blockedBy() === $performer->getName() ) {
871 return true;
872 } else {
873 return 'ipbnounblockself';
874 }
875 } else {
876 # User is trying to block/unblock someone else
877 return 'ipbblocked';
878 }
879 } else {
880 return true;
881 }
882 }
883
884 /**
885 * Return a comma-delimited list of "flags" to be passed to the log
886 * reader for this block, to provide more information in the logs
887 * @param array $data from HTMLForm data
888 * @param $type Block::TYPE_ constant (USER, RANGE, or IP)
889 * @return string
890 */
891 protected static function blockLogFlags( array $data, $type ) {
892 global $wgBlockAllowsUTEdit;
893 $flags = array();
894
895 # when blocking a user the option 'anononly' is not available/has no effect
896 # -> do not write this into log
897 if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
898 // For grepping: message block-log-flags-anononly
899 $flags[] = 'anononly';
900 }
901
902 if ( $data['CreateAccount'] ) {
903 // For grepping: message block-log-flags-nocreate
904 $flags[] = 'nocreate';
905 }
906
907 # Same as anononly, this is not displayed when blocking an IP address
908 if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
909 // For grepping: message block-log-flags-noautoblock
910 $flags[] = 'noautoblock';
911 }
912
913 if ( $data['DisableEmail'] ) {
914 // For grepping: message block-log-flags-noemail
915 $flags[] = 'noemail';
916 }
917
918 if ( $wgBlockAllowsUTEdit && $data['DisableUTEdit'] ) {
919 // For grepping: message block-log-flags-nousertalk
920 $flags[] = 'nousertalk';
921 }
922
923 if ( $data['HideUser'] ) {
924 // For grepping: message block-log-flags-hiddenname
925 $flags[] = 'hiddenname';
926 }
927
928 return implode( ',', $flags );
929 }
930
931 /**
932 * Process the form on POST submission.
933 * @param $data Array
934 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
935 */
936 public function onSubmit( array $data ) {
937 // This isn't used since we need that HTMLForm that's passed in the
938 // second parameter. See alterForm for the real function
939 }
940
941 /**
942 * Do something exciting on successful processing of the form, most likely to show a
943 * confirmation message
944 */
945 public function onSuccess() {
946 $out = $this->getOutput();
947 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
948 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
949 }
950
951 protected function getGroupName() {
952 return 'users';
953 }
954 }
955
956 # BC @since 1.18
957 class IPBlockForm extends SpecialBlock {}