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