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