Allow maxlength attribute on HTMLSelectAndOtherField
[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->setSubmitCallback( array( __CLASS__, 'processUIForm' ) );
101 $form->setSubmitDestructive();
102
103 $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
104 $form->setSubmitTextMsg( $msg );
105
106 # Don't need to do anything if the form has been posted
107 if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
108 $s = HTMLForm::formatErrors( $this->preErrors );
109 if ( $s ) {
110 $form->addHeaderText( Html::rawElement(
111 'div',
112 array( 'class' => 'error' ),
113 $s
114 ) );
115 }
116 }
117 }
118
119 /**
120 * Get the HTMLForm descriptor array for the block form
121 * @return array
122 */
123 protected function getFormFields() {
124 global $wgBlockAllowsUTEdit;
125
126 $user = $this->getUser();
127
128 $suggestedDurations = self::getSuggestedDurations();
129
130 $a = array(
131 'Target' => array(
132 'type' => 'text',
133 'label-message' => 'ipaddressorusername',
134 'id' => 'mw-bi-target',
135 'size' => '45',
136 'autofocus' => true,
137 'required' => true,
138 'validation-callback' => array( __CLASS__, 'validateTargetField' ),
139 ),
140 'Expiry' => array(
141 'type' => !count( $suggestedDurations ) ? 'text' : 'selectorother',
142 'label-message' => 'ipbexpiry',
143 'required' => true,
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 'maxlength' => 255,
151 'label-message' => 'ipbreason',
152 'options-message' => 'ipbreason-dropdown',
153 ),
154 'CreateAccount' => array(
155 'type' => 'check',
156 'label-message' => 'ipbcreateaccount',
157 'default' => true,
158 ),
159 );
160
161 if ( self::canBlockEmail( $user ) ) {
162 $a['DisableEmail'] = array(
163 'type' => 'check',
164 'label-message' => 'ipbemailban',
165 );
166 }
167
168 if ( $wgBlockAllowsUTEdit ) {
169 $a['DisableUTEdit'] = array(
170 'type' => 'check',
171 'label-message' => 'ipb-disableusertalk',
172 'default' => false,
173 );
174 }
175
176 $a['AutoBlock'] = array(
177 'type' => 'check',
178 'label-message' => 'ipbenableautoblock',
179 'default' => true,
180 );
181
182 # Allow some users to hide name from block log, blocklist and listusers
183 if ( $user->isAllowed( 'hideuser' ) ) {
184 $a['HideUser'] = array(
185 'type' => 'check',
186 'label-message' => 'ipbhidename',
187 'cssclass' => 'mw-block-hideuser',
188 );
189 }
190
191 # Watchlist their user page? (Only if user is logged in)
192 if ( $user->isLoggedIn() ) {
193 $a['Watch'] = array(
194 'type' => 'check',
195 'label-message' => 'ipbwatchuser',
196 );
197 }
198
199 $a['HardBlock'] = array(
200 'type' => 'check',
201 'label-message' => 'ipb-hardblock',
202 'default' => false,
203 );
204
205 # This is basically a copy of the Target field, but the user can't change it, so we
206 # can see if the warnings we maybe showed to the user before still apply
207 $a['PreviousTarget'] = array(
208 'type' => 'hidden',
209 'default' => false,
210 );
211
212 # We'll turn this into a checkbox if we need to
213 $a['Confirm'] = array(
214 'type' => 'hidden',
215 'default' => '',
216 'label-message' => 'ipb-confirm',
217 );
218
219 $this->maybeAlterFormDefaults( $a );
220
221 // Allow extensions to add more fields
222 wfRunHooks( 'SpecialBlockModifyFormFields', array( $this, &$a ) );
223
224 return $a;
225 }
226
227 /**
228 * If the user has already been blocked with similar settings, load that block
229 * and change the defaults for the form fields to match the existing settings.
230 * @param array $fields HTMLForm descriptor array
231 * @return bool Whether fields were altered (that is, whether the target is
232 * already blocked)
233 */
234 protected function maybeAlterFormDefaults( &$fields ) {
235 # This will be overwritten by request data
236 $fields['Target']['default'] = (string)$this->target;
237
238 # This won't be
239 $fields['PreviousTarget']['default'] = (string)$this->target;
240
241 $block = Block::newFromTarget( $this->target );
242
243 if ( $block instanceof Block && !$block->mAuto # The block exists and isn't an autoblock
244 && ( $this->type != Block::TYPE_RANGE # The block isn't a rangeblock
245 || $block->getTarget() == $this->target ) # or if it is, the range is what we're about to block
246 ) {
247 $fields['HardBlock']['default'] = $block->isHardblock();
248 $fields['CreateAccount']['default'] = $block->prevents( 'createaccount' );
249 $fields['AutoBlock']['default'] = $block->isAutoblocking();
250
251 if ( isset( $fields['DisableEmail'] ) ) {
252 $fields['DisableEmail']['default'] = $block->prevents( 'sendemail' );
253 }
254
255 if ( isset( $fields['HideUser'] ) ) {
256 $fields['HideUser']['default'] = $block->mHideName;
257 }
258
259 if ( isset( $fields['DisableUTEdit'] ) ) {
260 $fields['DisableUTEdit']['default'] = $block->prevents( 'editownusertalk' );
261 }
262
263 // If the username was hidden (ipb_deleted == 1), don't show the reason
264 // unless this user also has rights to hideuser: Bug 35839
265 if ( !$block->mHideName || $this->getUser()->isAllowed( 'hideuser' ) ) {
266 $fields['Reason']['default'] = $block->mReason;
267 } else {
268 $fields['Reason']['default'] = '';
269 }
270
271 if ( $this->getRequest()->wasPosted() ) {
272 # Ok, so we got a POST submission asking us to reblock a user. So show the
273 # confirm checkbox; the user will only see it if they haven't previously
274 $fields['Confirm']['type'] = 'check';
275 } else {
276 # We got a target, but it wasn't a POST request, so the user must have gone
277 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
278 # as long as they go ahead and block *that* user
279 $fields['Confirm']['default'] = 1;
280 }
281
282 if ( $block->mExpiry == 'infinity' ) {
283 $fields['Expiry']['default'] = 'infinite';
284 } else {
285 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->mExpiry );
286 }
287
288 $this->alreadyBlocked = true;
289 $this->preErrors[] = array( 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) );
290 }
291
292 # We always need confirmation to do HideUser
293 if ( $this->requestedHideUser ) {
294 $fields['Confirm']['type'] = 'check';
295 unset( $fields['Confirm']['default'] );
296 $this->preErrors[] = array( 'ipb-confirmhideuser', 'ipb-confirmaction' );
297 }
298
299 # Or if the user is trying to block themselves
300 if ( (string)$this->target === $this->getUser()->getName() ) {
301 $fields['Confirm']['type'] = 'check';
302 unset( $fields['Confirm']['default'] );
303 $this->preErrors[] = array( 'ipb-blockingself', 'ipb-confirmaction' );
304 }
305 }
306
307 /**
308 * Add header elements like block log entries, etc.
309 * @return string
310 */
311 protected function preText() {
312 $this->getOutput()->addModules( 'mediawiki.special.block' );
313
314 $text = $this->msg( 'blockiptext' )->parse();
315
316 $otherBlockMessages = array();
317 if ( $this->target !== null ) {
318 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
319 wfRunHooks( 'OtherBlockLogLink', array( &$otherBlockMessages, $this->target ) );
320
321 if ( count( $otherBlockMessages ) ) {
322 $s = Html::rawElement(
323 'h2',
324 array(),
325 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
326 ) . "\n";
327
328 $list = '';
329
330 foreach ( $otherBlockMessages as $link ) {
331 $list .= Html::rawElement( 'li', array(), $link ) . "\n";
332 }
333
334 $s .= Html::rawElement(
335 'ul',
336 array( 'class' => 'mw-blockip-alreadyblocked' ),
337 $list
338 ) . "\n";
339
340 $text .= $s;
341 }
342 }
343
344 return $text;
345 }
346
347 /**
348 * Add footer elements to the form
349 * @return string
350 */
351 protected function postText() {
352 $links = array();
353
354 # Link to the user's contributions, if applicable
355 if ( $this->target instanceof User ) {
356 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
357 $links[] = Linker::link(
358 $contribsPage,
359 $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->escaped()
360 );
361 }
362
363 # Link to unblock the specified user, or to a blank unblock form
364 if ( $this->target instanceof User ) {
365 $message = $this->msg(
366 'ipb-unblock-addr',
367 wfEscapeWikiText( $this->target->getName() )
368 )->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 User|string $target
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 WebRequest $request 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 string $value
511 * @param array $alldata
512 * @param HTMLForm $form
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 array $data
591 * @param HTMLForm $form
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 array $data
601 * @param IContextSource $context
602 * @return bool|string
603 */
604 public static function processForm( array $data, IContextSource $context ) {
605 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit, $wgContLang;
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 ( $wgHideUserContribLimit !== false
677 && $user->getEditCount() > $wgHideUserContribLimit
678 ) {
679 # Typically, the user should have a handful of edits.
680 # Disallow hiding users with many edits for performance.
681 return array( array( 'ipb_hide_invalid',
682 Message::numParam( $wgHideUserContribLimit ) ) );
683 } elseif ( !$data['Confirm'] ) {
684 return array( 'ipb-confirmhideuser', 'ipb-confirmaction' );
685 }
686 }
687
688 # Create block object.
689 $block = new Block();
690 $block->setTarget( $target );
691 $block->setBlocker( $performer );
692 # Truncate reason for whole multibyte characters
693 $block->mReason = $wgContLang->truncate( $data['Reason'][0], 255 );
694 $block->mExpiry = self::parseExpiryInput( $data['Expiry'] );
695 $block->prevents( 'createaccount', $data['CreateAccount'] );
696 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit || $data['DisableUTEdit'] ) );
697 $block->prevents( 'sendemail', $data['DisableEmail'] );
698 $block->isHardblock( $data['HardBlock'] );
699 $block->isAutoblocking( $data['AutoBlock'] );
700 $block->mHideName = $data['HideUser'];
701
702 $reason = array( 'hookaborted' );
703 if ( !wfRunHooks( 'BlockIp', array( &$block, &$performer, &$reason ) ) ) {
704 return $reason;
705 }
706
707 # Try to insert block. Is there a conflicting block?
708 $status = $block->insert();
709 if ( !$status ) {
710 # Indicates whether the user is confirming the block and is aware of
711 # the conflict (did not change the block target in the meantime)
712 $blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
713 && $data['PreviousTarget'] !== $target );
714
715 # Special case for API - bug 32434
716 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
717
718 # Show form unless the user is already aware of this...
719 if ( $blockNotConfirmed || $reblockNotAllowed ) {
720 return array( array( 'ipb_already_blocked', $block->getTarget() ) );
721 # Otherwise, try to update the block...
722 } else {
723 # This returns direct blocks before autoblocks/rangeblocks, since we should
724 # be sure the user is blocked by now it should work for our purposes
725 $currentBlock = Block::newFromTarget( $target );
726
727 if ( $block->equals( $currentBlock ) ) {
728 return array( array( 'ipb_already_blocked', $block->getTarget() ) );
729 }
730
731 # If the name was hidden and the blocking user cannot hide
732 # names, then don't allow any block changes...
733 if ( $currentBlock->mHideName && !$performer->isAllowed( 'hideuser' ) ) {
734 return array( 'cant-see-hidden-user' );
735 }
736
737 $currentBlock->isHardblock( $block->isHardblock() );
738 $currentBlock->prevents( 'createaccount', $block->prevents( 'createaccount' ) );
739 $currentBlock->mExpiry = $block->mExpiry;
740 $currentBlock->isAutoblocking( $block->isAutoblocking() );
741 $currentBlock->mHideName = $block->mHideName;
742 $currentBlock->prevents( 'sendemail', $block->prevents( 'sendemail' ) );
743 $currentBlock->prevents( 'editownusertalk', $block->prevents( 'editownusertalk' ) );
744 $currentBlock->mReason = $block->mReason;
745
746 $status = $currentBlock->update();
747
748 $logaction = 'reblock';
749
750 # Unset _deleted fields if requested
751 if ( $currentBlock->mHideName && !$data['HideUser'] ) {
752 RevisionDeleteUser::unsuppressUserName( $target, $userId );
753 }
754
755 # If hiding/unhiding a name, this should go in the private logs
756 if ( (bool)$currentBlock->mHideName ) {
757 $data['HideUser'] = true;
758 }
759 }
760 } else {
761 $logaction = 'block';
762 }
763
764 wfRunHooks( 'BlockIpComplete', array( $block, $performer ) );
765
766 # Set *_deleted fields if requested
767 if ( $data['HideUser'] ) {
768 RevisionDeleteUser::suppressUserName( $target, $userId );
769 }
770
771 # Can't watch a rangeblock
772 if ( $type != Block::TYPE_RANGE && $data['Watch'] ) {
773 WatchAction::doWatch(
774 Title::makeTitle( NS_USER, $target ),
775 $performer,
776 WatchedItem::IGNORE_USER_RIGHTS
777 );
778 }
779
780 # Block constructor sanitizes certain block options on insert
781 $data['BlockEmail'] = $block->prevents( 'sendemail' );
782 $data['AutoBlock'] = $block->isAutoblocking();
783
784 # Prepare log parameters
785 $logParams = array();
786 $logParams[] = $data['Expiry'];
787 $logParams[] = self::blockLogFlags( $data, $type );
788
789 # Make log entry, if the name is hidden, put it in the oversight log
790 $log_type = $data['HideUser'] ? 'suppress' : 'block';
791 $log = new LogPage( $log_type );
792 $log_id = $log->addEntry(
793 $logaction,
794 Title::makeTitle( NS_USER, $target ),
795 $data['Reason'][0],
796 $logParams,
797 $performer
798 );
799 # Relate log ID to block IDs (bug 25763)
800 $blockIds = array_merge( array( $status['id'] ), $status['autoIds'] );
801 $log->addRelations( 'ipb_id', $blockIds, $log_id );
802
803 # Report to the user
804 return true;
805 }
806
807 /**
808 * Get an array of suggested block durations from MediaWiki:Ipboptions
809 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
810 * to the standard "**<duration>|<displayname>" format?
811 * @param Language|null $lang The language to get the durations in, or null to use
812 * the wiki's content language
813 * @return array
814 */
815 public static function getSuggestedDurations( $lang = null ) {
816 $a = array();
817 $msg = $lang === null
818 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
819 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
820
821 if ( $msg == '-' ) {
822 return array();
823 }
824
825 foreach ( explode( ',', $msg ) as $option ) {
826 if ( strpos( $option, ':' ) === false ) {
827 $option = "$option:$option";
828 }
829
830 list( $show, $value ) = explode( ':', $option );
831 $a[htmlspecialchars( $show )] = htmlspecialchars( $value );
832 }
833
834 return $a;
835 }
836
837 /**
838 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
839 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
840 * @param string $expiry Whatever was typed into the form
841 * @return string Timestamp or "infinity" string for the DB implementation
842 */
843 public static function parseExpiryInput( $expiry ) {
844 static $infinity;
845 if ( $infinity == null ) {
846 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
847 }
848
849 if ( $expiry == 'infinite' || $expiry == 'indefinite' ) {
850 $expiry = $infinity;
851 } else {
852 $expiry = strtotime( $expiry );
853
854 if ( $expiry < 0 || $expiry === false ) {
855 return false;
856 }
857
858 $expiry = wfTimestamp( TS_MW, $expiry );
859 }
860
861 return $expiry;
862 }
863
864 /**
865 * Can we do an email block?
866 * @param User $user The sysop wanting to make a block
867 * @return bool
868 */
869 public static function canBlockEmail( $user ) {
870 global $wgEnableUserEmail, $wgSysopEmailBans;
871
872 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
873 }
874
875 /**
876 * bug 15810: blocked admins should not be able to block/unblock
877 * others, and probably shouldn't be able to unblock themselves
878 * either.
879 * @param User|int|string $user
880 * @param User $performer User doing the request
881 * @return bool|string True or error message key
882 */
883 public static function checkUnblockSelf( $user, User $performer ) {
884 if ( is_int( $user ) ) {
885 $user = User::newFromId( $user );
886 } elseif ( is_string( $user ) ) {
887 $user = User::newFromName( $user );
888 }
889
890 if ( $performer->isBlocked() ) {
891 if ( $user instanceof User && $user->getId() == $performer->getId() ) {
892 # User is trying to unblock themselves
893 if ( $performer->isAllowed( 'unblockself' ) ) {
894 return true;
895 # User blocked themselves and is now trying to reverse it
896 } elseif ( $performer->blockedBy() === $performer->getName() ) {
897 return true;
898 } else {
899 return 'ipbnounblockself';
900 }
901 } else {
902 # User is trying to block/unblock someone else
903 return 'ipbblocked';
904 }
905 } else {
906 return true;
907 }
908 }
909
910 /**
911 * Return a comma-delimited list of "flags" to be passed to the log
912 * reader for this block, to provide more information in the logs
913 * @param array $data From HTMLForm data
914 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
915 * @return string
916 */
917 protected static function blockLogFlags( array $data, $type ) {
918 global $wgBlockAllowsUTEdit;
919 $flags = array();
920
921 # when blocking a user the option 'anononly' is not available/has no effect
922 # -> do not write this into log
923 if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
924 // For grepping: message block-log-flags-anononly
925 $flags[] = 'anononly';
926 }
927
928 if ( $data['CreateAccount'] ) {
929 // For grepping: message block-log-flags-nocreate
930 $flags[] = 'nocreate';
931 }
932
933 # Same as anononly, this is not displayed when blocking an IP address
934 if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
935 // For grepping: message block-log-flags-noautoblock
936 $flags[] = 'noautoblock';
937 }
938
939 if ( $data['DisableEmail'] ) {
940 // For grepping: message block-log-flags-noemail
941 $flags[] = 'noemail';
942 }
943
944 if ( $wgBlockAllowsUTEdit && $data['DisableUTEdit'] ) {
945 // For grepping: message block-log-flags-nousertalk
946 $flags[] = 'nousertalk';
947 }
948
949 if ( $data['HideUser'] ) {
950 // For grepping: message block-log-flags-hiddenname
951 $flags[] = 'hiddenname';
952 }
953
954 return implode( ',', $flags );
955 }
956
957 /**
958 * Process the form on POST submission.
959 * @param array $data
960 * @return bool|array True for success, false for didn't-try, array of errors on failure
961 */
962 public function onSubmit( array $data ) {
963 // This isn't used since we need that HTMLForm that's passed in the
964 // second parameter. See alterForm for the real function
965 }
966
967 /**
968 * Do something exciting on successful processing of the form, most likely to show a
969 * confirmation message
970 */
971 public function onSuccess() {
972 $out = $this->getOutput();
973 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
974 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
975 }
976
977 protected function getGroupName() {
978 return 'users';
979 }
980 }