Purge remaining oversight references from code
[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->setSubmitDestructive();
101
102 $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
103 $form->setSubmitTextMsg( $msg );
104
105 $this->addHelpLink( 'Help:Blocking users' );
106
107 # Don't need to do anything if the form has been posted
108 if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
109 $s = $form->formatErrors( $this->preErrors );
110 if ( $s ) {
111 $form->addHeaderText( Html::rawElement(
112 'div',
113 array( 'class' => 'error' ),
114 $s
115 ) );
116 }
117 }
118 }
119
120 /**
121 * Get the HTMLForm descriptor array for the block form
122 * @return array
123 */
124 protected function getFormFields() {
125 global $wgBlockAllowsUTEdit;
126
127 $user = $this->getUser();
128
129 $suggestedDurations = self::getSuggestedDurations();
130
131 $a = array(
132 'Target' => array(
133 'type' => 'text',
134 'label-message' => 'ipaddressorusername',
135 'id' => 'mw-bi-target',
136 'size' => '45',
137 'autofocus' => true,
138 'required' => true,
139 'validation-callback' => array( __CLASS__, 'validateTargetField' ),
140 'cssclass' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
141 ),
142 'Expiry' => array(
143 'type' => !count( $suggestedDurations ) ? 'text' : 'selectorother',
144 'label-message' => 'ipbexpiry',
145 'required' => true,
146 'options' => $suggestedDurations,
147 'other' => $this->msg( 'ipbother' )->text(),
148 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
149 ),
150 'Reason' => array(
151 'type' => 'selectandother',
152 'maxlength' => 255,
153 'label-message' => 'ipbreason',
154 'options-message' => 'ipbreason-dropdown',
155 ),
156 'CreateAccount' => array(
157 'type' => 'check',
158 'label-message' => 'ipbcreateaccount',
159 'default' => true,
160 ),
161 );
162
163 if ( self::canBlockEmail( $user ) ) {
164 $a['DisableEmail'] = array(
165 'type' => 'check',
166 'label-message' => 'ipbemailban',
167 );
168 }
169
170 if ( $wgBlockAllowsUTEdit ) {
171 $a['DisableUTEdit'] = array(
172 'type' => 'check',
173 'label-message' => 'ipb-disableusertalk',
174 'default' => false,
175 );
176 }
177
178 $a['AutoBlock'] = array(
179 'type' => 'check',
180 'label-message' => 'ipbenableautoblock',
181 'default' => true,
182 );
183
184 # Allow some users to hide name from block log, blocklist and listusers
185 if ( $user->isAllowed( 'hideuser' ) ) {
186 $a['HideUser'] = array(
187 'type' => 'check',
188 'label-message' => 'ipbhidename',
189 'cssclass' => 'mw-block-hideuser',
190 );
191 }
192
193 # Watchlist their user page? (Only if user is logged in)
194 if ( $user->isLoggedIn() ) {
195 $a['Watch'] = array(
196 'type' => 'check',
197 'label-message' => 'ipbwatchuser',
198 );
199 }
200
201 $a['HardBlock'] = array(
202 'type' => 'check',
203 'label-message' => 'ipb-hardblock',
204 'default' => false,
205 );
206
207 # This is basically a copy of the Target field, but the user can't change it, so we
208 # can see if the warnings we maybe showed to the user before still apply
209 $a['PreviousTarget'] = array(
210 'type' => 'hidden',
211 'default' => false,
212 );
213
214 # We'll turn this into a checkbox if we need to
215 $a['Confirm'] = array(
216 'type' => 'hidden',
217 'default' => '',
218 'label-message' => 'ipb-confirm',
219 );
220
221 $this->maybeAlterFormDefaults( $a );
222
223 // Allow extensions to add more fields
224 Hooks::run( 'SpecialBlockModifyFormFields', array( $this, &$a ) );
225
226 return $a;
227 }
228
229 /**
230 * If the user has already been blocked with similar settings, load that block
231 * and change the defaults for the form fields to match the existing settings.
232 * @param array $fields HTMLForm descriptor array
233 * @return bool Whether fields were altered (that is, whether the target is
234 * already blocked)
235 */
236 protected function maybeAlterFormDefaults( &$fields ) {
237 # This will be overwritten by request data
238 $fields['Target']['default'] = (string)$this->target;
239
240 if ( $this->target ) {
241 $status = self::validateTarget( $this->target, $this->getUser() );
242 if ( !$status->isOK() ) {
243 $errors = $status->getErrorsArray();
244 $this->preErrors = array_merge( $this->preErrors, $errors );
245 }
246 }
247
248 # This won't be
249 $fields['PreviousTarget']['default'] = (string)$this->target;
250
251 $block = Block::newFromTarget( $this->target );
252
253 if ( $block instanceof Block && !$block->mAuto # The block exists and isn't an autoblock
254 && ( $this->type != Block::TYPE_RANGE # The block isn't a rangeblock
255 || $block->getTarget() == $this->target ) # or if it is, the range is what we're about to block
256 ) {
257 $fields['HardBlock']['default'] = $block->isHardblock();
258 $fields['CreateAccount']['default'] = $block->prevents( 'createaccount' );
259 $fields['AutoBlock']['default'] = $block->isAutoblocking();
260
261 if ( isset( $fields['DisableEmail'] ) ) {
262 $fields['DisableEmail']['default'] = $block->prevents( 'sendemail' );
263 }
264
265 if ( isset( $fields['HideUser'] ) ) {
266 $fields['HideUser']['default'] = $block->mHideName;
267 }
268
269 if ( isset( $fields['DisableUTEdit'] ) ) {
270 $fields['DisableUTEdit']['default'] = $block->prevents( 'editownusertalk' );
271 }
272
273 // If the username was hidden (ipb_deleted == 1), don't show the reason
274 // unless this user also has rights to hideuser: Bug 35839
275 if ( !$block->mHideName || $this->getUser()->isAllowed( 'hideuser' ) ) {
276 $fields['Reason']['default'] = $block->mReason;
277 } else {
278 $fields['Reason']['default'] = '';
279 }
280
281 if ( $this->getRequest()->wasPosted() ) {
282 # Ok, so we got a POST submission asking us to reblock a user. So show the
283 # confirm checkbox; the user will only see it if they haven't previously
284 $fields['Confirm']['type'] = 'check';
285 } else {
286 # We got a target, but it wasn't a POST request, so the user must have gone
287 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
288 # as long as they go ahead and block *that* user
289 $fields['Confirm']['default'] = 1;
290 }
291
292 if ( $block->mExpiry == 'infinity' ) {
293 $fields['Expiry']['default'] = 'infinite';
294 } else {
295 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->mExpiry );
296 }
297
298 $this->alreadyBlocked = true;
299 $this->preErrors[] = array( 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) );
300 }
301
302 # We always need confirmation to do HideUser
303 if ( $this->requestedHideUser ) {
304 $fields['Confirm']['type'] = 'check';
305 unset( $fields['Confirm']['default'] );
306 $this->preErrors[] = array( 'ipb-confirmhideuser', 'ipb-confirmaction' );
307 }
308
309 # Or if the user is trying to block themselves
310 if ( (string)$this->target === $this->getUser()->getName() ) {
311 $fields['Confirm']['type'] = 'check';
312 unset( $fields['Confirm']['default'] );
313 $this->preErrors[] = array( 'ipb-blockingself', 'ipb-confirmaction' );
314 }
315 }
316
317 /**
318 * Add header elements like block log entries, etc.
319 * @return string
320 */
321 protected function preText() {
322 $this->getOutput()->addModules( array( 'mediawiki.special.block', 'mediawiki.userSuggest' ) );
323
324 $text = $this->msg( 'blockiptext' )->parse();
325
326 $otherBlockMessages = array();
327 if ( $this->target !== null ) {
328 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
329 Hooks::run( 'OtherBlockLogLink', array( &$otherBlockMessages, $this->target ) );
330
331 if ( count( $otherBlockMessages ) ) {
332 $s = Html::rawElement(
333 'h2',
334 array(),
335 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
336 ) . "\n";
337
338 $list = '';
339
340 foreach ( $otherBlockMessages as $link ) {
341 $list .= Html::rawElement( 'li', array(), $link ) . "\n";
342 }
343
344 $s .= Html::rawElement(
345 'ul',
346 array( 'class' => 'mw-blockip-alreadyblocked' ),
347 $list
348 ) . "\n";
349
350 $text .= $s;
351 }
352 }
353
354 return $text;
355 }
356
357 /**
358 * Add footer elements to the form
359 * @return string
360 */
361 protected function postText() {
362 $links = array();
363
364 # Link to the user's contributions, if applicable
365 if ( $this->target instanceof User ) {
366 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
367 $links[] = Linker::link(
368 $contribsPage,
369 $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->escaped()
370 );
371 }
372
373 # Link to unblock the specified user, or to a blank unblock form
374 if ( $this->target instanceof User ) {
375 $message = $this->msg(
376 'ipb-unblock-addr',
377 wfEscapeWikiText( $this->target->getName() )
378 )->parse();
379 $list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
380 } else {
381 $message = $this->msg( 'ipb-unblock' )->parse();
382 $list = SpecialPage::getTitleFor( 'Unblock' );
383 }
384 $links[] = Linker::linkKnown( $list, $message, array() );
385
386 # Link to the block list
387 $links[] = Linker::linkKnown(
388 SpecialPage::getTitleFor( 'BlockList' ),
389 $this->msg( 'ipb-blocklist' )->escaped()
390 );
391
392 $user = $this->getUser();
393
394 # Link to edit the block dropdown reasons, if applicable
395 if ( $user->isAllowed( 'editinterface' ) ) {
396 $links[] = Linker::linkKnown(
397 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
398 $this->msg( 'ipb-edit-dropdown' )->escaped(),
399 array(),
400 array( 'action' => 'edit' )
401 );
402 }
403
404 $text = Html::rawElement(
405 'p',
406 array( 'class' => 'mw-ipb-conveniencelinks' ),
407 $this->getLanguage()->pipeList( $links )
408 );
409
410 $userTitle = self::getTargetUserTitle( $this->target );
411 if ( $userTitle ) {
412 # Get relevant extracts from the block and suppression logs, if possible
413 $out = '';
414
415 LogEventsList::showLogExtract(
416 $out,
417 'block',
418 $userTitle,
419 '',
420 array(
421 'lim' => 10,
422 'msgKey' => array( 'blocklog-showlog', $userTitle->getText() ),
423 'showIfEmpty' => false
424 )
425 );
426 $text .= $out;
427
428 # Add suppression block entries if allowed
429 if ( $user->isAllowed( 'suppressionlog' ) ) {
430 LogEventsList::showLogExtract(
431 $out,
432 'suppress',
433 $userTitle,
434 '',
435 array(
436 'lim' => 10,
437 'conds' => array( 'log_action' => array( 'block', 'reblock', 'unblock' ) ),
438 'msgKey' => array( 'blocklog-showsuppresslog', $userTitle->getText() ),
439 'showIfEmpty' => false
440 )
441 );
442
443 $text .= $out;
444 }
445 }
446
447 return $text;
448 }
449
450 /**
451 * Get a user page target for things like logs.
452 * This handles account and IP range targets.
453 * @param User|string $target
454 * @return Title|null
455 */
456 protected static function getTargetUserTitle( $target ) {
457 if ( $target instanceof User ) {
458 return $target->getUserPage();
459 } elseif ( IP::isIPAddress( $target ) ) {
460 return Title::makeTitleSafe( NS_USER, $target );
461 }
462
463 return null;
464 }
465
466 /**
467 * Determine the target of the block, and the type of target
468 * @todo Should be in Block.php?
469 * @param string $par Subpage parameter passed to setup, or data value from
470 * the HTMLForm
471 * @param WebRequest $request Optionally try and get data from a request too
472 * @return array( User|string|null, Block::TYPE_ constant|null )
473 */
474 public static function getTargetAndType( $par, WebRequest $request = null ) {
475 $i = 0;
476 $target = null;
477
478 while ( true ) {
479 switch ( $i++ ) {
480 case 0:
481 # The HTMLForm will check wpTarget first and only if it doesn't get
482 # a value use the default, which will be generated from the options
483 # below; so this has to have a higher precedence here than $par, or
484 # we could end up with different values in $this->target and the HTMLForm!
485 if ( $request instanceof WebRequest ) {
486 $target = $request->getText( 'wpTarget', null );
487 }
488 break;
489 case 1:
490 $target = $par;
491 break;
492 case 2:
493 if ( $request instanceof WebRequest ) {
494 $target = $request->getText( 'ip', null );
495 }
496 break;
497 case 3:
498 # B/C @since 1.18
499 if ( $request instanceof WebRequest ) {
500 $target = $request->getText( 'wpBlockAddress', null );
501 }
502 break;
503 case 4:
504 break 2;
505 }
506
507 list( $target, $type ) = Block::parseTarget( $target );
508
509 if ( $type !== null ) {
510 return array( $target, $type );
511 }
512 }
513
514 return array( null, null );
515 }
516
517 /**
518 * HTMLForm field validation-callback for Target field.
519 * @since 1.18
520 * @param string $value
521 * @param array $alldata
522 * @param HTMLForm $form
523 * @return Message
524 */
525 public static function validateTargetField( $value, $alldata, $form ) {
526 $status = self::validateTarget( $value, $form->getUser() );
527 if ( !$status->isOK() ) {
528 $errors = $status->getErrorsArray();
529
530 return call_user_func_array( array( $form, 'msg' ), $errors[0] );
531 } else {
532 return true;
533 }
534 }
535
536 /**
537 * Validate a block target.
538 *
539 * @since 1.21
540 * @param string $value Block target to check
541 * @param User $user Performer of the block
542 * @return Status
543 */
544 public static function validateTarget( $value, User $user ) {
545 global $wgBlockCIDRLimit;
546
547 /** @var User $target */
548 list( $target, $type ) = self::getTargetAndType( $value );
549 $status = Status::newGood( $target );
550
551 if ( $type == Block::TYPE_USER ) {
552 if ( $target->isAnon() ) {
553 $status->fatal(
554 'nosuchusershort',
555 wfEscapeWikiText( $target->getName() )
556 );
557 }
558
559 $unblockStatus = self::checkUnblockSelf( $target, $user );
560 if ( $unblockStatus !== true ) {
561 $status->fatal( 'badaccess', $unblockStatus );
562 }
563 } elseif ( $type == Block::TYPE_RANGE ) {
564 list( $ip, $range ) = explode( '/', $target, 2 );
565
566 if (
567 ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
568 ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
569 ) {
570 // Range block effectively disabled
571 $status->fatal( 'range_block_disabled' );
572 }
573
574 if (
575 ( IP::isIPv4( $ip ) && $range > 32 ) ||
576 ( IP::isIPv6( $ip ) && $range > 128 )
577 ) {
578 // Dodgy range
579 $status->fatal( 'ip_range_invalid' );
580 }
581
582 if ( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
583 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
584 }
585
586 if ( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
587 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
588 }
589 } elseif ( $type == Block::TYPE_IP ) {
590 # All is well
591 } else {
592 $status->fatal( 'badipaddress' );
593 }
594
595 return $status;
596 }
597
598 /**
599 * Given the form data, actually implement a block. This is also called from ApiBlock.
600 *
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 hideuser and block rights, loads block form,
666 # and loses hideuser rights 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 ( !wfIsInfinity( $data['Expiry'] ) ) {
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['5::duration'] = $data['Expiry'];
788 $logParams['6::flags'] = self::blockLogFlags( $data, $type );
789
790 # Make log entry, if the name is hidden, put it in the suppression log
791 $log_type = $data['HideUser'] ? 'suppress' : 'block';
792 $logEntry = new ManualLogEntry( $log_type, $logaction );
793 $logEntry->setTarget( Title::makeTitle( NS_USER, $target ) );
794 $logEntry->setComment( $data['Reason'][0] );
795 $logEntry->setPerformer( $performer );
796 $logEntry->setParameters( $logParams );
797 # Relate log ID to block IDs (bug 25763)
798 $blockIds = array_merge( array( $status['id'] ), $status['autoIds'] );
799 $logEntry->setRelations( array( 'ipb_id' => $blockIds ) );
800 $logId = $logEntry->insert();
801 $logEntry->publish( $logId );
802
803 # Report to the user
804 return true;
805 }
806
807 /**
808 * Get an array of suggested block durations from MediaWiki:Ipboptions
809 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
810 * to the standard "**<duration>|<displayname>" format?
811 * @param Language|null $lang The language to get the durations in, or null to use
812 * the wiki's content language
813 * @return array
814 */
815 public static function getSuggestedDurations( $lang = null ) {
816 $a = array();
817 $msg = $lang === null
818 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
819 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
820
821 if ( $msg == '-' ) {
822 return array();
823 }
824
825 foreach ( explode( ',', $msg ) as $option ) {
826 if ( strpos( $option, ':' ) === false ) {
827 $option = "$option:$option";
828 }
829
830 list( $show, $value ) = explode( ':', $option );
831 $a[$show] = $value;
832 }
833
834 return $a;
835 }
836
837 /**
838 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
839 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
840 * @param string $expiry Whatever was typed into the form
841 * @return string Timestamp or 'infinity'
842 */
843 public static function parseExpiryInput( $expiry ) {
844 if ( wfIsInfinity( $expiry ) ) {
845 $expiry = 'infinity';
846 } else {
847 $expiry = strtotime( $expiry );
848
849 if ( $expiry < 0 || $expiry === false ) {
850 return false;
851 }
852
853 $expiry = wfTimestamp( TS_MW, $expiry );
854 }
855
856 return $expiry;
857 }
858
859 /**
860 * Can we do an email block?
861 * @param User $user The sysop wanting to make a block
862 * @return bool
863 */
864 public static function canBlockEmail( $user ) {
865 global $wgEnableUserEmail, $wgSysopEmailBans;
866
867 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
868 }
869
870 /**
871 * bug 15810: blocked admins should not be able to block/unblock
872 * others, and probably shouldn't be able to unblock themselves
873 * either.
874 * @param User|int|string $user
875 * @param User $performer User doing the request
876 * @return bool|string True or error message key
877 */
878 public static function checkUnblockSelf( $user, User $performer ) {
879 if ( is_int( $user ) ) {
880 $user = User::newFromId( $user );
881 } elseif ( is_string( $user ) ) {
882 $user = User::newFromName( $user );
883 }
884
885 if ( $performer->isBlocked() ) {
886 if ( $user instanceof User && $user->getId() == $performer->getId() ) {
887 # User is trying to unblock themselves
888 if ( $performer->isAllowed( 'unblockself' ) ) {
889 return true;
890 # User blocked themselves and is now trying to reverse it
891 } elseif ( $performer->blockedBy() === $performer->getName() ) {
892 return true;
893 } else {
894 return 'ipbnounblockself';
895 }
896 } else {
897 # User is trying to block/unblock someone else
898 return 'ipbblocked';
899 }
900 } else {
901 return true;
902 }
903 }
904
905 /**
906 * Return a comma-delimited list of "flags" to be passed to the log
907 * reader for this block, to provide more information in the logs
908 * @param array $data From HTMLForm data
909 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
910 * @return string
911 */
912 protected static function blockLogFlags( array $data, $type ) {
913 global $wgBlockAllowsUTEdit;
914 $flags = array();
915
916 # when blocking a user the option 'anononly' is not available/has no effect
917 # -> do not write this into log
918 if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
919 // For grepping: message block-log-flags-anononly
920 $flags[] = 'anononly';
921 }
922
923 if ( $data['CreateAccount'] ) {
924 // For grepping: message block-log-flags-nocreate
925 $flags[] = 'nocreate';
926 }
927
928 # Same as anononly, this is not displayed when blocking an IP address
929 if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
930 // For grepping: message block-log-flags-noautoblock
931 $flags[] = 'noautoblock';
932 }
933
934 if ( $data['DisableEmail'] ) {
935 // For grepping: message block-log-flags-noemail
936 $flags[] = 'noemail';
937 }
938
939 if ( $wgBlockAllowsUTEdit && $data['DisableUTEdit'] ) {
940 // For grepping: message block-log-flags-nousertalk
941 $flags[] = 'nousertalk';
942 }
943
944 if ( $data['HideUser'] ) {
945 // For grepping: message block-log-flags-hiddenname
946 $flags[] = 'hiddenname';
947 }
948
949 return implode( ',', $flags );
950 }
951
952 /**
953 * Process the form on POST submission.
954 * @param array $data
955 * @param HTMLForm $form
956 * @return bool|array True for success, false for didn't-try, array of errors on failure
957 */
958 public function onSubmit( array $data, HTMLForm $form = null ) {
959 return self::processForm( $data, $form->getContext() );
960 }
961
962 /**
963 * Do something exciting on successful processing of the form, most likely to show a
964 * confirmation message
965 */
966 public function onSuccess() {
967 $out = $this->getOutput();
968 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
969 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
970 }
971
972 protected function getGroupName() {
973 return 'users';
974 }
975 }