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