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