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