merge latest master.
[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 /** The maximum number of edits a user can have and still be hidden
32 * TODO: config setting? */
33 const HIDEUSER_CONTRIBLIMIT = 1000;
34
35 /** @var User user to be blocked, as passed either by parameter (url?wpTarget=Foo)
36 * or as subpage (Special:Block/Foo) */
37 protected $target;
38
39 /// @var Block::TYPE_ constant
40 protected $type;
41
42 /// @var User|String the previous block target
43 protected $previousTarget;
44
45 /// @var Bool whether the previous submission of the form asked for HideUser
46 protected $requestedHideUser;
47
48 /// @var Bool
49 protected $alreadyBlocked;
50
51 /// @var Array
52 protected $preErrors = array();
53
54 public function __construct() {
55 parent::__construct( 'Block', 'block' );
56 }
57
58 /**
59 * Checks that the user can unblock themselves if they are trying to do so
60 *
61 * @param User $user
62 * @throws ErrorPageError
63 */
64 protected function checkExecutePermissions( User $user ) {
65 parent::checkExecutePermissions( $user );
66
67 # bug 15810: blocked admins should have limited access here
68 $status = self::checkUnblockSelf( $this->target, $user );
69 if ( $status !== true ) {
70 throw new ErrorPageError( 'badaccess', $status );
71 }
72 }
73
74 /**
75 * Handle some magic here
76 *
77 * @param $par String
78 */
79 protected function setParameter( $par ) {
80 # Extract variables from the request. Try not to get into a situation where we
81 # need to extract *every* variable from the form just for processing here, but
82 # there are legitimate uses for some variables
83 $request = $this->getRequest();
84 list( $this->target, $this->type ) = self::getTargetAndType( $par, $request );
85 if ( $this->target instanceof User ) {
86 # Set the 'relevant user' in the skin, so it displays links like Contributions,
87 # User logs, UserRights, etc.
88 $this->getSkin()->setRelevantUser( $this->target );
89 }
90
91 list( $this->previousTarget, /*...*/ ) = Block::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
92 $this->requestedHideUser = $request->getBool( 'wpHideUser' );
93 }
94
95 /**
96 * Customizes the HTMLForm a bit
97 *
98 * @param $form HTMLForm
99 */
100 protected function alterForm( HTMLForm $form ) {
101 $form->setWrapperLegendMsg( 'blockip-legend' );
102 $form->setHeaderText( '' );
103 $form->setSubmitCallback( array( __CLASS__, 'processUIForm' ) );
104
105 $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
106 $form->setSubmitTextMsg( $msg );
107
108 # Don't need to do anything if the form has been posted
109 if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
110 $s = HTMLForm::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 $a = array(
131 'Target' => array(
132 'type' => 'text',
133 'label-message' => 'ipadressorusername',
134 'tabindex' => '1',
135 'id' => 'mw-bi-target',
136 'size' => '45',
137 'required' => true,
138 'validation-callback' => array( __CLASS__, 'validateTargetField' ),
139 ),
140 'Expiry' => array(
141 'type' => !count( self::getSuggestedDurations() ) ? 'text' : 'selectorother',
142 'label-message' => 'ipbexpiry',
143 'required' => true,
144 'tabindex' => '2',
145 'options' => self::getSuggestedDurations(),
146 'other' => $this->msg( 'ipbother' )->text(),
147 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
148 ),
149 'Reason' => array(
150 'type' => 'selectandother',
151 'label-message' => 'ipbreason',
152 'options-message' => 'ipbreason-dropdown',
153 ),
154 'CreateAccount' => array(
155 'type' => 'check',
156 'label-message' => 'ipbcreateaccount',
157 'default' => true,
158 ),
159 );
160
161 if ( self::canBlockEmail( $user ) ) {
162 $a['DisableEmail'] = array(
163 'type' => 'check',
164 'label-message' => 'ipbemailban',
165 );
166 }
167
168 if ( $wgBlockAllowsUTEdit ) {
169 $a['DisableUTEdit'] = array(
170 'type' => 'check',
171 'label-message' => 'ipb-disableusertalk',
172 'default' => false,
173 );
174 }
175
176 $a['AutoBlock'] = array(
177 'type' => 'check',
178 'label-message' => 'ipbenableautoblock',
179 'default' => true,
180 );
181
182 # Allow some users to hide name from block log, blocklist and listusers
183 if ( $user->isAllowed( 'hideuser' ) ) {
184 $a['HideUser'] = array(
185 'type' => 'check',
186 'label-message' => 'ipbhidename',
187 'cssclass' => 'mw-block-hideuser',
188 );
189 }
190
191 # Watchlist their user page? (Only if user is logged in)
192 if ( $user->isLoggedIn() ) {
193 $a['Watch'] = array(
194 'type' => 'check',
195 'label-message' => 'ipbwatchuser',
196 );
197 }
198
199 $a['HardBlock'] = array(
200 'type' => 'check',
201 'label-message' => 'ipb-hardblock',
202 'default' => false,
203 );
204
205 # This is basically a copy of the Target field, but the user can't change it, so we
206 # can see if the warnings we maybe showed to the user before still apply
207 $a['PreviousTarget'] = array(
208 'type' => 'hidden',
209 'default' => false,
210 );
211
212 # We'll turn this into a checkbox if we need to
213 $a['Confirm'] = array(
214 'type' => 'hidden',
215 'default' => '',
216 'label-message' => 'ipb-confirm',
217 );
218
219 $this->maybeAlterFormDefaults( $a );
220
221 return $a;
222 }
223
224 /**
225 * If the user has already been blocked with similar settings, load that block
226 * and change the defaults for the form fields to match the existing settings.
227 * @param $fields Array HTMLForm descriptor array
228 * @return Bool whether fields were altered (that is, whether the target is
229 * already blocked)
230 */
231 protected function maybeAlterFormDefaults( &$fields ) {
232 # This will be overwritten by request data
233 $fields['Target']['default'] = (string)$this->target;
234
235 # This won't be
236 $fields['PreviousTarget']['default'] = (string)$this->target;
237
238 $block = Block::newFromTarget( $this->target );
239
240 if ( $block instanceof Block && !$block->mAuto # The block exists and isn't an autoblock
241 && ( $this->type != Block::TYPE_RANGE # The block isn't a rangeblock
242 || $block->getTarget() == $this->target ) # or if it is, the range is what we're about to block
243 )
244 {
245 $fields['HardBlock']['default'] = $block->isHardblock();
246 $fields['CreateAccount']['default'] = $block->prevents( 'createaccount' );
247 $fields['AutoBlock']['default'] = $block->isAutoblocking();
248
249 if ( isset( $fields['DisableEmail'] ) ) {
250 $fields['DisableEmail']['default'] = $block->prevents( 'sendemail' );
251 }
252
253 if ( isset( $fields['HideUser'] ) ) {
254 $fields['HideUser']['default'] = $block->mHideName;
255 }
256
257 if ( isset( $fields['DisableUTEdit'] ) ) {
258 $fields['DisableUTEdit']['default'] = $block->prevents( 'editownusertalk' );
259 }
260
261 // If the username was hidden (ipb_deleted == 1), don't show the reason
262 // unless this user also has rights to hideuser: Bug 35839
263 if ( !$block->mHideName || $this->getUser()->isAllowed( 'hideuser' ) ) {
264 $fields['Reason']['default'] = $block->mReason;
265 } else {
266 $fields['Reason']['default'] = '';
267 }
268
269 if ( $this->getRequest()->wasPosted() ) {
270 # Ok, so we got a POST submission asking us to reblock a user. So show the
271 # confirm checkbox; the user will only see it if they haven't previously
272 $fields['Confirm']['type'] = 'check';
273 } else {
274 # We got a target, but it wasn't a POST request, so the user must have gone
275 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
276 # as long as they go ahead and block *that* user
277 $fields['Confirm']['default'] = 1;
278 }
279
280 if ( $block->mExpiry == 'infinity' ) {
281 $fields['Expiry']['default'] = 'infinite';
282 } else {
283 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->mExpiry );
284 }
285
286 $this->alreadyBlocked = true;
287 $this->preErrors[] = array( 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) );
288 }
289
290 # We always need confirmation to do HideUser
291 if ( $this->requestedHideUser ) {
292 $fields['Confirm']['type'] = 'check';
293 unset( $fields['Confirm']['default'] );
294 $this->preErrors[] = 'ipb-confirmhideuser';
295 }
296
297 # Or if the user is trying to block themselves
298 if ( (string)$this->target === $this->getUser()->getName() ) {
299 $fields['Confirm']['type'] = 'check';
300 unset( $fields['Confirm']['default'] );
301 $this->preErrors[] = 'ipb-blockingself';
302 }
303 }
304
305 /**
306 * Add header elements like block log entries, etc.
307 * @return String
308 */
309 protected function preText() {
310 $this->getOutput()->addModules( 'mediawiki.special.block' );
311
312 $text = $this->msg( 'blockiptext' )->parse();
313
314 $otherBlockMessages = array();
315 if ( $this->target !== null ) {
316 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
317 wfRunHooks( 'OtherBlockLogLink', array( &$otherBlockMessages, $this->target ) );
318
319 if ( count( $otherBlockMessages ) ) {
320 $s = Html::rawElement(
321 'h2',
322 array(),
323 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
324 ) . "\n";
325
326 $list = '';
327
328 foreach ( $otherBlockMessages as $link ) {
329 $list .= Html::rawElement( 'li', array(), $link ) . "\n";
330 }
331
332 $s .= Html::rawElement(
333 'ul',
334 array( 'class' => 'mw-blockip-alreadyblocked' ),
335 $list
336 ) . "\n";
337
338 $text .= $s;
339 }
340 }
341
342 return $text;
343 }
344
345 /**
346 * Add footer elements to the form
347 * @return string
348 */
349 protected function postText() {
350 $links = array();
351
352 # Link to the user's contributions, if applicable
353 if ( $this->target instanceof User ) {
354 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
355 $links[] = Linker::link(
356 $contribsPage,
357 $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->escaped()
358 );
359 }
360
361 # Link to unblock the specified user, or to a blank unblock form
362 if ( $this->target instanceof User ) {
363 $message = $this->msg( 'ipb-unblock-addr', wfEscapeWikiText( $this->target->getName() ) )->parse();
364 $list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
365 } else {
366 $message = $this->msg( 'ipb-unblock' )->parse();
367 $list = SpecialPage::getTitleFor( 'Unblock' );
368 }
369 $links[] = Linker::linkKnown( $list, $message, array() );
370
371 # Link to the block list
372 $links[] = Linker::linkKnown(
373 SpecialPage::getTitleFor( 'BlockList' ),
374 $this->msg( 'ipb-blocklist' )->escaped()
375 );
376
377 $user = $this->getUser();
378
379 # Link to edit the block dropdown reasons, if applicable
380 if ( $user->isAllowed( 'editinterface' ) ) {
381 $links[] = Linker::link(
382 Title::makeTitle( NS_MEDIAWIKI, 'Ipbreason-dropdown' ),
383 $this->msg( 'ipb-edit-dropdown' )->escaped(),
384 array(),
385 array( 'action' => 'edit' )
386 );
387 }
388
389 $text = Html::rawElement(
390 'p',
391 array( 'class' => 'mw-ipb-conveniencelinks' ),
392 $this->getLanguage()->pipeList( $links )
393 );
394
395 $userTitle = self::getTargetUserTitle( $this->target );
396 if ( $userTitle ) {
397 # Get relevant extracts from the block and suppression logs, if possible
398 $out = '';
399
400 LogEventsList::showLogExtract(
401 $out,
402 'block',
403 $userTitle,
404 '',
405 array(
406 'lim' => 10,
407 'msgKey' => array( 'blocklog-showlog', $userTitle->getText() ),
408 'showIfEmpty' => false
409 )
410 );
411 $text .= $out;
412
413 # Add suppression block entries if allowed
414 if ( $user->isAllowed( 'suppressionlog' ) ) {
415 LogEventsList::showLogExtract(
416 $out,
417 'suppress',
418 $userTitle,
419 '',
420 array(
421 'lim' => 10,
422 'conds' => array( 'log_action' => array( 'block', 'reblock', 'unblock' ) ),
423 'msgKey' => array( 'blocklog-showsuppresslog', $userTitle->getText() ),
424 'showIfEmpty' => false
425 )
426 );
427
428 $text .= $out;
429 }
430 }
431
432 return $text;
433 }
434
435 /**
436 * Get a user page target for things like logs.
437 * This handles account and IP range targets.
438 * @param $target User|string
439 * @return Title|null
440 */
441 protected static function getTargetUserTitle( $target ) {
442 if ( $target instanceof User ) {
443 return $target->getUserPage();
444 } elseif ( IP::isIPAddress( $target ) ) {
445 return Title::makeTitleSafe( NS_USER, $target );
446 }
447 return null;
448 }
449
450 /**
451 * Determine the target of the block, and the type of target
452 * TODO: should be in Block.php?
453 * @param $par String subpage parameter passed to setup, or data value from
454 * the HTMLForm
455 * @param $request WebRequest optionally try and get data from a request too
456 * @return array( User|string|null, Block::TYPE_ constant|null )
457 */
458 public static function getTargetAndType( $par, WebRequest $request = null ) {
459 $i = 0;
460 $target = null;
461
462 while( true ) {
463 switch( $i++ ) {
464 case 0:
465 # The HTMLForm will check wpTarget first and only if it doesn't get
466 # a value use the default, which will be generated from the options
467 # below; so this has to have a higher precedence here than $par, or
468 # we could end up with different values in $this->target and the HTMLForm!
469 if ( $request instanceof WebRequest ) {
470 $target = $request->getText( 'wpTarget', null );
471 }
472 break;
473 case 1:
474 $target = $par;
475 break;
476 case 2:
477 if ( $request instanceof WebRequest ) {
478 $target = $request->getText( 'ip', null );
479 }
480 break;
481 case 3:
482 # B/C @since 1.18
483 if ( $request instanceof WebRequest ) {
484 $target = $request->getText( 'wpBlockAddress', null );
485 }
486 break;
487 case 4:
488 break 2;
489 }
490
491 list( $target, $type ) = Block::parseTarget( $target );
492
493 if ( $type !== null ) {
494 return array( $target, $type );
495 }
496 }
497
498 return array( null, null );
499 }
500
501 /**
502 * HTMLForm field validation-callback for Target field.
503 * @since 1.18
504 * @param $value String
505 * @param $alldata Array
506 * @param $form HTMLForm
507 * @return Message
508 */
509 public static function validateTargetField( $value, $alldata, $form ) {
510 global $wgBlockCIDRLimit;
511
512 list( $target, $type ) = self::getTargetAndType( $value );
513
514 if ( $type == Block::TYPE_USER ) {
515 # TODO: why do we not have a User->exists() method?
516 if ( !$target->getId() ) {
517 return $form->msg( 'nosuchusershort',
518 wfEscapeWikiText( $target->getName() ) );
519 }
520
521 $status = self::checkUnblockSelf( $target, $form->getUser() );
522 if ( $status !== true ) {
523 return $form->msg( 'badaccess', $status );
524 }
525
526 } elseif ( $type == Block::TYPE_RANGE ) {
527 list( $ip, $range ) = explode( '/', $target, 2 );
528
529 if ( ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 )
530 || ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 ) )
531 {
532 # Range block effectively disabled
533 return $form->msg( 'range_block_disabled' );
534 }
535
536 if ( ( IP::isIPv4( $ip ) && $range > 32 )
537 || ( IP::isIPv6( $ip ) && $range > 128 ) )
538 {
539 # Dodgy range
540 return $form->msg( 'ip_range_invalid' );
541 }
542
543 if ( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
544 return $form->msg( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
545 }
546
547 if ( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
548 return $form->msg( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
549 }
550 } elseif ( $type == Block::TYPE_IP ) {
551 # All is well
552 } else {
553 return $form->msg( 'badipaddress' );
554 }
555
556 return true;
557 }
558
559 /**
560 * Submit callback for an HTMLForm object, will simply pass
561 * @param $data array
562 * @param $form HTMLForm
563 * @return Bool|String
564 */
565 public static function processUIForm( array $data, HTMLForm $form ) {
566 return self::processForm( $data, $form->getContext() );
567 }
568
569 /**
570 * Given the form data, actually implement a block
571 * @param $data Array
572 * @param $context IContextSource
573 * @return Bool|String
574 */
575 public static function processForm( array $data, IContextSource $context ) {
576 global $wgBlockAllowsUTEdit;
577
578 $performer = $context->getUser();
579
580 // Handled by field validator callback
581 // self::validateTargetField( $data['Target'] );
582
583 # This might have been a hidden field or a checkbox, so interesting data
584 # can come from it
585 $data['Confirm'] = !in_array( $data['Confirm'], array( '', '0', null, false ), true );
586
587 list( $target, $type ) = self::getTargetAndType( $data['Target'] );
588 if ( $type == Block::TYPE_USER ) {
589 $user = $target;
590 $target = $user->getName();
591 $userId = $user->getId();
592
593 # Give admins a heads-up before they go and block themselves. Much messier
594 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
595 # permission anyway, although the code does allow for it.
596 # Note: Important to use $target instead of $data['Target']
597 # since both $data['PreviousTarget'] and $target are normalized
598 # but $data['target'] gets overriden by (non-normalized) request variable
599 # from previous request.
600 if ( $target === $performer->getName() &&
601 ( $data['PreviousTarget'] !== $target || !$data['Confirm'] ) )
602 {
603 return array( 'ipb-blockingself' );
604 }
605 } elseif ( $type == Block::TYPE_RANGE ) {
606 $userId = 0;
607 } elseif ( $type == Block::TYPE_IP ) {
608 $target = $target->getName();
609 $userId = 0;
610 } else {
611 # This should have been caught in the form field validation
612 return array( 'badipaddress' );
613 }
614
615 if ( ( strlen( $data['Expiry'] ) == 0) || ( strlen( $data['Expiry'] ) > 50 )
616 || !self::parseExpiryInput( $data['Expiry'] ) )
617 {
618 return array( 'ipb_expiry_invalid' );
619 }
620
621 if ( !isset( $data['DisableEmail'] ) ) {
622 $data['DisableEmail'] = false;
623 }
624
625 # If the user has done the form 'properly', they won't even have been given the
626 # option to suppress-block unless they have the 'hideuser' permission
627 if ( !isset( $data['HideUser'] ) ) {
628 $data['HideUser'] = false;
629 }
630
631 if ( $data['HideUser'] ) {
632 if ( !$performer->isAllowed('hideuser') ) {
633 # this codepath is unreachable except by a malicious user spoofing forms,
634 # or by race conditions (user has oversight and sysop, loads block form,
635 # and is de-oversighted before submission); so need to fail completely
636 # rather than just silently disable hiding
637 return array( 'badaccess-group0' );
638 }
639
640 # Recheck params here...
641 if ( $type != Block::TYPE_USER ) {
642 $data['HideUser'] = false; # IP users should not be hidden
643 } elseif ( !in_array( $data['Expiry'], array( 'infinite', 'infinity', 'indefinite' ) ) ) {
644 # Bad expiry.
645 return array( 'ipb_expiry_temp' );
646 } elseif ( $user->getEditCount() > self::HIDEUSER_CONTRIBLIMIT ) {
647 # Typically, the user should have a handful of edits.
648 # Disallow hiding users with many edits for performance.
649 return array( 'ipb_hide_invalid' );
650 } elseif ( !$data['Confirm'] ) {
651 return array( 'ipb-confirmhideuser' );
652 }
653 }
654
655 # Create block object.
656 $block = new Block();
657 $block->setTarget( $target );
658 $block->setBlocker( $performer );
659 $block->mReason = $data['Reason'][0];
660 $block->mExpiry = self::parseExpiryInput( $data['Expiry'] );
661 $block->prevents( 'createaccount', $data['CreateAccount'] );
662 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit || $data['DisableUTEdit'] ) );
663 $block->prevents( 'sendemail', $data['DisableEmail'] );
664 $block->isHardblock( $data['HardBlock'] );
665 $block->isAutoblocking( $data['AutoBlock'] );
666 $block->mHideName = $data['HideUser'];
667
668 if ( !wfRunHooks( 'BlockIp', array( &$block, &$performer ) ) ) {
669 return array( 'hookaborted' );
670 }
671
672 # Try to insert block. Is there a conflicting block?
673 $status = $block->insert();
674 if ( !$status ) {
675 # Show form unless the user is already aware of this...
676 if ( !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
677 && $data['PreviousTarget'] !== $target ) )
678 {
679 return array( array( 'ipb_already_blocked', $block->getTarget() ) );
680 # Otherwise, try to update the block...
681 } else {
682 # This returns direct blocks before autoblocks/rangeblocks, since we should
683 # be sure the user is blocked by now it should work for our purposes
684 $currentBlock = Block::newFromTarget( $target );
685
686 if ( $block->equals( $currentBlock ) ) {
687 return array( array( 'ipb_already_blocked', $block->getTarget() ) );
688 }
689
690 # If the name was hidden and the blocking user cannot hide
691 # names, then don't allow any block changes...
692 if ( $currentBlock->mHideName && !$performer->isAllowed( 'hideuser' ) ) {
693 return array( 'cant-see-hidden-user' );
694 }
695
696 $currentBlock->delete();
697 $status = $block->insert();
698 $logaction = 'reblock';
699
700 # Unset _deleted fields if requested
701 if ( $currentBlock->mHideName && !$data['HideUser'] ) {
702 RevisionDeleteUser::unsuppressUserName( $target, $userId );
703 }
704
705 # If hiding/unhiding a name, this should go in the private logs
706 if ( (bool)$currentBlock->mHideName ) {
707 $data['HideUser'] = true;
708 }
709 }
710 } else {
711 $logaction = 'block';
712 }
713
714 wfRunHooks( 'BlockIpComplete', array( $block, $performer ) );
715
716 # Set *_deleted fields if requested
717 if ( $data['HideUser'] ) {
718 RevisionDeleteUser::suppressUserName( $target, $userId );
719 }
720
721 # Can't watch a rangeblock
722 if ( $type != Block::TYPE_RANGE && $data['Watch'] ) {
723 $performer->addWatch( Title::makeTitle( NS_USER, $target ) );
724 }
725
726 # Block constructor sanitizes certain block options on insert
727 $data['BlockEmail'] = $block->prevents( 'sendemail' );
728 $data['AutoBlock'] = $block->isAutoblocking();
729
730 # Prepare log parameters
731 $logParams = array();
732 $logParams[] = $data['Expiry'];
733 $logParams[] = self::blockLogFlags( $data, $type );
734
735 # Make log entry, if the name is hidden, put it in the oversight log
736 $log_type = $data['HideUser'] ? 'suppress' : 'block';
737 $log = new LogPage( $log_type );
738 $log_id = $log->addEntry(
739 $logaction,
740 Title::makeTitle( NS_USER, $target ),
741 $data['Reason'][0],
742 $logParams
743 );
744 # Relate log ID to block IDs (bug 25763)
745 $blockIds = array_merge( array( $status['id'] ), $status['autoIds'] );
746 $log->addRelations( 'ipb_id', $blockIds, $log_id );
747
748 # Report to the user
749 return true;
750 }
751
752 /**
753 * Get an array of suggested block durations from MediaWiki:Ipboptions
754 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
755 * to the standard "**<duration>|<displayname>" format?
756 * @param $lang Language|null the language to get the durations in, or null to use
757 * the wiki's content language
758 * @return Array
759 */
760 public static function getSuggestedDurations( $lang = null ) {
761 $a = array();
762 $msg = $lang === null
763 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
764 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
765
766 if ( $msg == '-' ) {
767 return array();
768 }
769
770 foreach ( explode( ',', $msg ) as $option ) {
771 if ( strpos( $option, ':' ) === false ) {
772 $option = "$option:$option";
773 }
774
775 list( $show, $value ) = explode( ':', $option );
776 $a[htmlspecialchars( $show )] = htmlspecialchars( $value );
777 }
778
779 return $a;
780 }
781
782 /**
783 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
784 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
785 * @param $expiry String: whatever was typed into the form
786 * @return String: timestamp or "infinity" string for the DB implementation
787 */
788 public static function parseExpiryInput( $expiry ) {
789 static $infinity;
790 if ( $infinity == null ) {
791 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
792 }
793
794 if ( $expiry == 'infinite' || $expiry == 'indefinite' ) {
795 $expiry = $infinity;
796 } else {
797 $expiry = strtotime( $expiry );
798
799 if ( $expiry < 0 || $expiry === false ) {
800 return false;
801 }
802
803 $expiry = wfTimestamp( TS_MW, $expiry );
804 }
805
806 return $expiry;
807 }
808
809 /**
810 * Can we do an email block?
811 * @param $user User: the sysop wanting to make a block
812 * @return Boolean
813 */
814 public static function canBlockEmail( $user ) {
815 global $wgEnableUserEmail, $wgSysopEmailBans;
816
817 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
818 }
819
820 /**
821 * bug 15810: blocked admins should not be able to block/unblock
822 * others, and probably shouldn't be able to unblock themselves
823 * either.
824 * @param $user User|Int|String
825 * @param $performer User user doing the request
826 * @return Bool|String true or error message key
827 */
828 public static function checkUnblockSelf( $user, User $performer ) {
829 if ( is_int( $user ) ) {
830 $user = User::newFromId( $user );
831 } elseif ( is_string( $user ) ) {
832 $user = User::newFromName( $user );
833 }
834
835 if ( $performer->isBlocked() ) {
836 if ( $user instanceof User && $user->getId() == $performer->getId() ) {
837 # User is trying to unblock themselves
838 if ( $performer->isAllowed( 'unblockself' ) ) {
839 return true;
840 # User blocked themselves and is now trying to reverse it
841 } elseif ( $performer->blockedBy() === $performer->getName() ) {
842 return true;
843 } else {
844 return 'ipbnounblockself';
845 }
846 } else {
847 # User is trying to block/unblock someone else
848 return 'ipbblocked';
849 }
850 } else {
851 return true;
852 }
853 }
854
855 /**
856 * Return a comma-delimited list of "flags" to be passed to the log
857 * reader for this block, to provide more information in the logs
858 * @param $data Array from HTMLForm data
859 * @param $type Block::TYPE_ constant (USER, RANGE, or IP)
860 * @return string
861 */
862 protected static function blockLogFlags( array $data, $type ) {
863 global $wgBlockAllowsUTEdit;
864 $flags = array();
865
866 # when blocking a user the option 'anononly' is not available/has no effect
867 # -> do not write this into log
868 if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
869 // For grepping: message block-log-flags-anononly
870 $flags[] = 'anononly';
871 }
872
873 if ( $data['CreateAccount'] ) {
874 // For grepping: message block-log-flags-nocreate
875 $flags[] = 'nocreate';
876 }
877
878 # Same as anononly, this is not displayed when blocking an IP address
879 if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
880 // For grepping: message block-log-flags-noautoblock
881 $flags[] = 'noautoblock';
882 }
883
884 if ( $data['DisableEmail'] ) {
885 // For grepping: message block-log-flags-noemail
886 $flags[] = 'noemail';
887 }
888
889 if ( $wgBlockAllowsUTEdit && $data['DisableUTEdit'] ) {
890 // For grepping: message block-log-flags-nousertalk
891 $flags[] = 'nousertalk';
892 }
893
894 if ( $data['HideUser'] ) {
895 // For grepping: message block-log-flags-hiddenname
896 $flags[] = 'hiddenname';
897 }
898
899 return implode( ',', $flags );
900 }
901
902 /**
903 * Process the form on POST submission.
904 * @param $data Array
905 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
906 */
907 public function onSubmit( array $data ) {
908 // This isn't used since we need that HTMLForm that's passed in the
909 // second parameter. See alterForm for the real function
910 }
911
912 /**
913 * Do something exciting on successful processing of the form, most likely to show a
914 * confirmation message
915 */
916 public function onSuccess() {
917 $out = $this->getOutput();
918 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
919 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
920 }
921 }
922
923 # BC @since 1.18
924 class IPBlockForm extends SpecialBlock {}