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