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