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