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