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