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