Fix spacing after @param and friends in comments
[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 /** @var User user to be blocked, as passed either by parameter (url?wpTarget=Foo)
32 * or as subpage (Special:Block/Foo) */
33 protected $target;
34
35 /// @var Block::TYPE_ constant
36 protected $type;
37
38 /// @var User|String the previous block target
39 protected $previousTarget;
40
41 /// @var Bool whether the previous submission of the form asked for HideUser
42 protected $requestedHideUser;
43
44 /// @var Bool
45 protected $alreadyBlocked;
46
47 /// @var Array
48 protected $preErrors = array();
49
50 public function __construct() {
51 parent::__construct( 'Block', 'block' );
52 }
53
54 /**
55 * Checks that the user can unblock themselves if they are trying to do so
56 *
57 * @param User $user
58 * @throws ErrorPageError
59 */
60 protected function checkExecutePermissions( User $user ) {
61 parent::checkExecutePermissions( $user );
62
63 # bug 15810: blocked admins should have limited access here
64 $status = self::checkUnblockSelf( $this->target, $user );
65 if ( $status !== true ) {
66 throw new ErrorPageError( 'badaccess', $status );
67 }
68 }
69
70 /**
71 * Handle some magic here
72 *
73 * @param $par String
74 */
75 protected function setParameter( $par ) {
76 # Extract variables from the request. Try not to get into a situation where we
77 # need to extract *every* variable from the form just for processing here, but
78 # there are legitimate uses for some variables
79 $request = $this->getRequest();
80 list( $this->target, $this->type ) = self::getTargetAndType( $par, $request );
81 if ( $this->target instanceof User ) {
82 # Set the 'relevant user' in the skin, so it displays links like Contributions,
83 # User logs, UserRights, etc.
84 $this->getSkin()->setRelevantUser( $this->target );
85 }
86
87 list( $this->previousTarget, /*...*/ ) = Block::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
88 $this->requestedHideUser = $request->getBool( 'wpHideUser' );
89 }
90
91 /**
92 * Customizes the HTMLForm a bit
93 *
94 * @param $form HTMLForm
95 */
96 protected function alterForm( HTMLForm $form ) {
97 $form->setWrapperLegendMsg( 'blockip-legend' );
98 $form->setHeaderText( '' );
99 $form->setSubmitCallback( array( __CLASS__, 'processUIForm' ) );
100
101 $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
102 $form->setSubmitTextMsg( $msg );
103
104 # Don't need to do anything if the form has been posted
105 if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
106 $s = HTMLForm::formatErrors( $this->preErrors );
107 if ( $s ) {
108 $form->addHeaderText( Html::rawElement(
109 'div',
110 array( 'class' => 'error' ),
111 $s
112 ) );
113 }
114 }
115 }
116
117 /**
118 * Get the HTMLForm descriptor array for the block form
119 * @return Array
120 */
121 protected function getFormFields() {
122 global $wgBlockAllowsUTEdit;
123
124 $user = $this->getUser();
125
126 $suggestedDurations = self::getSuggestedDurations();
127
128 $a = array(
129 'Target' => array(
130 'type' => 'text',
131 'label-message' => 'ipadressorusername',
132 'tabindex' => '1',
133 'id' => 'mw-bi-target',
134 'size' => '45',
135 'autofocus' => true,
136 'required' => true,
137 'validation-callback' => array( __CLASS__, 'validateTargetField' ),
138 ),
139 'Expiry' => array(
140 'type' => !count( $suggestedDurations ) ? 'text' : 'selectorother',
141 'label-message' => 'ipbexpiry',
142 'required' => true,
143 'tabindex' => '2',
144 'options' => $suggestedDurations,
145 'other' => $this->msg( 'ipbother' )->text(),
146 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
147 ),
148 'Reason' => array(
149 'type' => 'selectandother',
150 'label-message' => 'ipbreason',
151 'options-message' => 'ipbreason-dropdown',
152 ),
153 'CreateAccount' => array(
154 'type' => 'check',
155 'label-message' => 'ipbcreateaccount',
156 'default' => true,
157 ),
158 );
159
160 if ( self::canBlockEmail( $user ) ) {
161 $a['DisableEmail'] = array(
162 'type' => 'check',
163 'label-message' => 'ipbemailban',
164 );
165 }
166
167 if ( $wgBlockAllowsUTEdit ) {
168 $a['DisableUTEdit'] = array(
169 'type' => 'check',
170 'label-message' => 'ipb-disableusertalk',
171 'default' => false,
172 );
173 }
174
175 $a['AutoBlock'] = array(
176 'type' => 'check',
177 'label-message' => 'ipbenableautoblock',
178 'default' => true,
179 );
180
181 # Allow some users to hide name from block log, blocklist and listusers
182 if ( $user->isAllowed( 'hideuser' ) ) {
183 $a['HideUser'] = array(
184 'type' => 'check',
185 'label-message' => 'ipbhidename',
186 'cssclass' => 'mw-block-hideuser',
187 );
188 }
189
190 # Watchlist their user page? (Only if user is logged in)
191 if ( $user->isLoggedIn() ) {
192 $a['Watch'] = array(
193 'type' => 'check',
194 'label-message' => 'ipbwatchuser',
195 );
196 }
197
198 $a['HardBlock'] = array(
199 'type' => 'check',
200 'label-message' => 'ipb-hardblock',
201 'default' => false,
202 );
203
204 # This is basically a copy of the Target field, but the user can't change it, so we
205 # can see if the warnings we maybe showed to the user before still apply
206 $a['PreviousTarget'] = array(
207 'type' => 'hidden',
208 'default' => false,
209 );
210
211 # We'll turn this into a checkbox if we need to
212 $a['Confirm'] = array(
213 'type' => 'hidden',
214 'default' => '',
215 'label-message' => 'ipb-confirm',
216 );
217
218 $this->maybeAlterFormDefaults( $a );
219
220 // Allow extensions to add more fields
221 wfRunHooks( 'SpecialBlockModifyFormFields', array( $this, &$a ) );
222
223 return $a;
224 }
225
226 /**
227 * If the user has already been blocked with similar settings, load that block
228 * and change the defaults for the form fields to match the existing settings.
229 * @param array $fields HTMLForm descriptor array
230 * @return Bool whether fields were altered (that is, whether the target is
231 * already blocked)
232 */
233 protected function maybeAlterFormDefaults( &$fields ) {
234 # This will be overwritten by request data
235 $fields['Target']['default'] = (string)$this->target;
236
237 # This won't be
238 $fields['PreviousTarget']['default'] = (string)$this->target;
239
240 $block = Block::newFromTarget( $this->target );
241
242 if ( $block instanceof Block && !$block->mAuto # The block exists and isn't an autoblock
243 && ( $this->type != Block::TYPE_RANGE # The block isn't a rangeblock
244 || $block->getTarget() == $this->target ) # or if it is, the range is what we're about to block
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[] = array( 'ipb-confirmhideuser', 'ipb-confirmaction' );
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[] = array( 'ipb-blockingself', 'ipb-confirmaction' );
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
449 return null;
450 }
451
452 /**
453 * Determine the target of the block, and the type of target
454 * TODO: should be in Block.php?
455 * @param string $par subpage parameter passed to setup, or data value from
456 * the HTMLForm
457 * @param $request WebRequest optionally try and get data from a request too
458 * @return array( User|string|null, Block::TYPE_ constant|null )
459 */
460 public static function getTargetAndType( $par, WebRequest $request = null ) {
461 $i = 0;
462 $target = null;
463
464 while ( true ) {
465 switch ( $i++ ) {
466 case 0:
467 # The HTMLForm will check wpTarget first and only if it doesn't get
468 # a value use the default, which will be generated from the options
469 # below; so this has to have a higher precedence here than $par, or
470 # we could end up with different values in $this->target and the HTMLForm!
471 if ( $request instanceof WebRequest ) {
472 $target = $request->getText( 'wpTarget', null );
473 }
474 break;
475 case 1:
476 $target = $par;
477 break;
478 case 2:
479 if ( $request instanceof WebRequest ) {
480 $target = $request->getText( 'ip', null );
481 }
482 break;
483 case 3:
484 # B/C @since 1.18
485 if ( $request instanceof WebRequest ) {
486 $target = $request->getText( 'wpBlockAddress', null );
487 }
488 break;
489 case 4:
490 break 2;
491 }
492
493 list( $target, $type ) = Block::parseTarget( $target );
494
495 if ( $type !== null ) {
496 return array( $target, $type );
497 }
498 }
499
500 return array( null, null );
501 }
502
503 /**
504 * HTMLForm field validation-callback for Target field.
505 * @since 1.18
506 * @param $value String
507 * @param $alldata Array
508 * @param $form HTMLForm
509 * @return Message
510 */
511 public static function validateTargetField( $value, $alldata, $form ) {
512 $status = self::validateTarget( $value, $form->getUser() );
513 if ( !$status->isOK() ) {
514 $errors = $status->getErrorsArray();
515
516 return call_user_func_array( array( $form, 'msg' ), $errors[0] );
517 } else {
518 return true;
519 }
520 }
521
522 /**
523 * Validate a block target.
524 *
525 * @since 1.21
526 * @param string $value Block target to check
527 * @param User $user Performer of the block
528 * @return Status
529 */
530 public static function validateTarget( $value, User $user ) {
531 global $wgBlockCIDRLimit;
532
533 /** @var User $target */
534 list( $target, $type ) = self::getTargetAndType( $value );
535 $status = Status::newGood( $target );
536
537 if ( $type == Block::TYPE_USER ) {
538 if ( $target->isAnon() ) {
539 $status->fatal(
540 'nosuchusershort',
541 wfEscapeWikiText( $target->getName() )
542 );
543 }
544
545 $unblockStatus = self::checkUnblockSelf( $target, $user );
546 if ( $unblockStatus !== true ) {
547 $status->fatal( 'badaccess', $unblockStatus );
548 }
549 } elseif ( $type == Block::TYPE_RANGE ) {
550 list( $ip, $range ) = explode( '/', $target, 2 );
551
552 if (
553 ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
554 ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
555 ) {
556 // Range block effectively disabled
557 $status->fatal( 'range_block_disabled' );
558 }
559
560 if (
561 ( IP::isIPv4( $ip ) && $range > 32 ) ||
562 ( IP::isIPv6( $ip ) && $range > 128 )
563 ) {
564 // Dodgy range
565 $status->fatal( 'ip_range_invalid' );
566 }
567
568 if ( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
569 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
570 }
571
572 if ( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
573 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
574 }
575 } elseif ( $type == Block::TYPE_IP ) {
576 # All is well
577 } else {
578 $status->fatal( 'badipaddress' );
579 }
580
581 return $status;
582 }
583
584 /**
585 * Submit callback for an HTMLForm object, will simply pass
586 * @param $data array
587 * @param $form HTMLForm
588 * @return Bool|String
589 */
590 public static function processUIForm( array $data, HTMLForm $form ) {
591 return self::processForm( $data, $form->getContext() );
592 }
593
594 /**
595 * Given the form data, actually implement a block
596 * @param $data Array
597 * @param $context IContextSource
598 * @return Bool|String
599 */
600 public static function processForm( array $data, IContextSource $context ) {
601 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit;
602
603 $performer = $context->getUser();
604
605 // Handled by field validator callback
606 // self::validateTargetField( $data['Target'] );
607
608 # This might have been a hidden field or a checkbox, so interesting data
609 # can come from it
610 $data['Confirm'] = !in_array( $data['Confirm'], array( '', '0', null, false ), true );
611
612 /** @var User $target */
613 list( $target, $type ) = self::getTargetAndType( $data['Target'] );
614 if ( $type == Block::TYPE_USER ) {
615 $user = $target;
616 $target = $user->getName();
617 $userId = $user->getId();
618
619 # Give admins a heads-up before they go and block themselves. Much messier
620 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
621 # permission anyway, although the code does allow for it.
622 # Note: Important to use $target instead of $data['Target']
623 # since both $data['PreviousTarget'] and $target are normalized
624 # but $data['target'] gets overriden by (non-normalized) request variable
625 # from previous request.
626 if ( $target === $performer->getName() &&
627 ( $data['PreviousTarget'] !== $target || !$data['Confirm'] )
628 ) {
629 return array( 'ipb-blockingself', 'ipb-confirmaction' );
630 }
631 } elseif ( $type == Block::TYPE_RANGE ) {
632 $userId = 0;
633 } elseif ( $type == Block::TYPE_IP ) {
634 $target = $target->getName();
635 $userId = 0;
636 } else {
637 # This should have been caught in the form field validation
638 return array( 'badipaddress' );
639 }
640
641 if ( ( strlen( $data['Expiry'] ) == 0 ) || ( strlen( $data['Expiry'] ) > 50 )
642 || !self::parseExpiryInput( $data['Expiry'] )
643 ) {
644 return array( 'ipb_expiry_invalid' );
645 }
646
647 if ( !isset( $data['DisableEmail'] ) ) {
648 $data['DisableEmail'] = false;
649 }
650
651 # If the user has done the form 'properly', they won't even have been given the
652 # option to suppress-block unless they have the 'hideuser' permission
653 if ( !isset( $data['HideUser'] ) ) {
654 $data['HideUser'] = false;
655 }
656
657 if ( $data['HideUser'] ) {
658 if ( !$performer->isAllowed( 'hideuser' ) ) {
659 # this codepath is unreachable except by a malicious user spoofing forms,
660 # or by race conditions (user has oversight and sysop, loads block form,
661 # and is de-oversighted before submission); so need to fail completely
662 # rather than just silently disable hiding
663 return array( 'badaccess-group0' );
664 }
665
666 # Recheck params here...
667 if ( $type != Block::TYPE_USER ) {
668 $data['HideUser'] = false; # IP users should not be hidden
669 } elseif ( !in_array( $data['Expiry'], array( 'infinite', 'infinity', 'indefinite' ) ) ) {
670 # Bad expiry.
671 return array( 'ipb_expiry_temp' );
672 } elseif ( $wgHideUserContribLimit !== false
673 && $user->getEditCount() > $wgHideUserContribLimit
674 ) {
675 # Typically, the user should have a handful of edits.
676 # Disallow hiding users with many edits for performance.
677 return array( array( 'ipb_hide_invalid',
678 Message::numParam( $wgHideUserContribLimit ) ) );
679 } elseif ( !$data['Confirm'] ) {
680 return array( 'ipb-confirmhideuser', 'ipb-confirmaction' );
681 }
682 }
683
684 # Create block object.
685 $block = new Block();
686 $block->setTarget( $target );
687 $block->setBlocker( $performer );
688 $block->mReason = $data['Reason'][0];
689 $block->mExpiry = self::parseExpiryInput( $data['Expiry'] );
690 $block->prevents( 'createaccount', $data['CreateAccount'] );
691 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit || $data['DisableUTEdit'] ) );
692 $block->prevents( 'sendemail', $data['DisableEmail'] );
693 $block->isHardblock( $data['HardBlock'] );
694 $block->isAutoblocking( $data['AutoBlock'] );
695 $block->mHideName = $data['HideUser'];
696
697 $reason = array( 'hookaborted' );
698 if ( !wfRunHooks( 'BlockIp', array( &$block, &$performer, &$reason ) ) ) {
699 return $reason;
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->isHardblock( $block->isHardblock() );
733 $currentBlock->prevents( 'createaccount', $block->prevents( 'createaccount' ) );
734 $currentBlock->mExpiry = $block->mExpiry;
735 $currentBlock->isAutoblocking( $block->isAutoblocking() );
736 $currentBlock->mHideName = $block->mHideName;
737 $currentBlock->prevents( 'sendemail', $block->prevents( 'sendemail' ) );
738 $currentBlock->prevents( 'editownusertalk', $block->prevents( 'editownusertalk' ) );
739 $currentBlock->mReason = $block->mReason;
740
741 $status = $currentBlock->update();
742
743 $logaction = 'reblock';
744
745 # Unset _deleted fields if requested
746 if ( $currentBlock->mHideName && !$data['HideUser'] ) {
747 RevisionDeleteUser::unsuppressUserName( $target, $userId );
748 }
749
750 # If hiding/unhiding a name, this should go in the private logs
751 if ( (bool)$currentBlock->mHideName ) {
752 $data['HideUser'] = true;
753 }
754 }
755 } else {
756 $logaction = 'block';
757 }
758
759 wfRunHooks( 'BlockIpComplete', array( $block, $performer ) );
760
761 # Set *_deleted fields if requested
762 if ( $data['HideUser'] ) {
763 RevisionDeleteUser::suppressUserName( $target, $userId );
764 }
765
766 # Can't watch a rangeblock
767 if ( $type != Block::TYPE_RANGE && $data['Watch'] ) {
768 WatchAction::doWatch( Title::makeTitle( NS_USER, $target ), $performer, WatchedItem::IGNORE_USER_RIGHTS );
769 }
770
771 # Block constructor sanitizes certain block options on insert
772 $data['BlockEmail'] = $block->prevents( 'sendemail' );
773 $data['AutoBlock'] = $block->isAutoblocking();
774
775 # Prepare log parameters
776 $logParams = array();
777 $logParams[] = $data['Expiry'];
778 $logParams[] = self::blockLogFlags( $data, $type );
779
780 # Make log entry, if the name is hidden, put it in the oversight log
781 $log_type = $data['HideUser'] ? 'suppress' : 'block';
782 $log = new LogPage( $log_type );
783 $log_id = $log->addEntry(
784 $logaction,
785 Title::makeTitle( NS_USER, $target ),
786 $data['Reason'][0],
787 $logParams,
788 $performer
789 );
790 # Relate log ID to block IDs (bug 25763)
791 $blockIds = array_merge( array( $status['id'] ), $status['autoIds'] );
792 $log->addRelations( 'ipb_id', $blockIds, $log_id );
793
794 # Report to the user
795 return true;
796 }
797
798 /**
799 * Get an array of suggested block durations from MediaWiki:Ipboptions
800 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
801 * to the standard "**<duration>|<displayname>" format?
802 * @param $lang Language|null the language to get the durations in, or null to use
803 * the wiki's content language
804 * @return Array
805 */
806 public static function getSuggestedDurations( $lang = null ) {
807 $a = array();
808 $msg = $lang === null
809 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
810 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
811
812 if ( $msg == '-' ) {
813 return array();
814 }
815
816 foreach ( explode( ',', $msg ) as $option ) {
817 if ( strpos( $option, ':' ) === false ) {
818 $option = "$option:$option";
819 }
820
821 list( $show, $value ) = explode( ':', $option );
822 $a[htmlspecialchars( $show )] = htmlspecialchars( $value );
823 }
824
825 return $a;
826 }
827
828 /**
829 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
830 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
831 * @param string $expiry whatever was typed into the form
832 * @return String: timestamp or "infinity" string for the DB implementation
833 */
834 public static function parseExpiryInput( $expiry ) {
835 static $infinity;
836 if ( $infinity == null ) {
837 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
838 }
839
840 if ( $expiry == 'infinite' || $expiry == 'indefinite' ) {
841 $expiry = $infinity;
842 } else {
843 $expiry = strtotime( $expiry );
844
845 if ( $expiry < 0 || $expiry === false ) {
846 return false;
847 }
848
849 $expiry = wfTimestamp( TS_MW, $expiry );
850 }
851
852 return $expiry;
853 }
854
855 /**
856 * Can we do an email block?
857 * @param $user User: the sysop wanting to make a block
858 * @return Boolean
859 */
860 public static function canBlockEmail( $user ) {
861 global $wgEnableUserEmail, $wgSysopEmailBans;
862
863 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
864 }
865
866 /**
867 * bug 15810: blocked admins should not be able to block/unblock
868 * others, and probably shouldn't be able to unblock themselves
869 * either.
870 * @param $user User|Int|String
871 * @param $performer User user doing the request
872 * @return Bool|String true or error message key
873 */
874 public static function checkUnblockSelf( $user, User $performer ) {
875 if ( is_int( $user ) ) {
876 $user = User::newFromId( $user );
877 } elseif ( is_string( $user ) ) {
878 $user = User::newFromName( $user );
879 }
880
881 if ( $performer->isBlocked() ) {
882 if ( $user instanceof User && $user->getId() == $performer->getId() ) {
883 # User is trying to unblock themselves
884 if ( $performer->isAllowed( 'unblockself' ) ) {
885 return true;
886 # User blocked themselves and is now trying to reverse it
887 } elseif ( $performer->blockedBy() === $performer->getName() ) {
888 return true;
889 } else {
890 return 'ipbnounblockself';
891 }
892 } else {
893 # User is trying to block/unblock someone else
894 return 'ipbblocked';
895 }
896 } else {
897 return true;
898 }
899 }
900
901 /**
902 * Return a comma-delimited list of "flags" to be passed to the log
903 * reader for this block, to provide more information in the logs
904 * @param array $data from HTMLForm data
905 * @param $type Block::TYPE_ constant (USER, RANGE, or IP)
906 * @return string
907 */
908 protected static function blockLogFlags( array $data, $type ) {
909 global $wgBlockAllowsUTEdit;
910 $flags = array();
911
912 # when blocking a user the option 'anononly' is not available/has no effect
913 # -> do not write this into log
914 if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
915 // For grepping: message block-log-flags-anononly
916 $flags[] = 'anononly';
917 }
918
919 if ( $data['CreateAccount'] ) {
920 // For grepping: message block-log-flags-nocreate
921 $flags[] = 'nocreate';
922 }
923
924 # Same as anononly, this is not displayed when blocking an IP address
925 if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
926 // For grepping: message block-log-flags-noautoblock
927 $flags[] = 'noautoblock';
928 }
929
930 if ( $data['DisableEmail'] ) {
931 // For grepping: message block-log-flags-noemail
932 $flags[] = 'noemail';
933 }
934
935 if ( $wgBlockAllowsUTEdit && $data['DisableUTEdit'] ) {
936 // For grepping: message block-log-flags-nousertalk
937 $flags[] = 'nousertalk';
938 }
939
940 if ( $data['HideUser'] ) {
941 // For grepping: message block-log-flags-hiddenname
942 $flags[] = 'hiddenname';
943 }
944
945 return implode( ',', $flags );
946 }
947
948 /**
949 * Process the form on POST submission.
950 * @param $data Array
951 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
952 */
953 public function onSubmit( array $data ) {
954 // This isn't used since we need that HTMLForm that's passed in the
955 // second parameter. See alterForm for the real function
956 }
957
958 /**
959 * Do something exciting on successful processing of the form, most likely to show a
960 * confirmation message
961 */
962 public function onSuccess() {
963 $out = $this->getOutput();
964 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
965 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
966 }
967
968 protected function getGroupName() {
969 return 'users';
970 }
971 }
972
973 # BC @since 1.18
974 class IPBlockForm extends SpecialBlock {
975 }