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 '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 $status = self::validateTarget( $value, $form->getUser() );
511 if ( !$status->isOK() ) {
512 $errors = $status->getErrorsArray();
513 return call_user_func_array( array( $form, 'msg' ), $errors[0] );
514 } else {
515 return true;
516 }
517 }
518
519 /**
520 * Validate a block target.
521 *
522 * @since 1.21
523 * @param String $value Block target to check
524 * @param User $user Performer of the block
525 * @return Status
526 */
527 public static function validateTarget( $value, User $user ) {
528 global $wgBlockCIDRLimit;
529
530 list( $target, $type ) = self::getTargetAndType( $value );
531 $status = Status::newGood( $target );
532
533 if ( $type == Block::TYPE_USER ) {
534 if ( $target->isAnon() ) {
535 $status->fatal(
536 'nosuchusershort',
537 wfEscapeWikiText( $target->getName() )
538 );
539 }
540
541 $unblockStatus = self::checkUnblockSelf( $target, $user );
542 if ( $unblockStatus !== true ) {
543 $status->fatal( 'badaccess', $unblockStatus );
544 }
545 } elseif ( $type == Block::TYPE_RANGE ) {
546 list( $ip, $range ) = explode( '/', $target, 2 );
547
548 if (
549 ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
550 ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
551 ) {
552 // Range block effectively disabled
553 $status->fatal( 'range_block_disabled' );
554 }
555
556 if (
557 ( IP::isIPv4( $ip ) && $range > 32 ) ||
558 ( IP::isIPv6( $ip ) && $range > 128 )
559 ) {
560 // Dodgy range
561 $status->fatal( 'ip_range_invalid' );
562 }
563
564 if ( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
565 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
566 }
567
568 if ( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
569 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
570 }
571 } elseif ( $type == Block::TYPE_IP ) {
572 # All is well
573 } else {
574 $status->fatal( 'badipaddress' );
575 }
576
577 return $status;
578 }
579
580 /**
581 * Submit callback for an HTMLForm object, will simply pass
582 * @param $data array
583 * @param $form HTMLForm
584 * @return Bool|String
585 */
586 public static function processUIForm( array $data, HTMLForm $form ) {
587 return self::processForm( $data, $form->getContext() );
588 }
589
590 /**
591 * Given the form data, actually implement a block
592 * @param $data Array
593 * @param $context IContextSource
594 * @return Bool|String
595 */
596 public static function processForm( array $data, IContextSource $context ) {
597 global $wgBlockAllowsUTEdit;
598
599 $performer = $context->getUser();
600
601 // Handled by field validator callback
602 // self::validateTargetField( $data['Target'] );
603
604 # This might have been a hidden field or a checkbox, so interesting data
605 # can come from it
606 $data['Confirm'] = !in_array( $data['Confirm'], array( '', '0', null, false ), true );
607
608 list( $target, $type ) = self::getTargetAndType( $data['Target'] );
609 if ( $type == Block::TYPE_USER ) {
610 $user = $target;
611 $target = $user->getName();
612 $userId = $user->getId();
613
614 # Give admins a heads-up before they go and block themselves. Much messier
615 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
616 # permission anyway, although the code does allow for it.
617 # Note: Important to use $target instead of $data['Target']
618 # since both $data['PreviousTarget'] and $target are normalized
619 # but $data['target'] gets overriden by (non-normalized) request variable
620 # from previous request.
621 if ( $target === $performer->getName() &&
622 ( $data['PreviousTarget'] !== $target || !$data['Confirm'] ) )
623 {
624 return array( 'ipb-blockingself' );
625 }
626 } elseif ( $type == Block::TYPE_RANGE ) {
627 $userId = 0;
628 } elseif ( $type == Block::TYPE_IP ) {
629 $target = $target->getName();
630 $userId = 0;
631 } else {
632 # This should have been caught in the form field validation
633 return array( 'badipaddress' );
634 }
635
636 if ( ( strlen( $data['Expiry'] ) == 0) || ( strlen( $data['Expiry'] ) > 50 )
637 || !self::parseExpiryInput( $data['Expiry'] ) )
638 {
639 return array( 'ipb_expiry_invalid' );
640 }
641
642 if ( !isset( $data['DisableEmail'] ) ) {
643 $data['DisableEmail'] = false;
644 }
645
646 # If the user has done the form 'properly', they won't even have been given the
647 # option to suppress-block unless they have the 'hideuser' permission
648 if ( !isset( $data['HideUser'] ) ) {
649 $data['HideUser'] = false;
650 }
651
652 if ( $data['HideUser'] ) {
653 if ( !$performer->isAllowed( 'hideuser' ) ) {
654 # this codepath is unreachable except by a malicious user spoofing forms,
655 # or by race conditions (user has oversight and sysop, loads block form,
656 # and is de-oversighted before submission); so need to fail completely
657 # rather than just silently disable hiding
658 return array( 'badaccess-group0' );
659 }
660
661 # Recheck params here...
662 if ( $type != Block::TYPE_USER ) {
663 $data['HideUser'] = false; # IP users should not be hidden
664 } elseif ( !in_array( $data['Expiry'], array( 'infinite', 'infinity', 'indefinite' ) ) ) {
665 # Bad expiry.
666 return array( 'ipb_expiry_temp' );
667 } elseif ( $user->getEditCount() > self::HIDEUSER_CONTRIBLIMIT ) {
668 # Typically, the user should have a handful of edits.
669 # Disallow hiding users with many edits for performance.
670 return array( 'ipb_hide_invalid' );
671 } elseif ( !$data['Confirm'] ) {
672 return array( 'ipb-confirmhideuser' );
673 }
674 }
675
676 # Create block object.
677 $block = new Block();
678 $block->setTarget( $target );
679 $block->setBlocker( $performer );
680 $block->mReason = $data['Reason'][0];
681 $block->mExpiry = self::parseExpiryInput( $data['Expiry'] );
682 $block->prevents( 'createaccount', $data['CreateAccount'] );
683 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit || $data['DisableUTEdit'] ) );
684 $block->prevents( 'sendemail', $data['DisableEmail'] );
685 $block->isHardblock( $data['HardBlock'] );
686 $block->isAutoblocking( $data['AutoBlock'] );
687 $block->mHideName = $data['HideUser'];
688
689 if ( !wfRunHooks( 'BlockIp', array( &$block, &$performer ) ) ) {
690 return array( 'hookaborted' );
691 }
692
693 # Try to insert block. Is there a conflicting block?
694 $status = $block->insert();
695 if ( !$status ) {
696 # Indicates whether the user is confirming the block and is aware of
697 # the conflict (did not change the block target in the meantime)
698 $blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
699 && $data['PreviousTarget'] !== $target );
700
701 # Special case for API - bug 32434
702 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
703
704 # Show form unless the user is already aware of this...
705 if( $blockNotConfirmed || $reblockNotAllowed ) {
706 return array( array( 'ipb_already_blocked', $block->getTarget() ) );
707 # Otherwise, try to update the block...
708 } else {
709 # This returns direct blocks before autoblocks/rangeblocks, since we should
710 # be sure the user is blocked by now it should work for our purposes
711 $currentBlock = Block::newFromTarget( $target );
712
713 if ( $block->equals( $currentBlock ) ) {
714 return array( array( 'ipb_already_blocked', $block->getTarget() ) );
715 }
716
717 # If the name was hidden and the blocking user cannot hide
718 # names, then don't allow any block changes...
719 if ( $currentBlock->mHideName && !$performer->isAllowed( 'hideuser' ) ) {
720 return array( 'cant-see-hidden-user' );
721 }
722
723 $currentBlock->delete();
724 $status = $block->insert();
725 $logaction = 'reblock';
726
727 # Unset _deleted fields if requested
728 if ( $currentBlock->mHideName && !$data['HideUser'] ) {
729 RevisionDeleteUser::unsuppressUserName( $target, $userId );
730 }
731
732 # If hiding/unhiding a name, this should go in the private logs
733 if ( (bool)$currentBlock->mHideName ) {
734 $data['HideUser'] = true;
735 }
736 }
737 } else {
738 $logaction = 'block';
739 }
740
741 wfRunHooks( 'BlockIpComplete', array( $block, $performer ) );
742
743 # Set *_deleted fields if requested
744 if ( $data['HideUser'] ) {
745 RevisionDeleteUser::suppressUserName( $target, $userId );
746 }
747
748 # Can't watch a rangeblock
749 if ( $type != Block::TYPE_RANGE && $data['Watch'] ) {
750 $performer->addWatch( Title::makeTitle( NS_USER, $target ) );
751 }
752
753 # Block constructor sanitizes certain block options on insert
754 $data['BlockEmail'] = $block->prevents( 'sendemail' );
755 $data['AutoBlock'] = $block->isAutoblocking();
756
757 # Prepare log parameters
758 $logParams = array();
759 $logParams[] = $data['Expiry'];
760 $logParams[] = self::blockLogFlags( $data, $type );
761
762 # Make log entry, if the name is hidden, put it in the oversight log
763 $log_type = $data['HideUser'] ? 'suppress' : 'block';
764 $log = new LogPage( $log_type );
765 $log_id = $log->addEntry(
766 $logaction,
767 Title::makeTitle( NS_USER, $target ),
768 $data['Reason'][0],
769 $logParams
770 );
771 # Relate log ID to block IDs (bug 25763)
772 $blockIds = array_merge( array( $status['id'] ), $status['autoIds'] );
773 $log->addRelations( 'ipb_id', $blockIds, $log_id );
774
775 # Report to the user
776 return true;
777 }
778
779 /**
780 * Get an array of suggested block durations from MediaWiki:Ipboptions
781 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
782 * to the standard "**<duration>|<displayname>" format?
783 * @param $lang Language|null the language to get the durations in, or null to use
784 * the wiki's content language
785 * @return Array
786 */
787 public static function getSuggestedDurations( $lang = null ) {
788 $a = array();
789 $msg = $lang === null
790 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
791 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
792
793 if ( $msg == '-' ) {
794 return array();
795 }
796
797 foreach ( explode( ',', $msg ) as $option ) {
798 if ( strpos( $option, ':' ) === false ) {
799 $option = "$option:$option";
800 }
801
802 list( $show, $value ) = explode( ':', $option );
803 $a[htmlspecialchars( $show )] = htmlspecialchars( $value );
804 }
805
806 return $a;
807 }
808
809 /**
810 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
811 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
812 * @param $expiry String: whatever was typed into the form
813 * @return String: timestamp or "infinity" string for the DB implementation
814 */
815 public static function parseExpiryInput( $expiry ) {
816 static $infinity;
817 if ( $infinity == null ) {
818 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
819 }
820
821 if ( $expiry == 'infinite' || $expiry == 'indefinite' ) {
822 $expiry = $infinity;
823 } else {
824 $expiry = strtotime( $expiry );
825
826 if ( $expiry < 0 || $expiry === false ) {
827 return false;
828 }
829
830 $expiry = wfTimestamp( TS_MW, $expiry );
831 }
832
833 return $expiry;
834 }
835
836 /**
837 * Can we do an email block?
838 * @param $user User: the sysop wanting to make a block
839 * @return Boolean
840 */
841 public static function canBlockEmail( $user ) {
842 global $wgEnableUserEmail, $wgSysopEmailBans;
843
844 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
845 }
846
847 /**
848 * bug 15810: blocked admins should not be able to block/unblock
849 * others, and probably shouldn't be able to unblock themselves
850 * either.
851 * @param $user User|Int|String
852 * @param $performer User user doing the request
853 * @return Bool|String true or error message key
854 */
855 public static function checkUnblockSelf( $user, User $performer ) {
856 if ( is_int( $user ) ) {
857 $user = User::newFromId( $user );
858 } elseif ( is_string( $user ) ) {
859 $user = User::newFromName( $user );
860 }
861
862 if ( $performer->isBlocked() ) {
863 if ( $user instanceof User && $user->getId() == $performer->getId() ) {
864 # User is trying to unblock themselves
865 if ( $performer->isAllowed( 'unblockself' ) ) {
866 return true;
867 # User blocked themselves and is now trying to reverse it
868 } elseif ( $performer->blockedBy() === $performer->getName() ) {
869 return true;
870 } else {
871 return 'ipbnounblockself';
872 }
873 } else {
874 # User is trying to block/unblock someone else
875 return 'ipbblocked';
876 }
877 } else {
878 return true;
879 }
880 }
881
882 /**
883 * Return a comma-delimited list of "flags" to be passed to the log
884 * reader for this block, to provide more information in the logs
885 * @param $data Array from HTMLForm data
886 * @param $type Block::TYPE_ constant (USER, RANGE, or IP)
887 * @return string
888 */
889 protected static function blockLogFlags( array $data, $type ) {
890 global $wgBlockAllowsUTEdit;
891 $flags = array();
892
893 # when blocking a user the option 'anononly' is not available/has no effect
894 # -> do not write this into log
895 if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
896 // For grepping: message block-log-flags-anononly
897 $flags[] = 'anononly';
898 }
899
900 if ( $data['CreateAccount'] ) {
901 // For grepping: message block-log-flags-nocreate
902 $flags[] = 'nocreate';
903 }
904
905 # Same as anononly, this is not displayed when blocking an IP address
906 if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
907 // For grepping: message block-log-flags-noautoblock
908 $flags[] = 'noautoblock';
909 }
910
911 if ( $data['DisableEmail'] ) {
912 // For grepping: message block-log-flags-noemail
913 $flags[] = 'noemail';
914 }
915
916 if ( $wgBlockAllowsUTEdit && $data['DisableUTEdit'] ) {
917 // For grepping: message block-log-flags-nousertalk
918 $flags[] = 'nousertalk';
919 }
920
921 if ( $data['HideUser'] ) {
922 // For grepping: message block-log-flags-hiddenname
923 $flags[] = 'hiddenname';
924 }
925
926 return implode( ',', $flags );
927 }
928
929 /**
930 * Process the form on POST submission.
931 * @param $data Array
932 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
933 */
934 public function onSubmit( array $data ) {
935 // This isn't used since we need that HTMLForm that's passed in the
936 // second parameter. See alterForm for the real function
937 }
938
939 /**
940 * Do something exciting on successful processing of the form, most likely to show a
941 * confirmation message
942 */
943 public function onSuccess() {
944 $out = $this->getOutput();
945 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
946 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
947 }
948 }
949
950 # BC @since 1.18
951 class IPBlockForm extends SpecialBlock {}