Use local context to get messages
[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 /** The maximum number of edits a user can have and still be hidden
32 * TODO: config setting? */
33 const HIDEUSER_CONTRIBLIMIT = 1000;
34
35 /** @var User user to be blocked, as passed either by parameter (url?wpTarget=Foo)
36 * or as subpage (Special:Block/Foo) */
37 protected $target;
38
39 /// @var Block::TYPE_ constant
40 protected $type;
41
42 /// @var User|String the previous block target
43 protected $previousTarget;
44
45 /// @var Bool whether the previous submission of the form asked for HideUser
46 protected $requestedHideUser;
47
48 /// @var Bool
49 protected $alreadyBlocked;
50
51 /// @var Array
52 protected $preErrors = array();
53
54 public function __construct() {
55 parent::__construct( 'Block', 'block' );
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 $par String
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, /*...*/ ) = Block::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
92 $this->requestedHideUser = $request->getBool( 'wpHideUser' );
93 }
94
95 /**
96 * Customizes the HTMLForm a bit
97 *
98 * @param $form HTMLForm
99 */
100 protected function alterForm( HTMLForm $form ) {
101 $form->setWrapperLegendMsg( 'blockip-legend' );
102 $form->setHeaderText( '' );
103 $form->setSubmitCallback( array( __CLASS__, 'processUIForm' ) );
104
105 $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
106 $form->setSubmitTextMsg( $msg );
107
108 # Don't need to do anything if the form has been posted
109 if( !$this->getRequest()->wasPosted() && $this->preErrors ){
110 $s = HTMLForm::formatErrors( $this->preErrors );
111 if( $s ){
112 $form->addHeaderText( Html::rawElement(
113 'div',
114 array( 'class' => 'error' ),
115 $s
116 ) );
117 }
118 }
119 }
120
121 /**
122 * Get the HTMLForm descriptor array for the block form
123 * @return Array
124 */
125 protected function getFormFields(){
126 global $wgBlockAllowsUTEdit;
127
128 $user = $this->getUser();
129
130 $a = array(
131 'Target' => array(
132 'type' => 'text',
133 'label-message' => 'ipadressorusername',
134 'tabindex' => '1',
135 'id' => 'mw-bi-target',
136 'size' => '45',
137 'required' => true,
138 'validation-callback' => array( __CLASS__, 'validateTargetField' ),
139 ),
140 'Expiry' => array(
141 'type' => !count( self::getSuggestedDurations() ) ? 'text' : 'selectorother',
142 'label-message' => 'ipbexpiry',
143 'required' => true,
144 'tabindex' => '2',
145 'options' => self::getSuggestedDurations(),
146 'other' => $this->msg( 'ipbother' )->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 return $a;
221 }
222
223 /**
224 * If the user has already been blocked with similar settings, load that block
225 * and change the defaults for the form fields to match the existing settings.
226 * @param $fields Array HTMLForm descriptor array
227 * @return Bool whether fields were altered (that is, whether the target is
228 * already blocked)
229 */
230 protected function maybeAlterFormDefaults( &$fields ){
231 # This will be overwritten by request data
232 $fields['Target']['default'] = (string)$this->target;
233
234 # This won't be
235 $fields['PreviousTarget']['default'] = (string)$this->target;
236
237 $block = Block::newFromTarget( $this->target );
238
239 if( $block instanceof Block && !$block->mAuto # The block exists and isn't an autoblock
240 && ( $this->type != Block::TYPE_RANGE # The block isn't a rangeblock
241 || $block->getTarget() == $this->target ) # or if it is, the range is what we're about to block
242 )
243 {
244 $fields['HardBlock']['default'] = $block->isHardblock();
245 $fields['CreateAccount']['default'] = $block->prevents( 'createaccount' );
246 $fields['AutoBlock']['default'] = $block->isAutoblocking();
247
248 if( isset( $fields['DisableEmail'] ) ){
249 $fields['DisableEmail']['default'] = $block->prevents( 'sendemail' );
250 }
251
252 if( isset( $fields['HideUser'] ) ){
253 $fields['HideUser']['default'] = $block->mHideName;
254 }
255
256 if( isset( $fields['DisableUTEdit'] ) ){
257 $fields['DisableUTEdit']['default'] = $block->prevents( 'editownusertalk' );
258 }
259
260 $fields['Reason']['default'] = $block->mReason;
261
262 if( $this->getRequest()->wasPosted() ){
263 # Ok, so we got a POST submission asking us to reblock a user. So show the
264 # confirm checkbox; the user will only see it if they haven't previously
265 $fields['Confirm']['type'] = 'check';
266 } else {
267 # We got a target, but it wasn't a POST request, so the user must have gone
268 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
269 # as long as they go ahead and block *that* user
270 $fields['Confirm']['default'] = 1;
271 }
272
273 if( $block->mExpiry == 'infinity' ) {
274 $fields['Expiry']['default'] = 'indefinite';
275 } else {
276 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->mExpiry );
277 }
278
279 $this->alreadyBlocked = true;
280 $this->preErrors[] = array( 'ipb-needreblock', (string)$block->getTarget() );
281 }
282
283 # We always need confirmation to do HideUser
284 if( $this->requestedHideUser ){
285 $fields['Confirm']['type'] = 'check';
286 unset( $fields['Confirm']['default'] );
287 $this->preErrors[] = 'ipb-confirmhideuser';
288 }
289
290 # Or if the user is trying to block themselves
291 if( (string)$this->target === $this->getUser()->getName() ){
292 $fields['Confirm']['type'] = 'check';
293 unset( $fields['Confirm']['default'] );
294 $this->preErrors[] = 'ipb-blockingself';
295 }
296 }
297
298 /**
299 * Add header elements like block log entries, etc.
300 */
301 protected function preText(){
302 $text = $this->msg( 'blockiptext' )->parse();
303
304 $otherBlockMessages = array();
305 if( $this->target !== null ) {
306 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
307 wfRunHooks( 'OtherBlockLogLink', array( &$otherBlockMessages, $this->target ) );
308
309 if( count( $otherBlockMessages ) ) {
310 $s = Html::rawElement(
311 'h2',
312 array(),
313 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
314 ) . "\n";
315
316 $list = '';
317
318 foreach( $otherBlockMessages as $link ) {
319 $list .= Html::rawElement( 'li', array(), $link ) . "\n";
320 }
321
322 $s .= Html::rawElement(
323 'ul',
324 array( 'class' => 'mw-blockip-alreadyblocked' ),
325 $list
326 ) . "\n";
327
328 $text .= $s;
329 }
330 }
331
332 return $text;
333 }
334
335 /**
336 * Add footer elements to the form
337 * @return void
338 */
339 protected function postText(){
340 # Link to the user's contributions, if applicable
341 if( $this->target instanceof User ){
342 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
343 $links[] = Linker::link(
344 $contribsPage,
345 $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->escaped()
346 );
347 }
348
349 # Link to unblock the specified user, or to a blank unblock form
350 if( $this->target instanceof User ) {
351 $message = $this->msg( 'ipb-unblock-addr', $this->target->getName() )->parse();
352 $list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
353 } else {
354 $message = $this->msg( 'ipb-unblock' )->parse();
355 $list = SpecialPage::getTitleFor( 'Unblock' );
356 }
357 $links[] = Linker::linkKnown( $list, $message, array() );
358
359 # Link to the block list
360 $links[] = Linker::linkKnown(
361 SpecialPage::getTitleFor( 'BlockList' ),
362 $this->msg( 'ipb-blocklist' )->escaped()
363 );
364
365 $user = $this->getUser();
366
367 # Link to edit the block dropdown reasons, if applicable
368 if ( $user->isAllowed( 'editinterface' ) ) {
369 $links[] = Linker::link(
370 Title::makeTitle( NS_MEDIAWIKI, 'Ipbreason-dropdown' ),
371 $this->msg( 'ipb-edit-dropdown' )->escaped(),
372 array(),
373 array( 'action' => 'edit' )
374 );
375 }
376
377 $text = Html::rawElement(
378 'p',
379 array( 'class' => 'mw-ipb-conveniencelinks' ),
380 $this->getLanguage()->pipeList( $links )
381 );
382
383 if( $this->target instanceof User ){
384 # Get relevant extracts from the block and suppression logs, if possible
385 $userpage = $this->target->getUserPage();
386 $out = '';
387
388 LogEventsList::showLogExtract(
389 $out,
390 'block',
391 $userpage,
392 '',
393 array(
394 'lim' => 10,
395 'msgKey' => array( 'blocklog-showlog', $userpage->getText() ),
396 'showIfEmpty' => false
397 )
398 );
399 $text .= $out;
400
401 # Add suppression block entries if allowed
402 if( $user->isAllowed( 'suppressionlog' ) ) {
403 LogEventsList::showLogExtract(
404 $out,
405 'suppress',
406 $userpage,
407 '',
408 array(
409 'lim' => 10,
410 'conds' => array( 'log_action' => array( 'block', 'reblock', 'unblock' ) ),
411 'msgKey' => array( 'blocklog-showsuppresslog', $userpage->getText() ),
412 'showIfEmpty' => false
413 )
414 );
415
416 $text .= $out;
417 }
418 }
419
420 return $text;
421 }
422
423 /**
424 * Determine the target of the block, and the type of target
425 * TODO: should be in Block.php?
426 * @param $par String subpage parameter passed to setup, or data value from
427 * the HTMLForm
428 * @param $request WebRequest optionally try and get data from a request too
429 * @return array( User|string|null, Block::TYPE_ constant|null )
430 */
431 public static function getTargetAndType( $par, WebRequest $request = null ){
432 $i = 0;
433 $target = null;
434
435 while( true ){
436 switch( $i++ ){
437 case 0:
438 # The HTMLForm will check wpTarget first and only if it doesn't get
439 # a value use the default, which will be generated from the options
440 # below; so this has to have a higher precedence here than $par, or
441 # we could end up with different values in $this->target and the HTMLForm!
442 if( $request instanceof WebRequest ){
443 $target = $request->getText( 'wpTarget', null );
444 }
445 break;
446 case 1:
447 $target = $par;
448 break;
449 case 2:
450 if( $request instanceof WebRequest ){
451 $target = $request->getText( 'ip', null );
452 }
453 break;
454 case 3:
455 # B/C @since 1.18
456 if( $request instanceof WebRequest ){
457 $target = $request->getText( 'wpBlockAddress', null );
458 }
459 break;
460 case 4:
461 break 2;
462 }
463
464 list( $target, $type ) = Block::parseTarget( $target );
465
466 if( $type !== null ){
467 return array( $target, $type );
468 }
469 }
470
471 return array( null, null );
472 }
473
474 /**
475 * HTMLForm field validation-callback for Target field.
476 * @since 1.18
477 * @param $value String
478 * @param $alldata Array
479 * @param $form HTMLForm
480 * @return Message
481 */
482 public static function validateTargetField( $value, $alldata, $form ) {
483 global $wgBlockCIDRLimit;
484
485 list( $target, $type ) = self::getTargetAndType( $value );
486
487 if( $type == Block::TYPE_USER ){
488 # TODO: why do we not have a User->exists() method?
489 if( !$target->getId() ){
490 return $form->msg( 'nosuchusershort',
491 wfEscapeWikiText( $target->getName() ) );
492 }
493
494 $status = self::checkUnblockSelf( $target, $form->getUser() );
495 if ( $status !== true ) {
496 return $form->msg( 'badaccess', $status );
497 }
498
499 } elseif( $type == Block::TYPE_RANGE ){
500 list( $ip, $range ) = explode( '/', $target, 2 );
501
502 if( ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 )
503 || ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 ) )
504 {
505 # Range block effectively disabled
506 return $form->msg( 'range_block_disabled' );
507 }
508
509 if( ( IP::isIPv4( $ip ) && $range > 32 )
510 || ( IP::isIPv6( $ip ) && $range > 128 ) )
511 {
512 # Dodgy range
513 return $form->msg( 'ip_range_invalid' );
514 }
515
516 if( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
517 return $form->msg( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
518 }
519
520 if( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
521 return $form->msg( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
522 }
523 } elseif( $type == Block::TYPE_IP ){
524 # All is well
525 } else {
526 return $form->msg( 'badipaddress' );
527 }
528
529 return true;
530 }
531
532 /**
533 * Submit callback for an HTMLForm object, will simply pass
534 * @param $data array
535 * @param $form HTMLForm
536 * @return Bool|String
537 */
538 public static function processUIForm( array $data, HTMLForm $form ) {
539 return self::processForm( $data, $form->getContext() );
540 }
541
542 /**
543 * Given the form data, actually implement a block
544 * @param $data Array
545 * @param $context IContextSource
546 * @return Bool|String
547 */
548 public static function processForm( array $data, IContextSource $context ){
549 global $wgBlockAllowsUTEdit;
550
551 $performer = $context->getUser();
552
553 // Handled by field validator callback
554 // self::validateTargetField( $data['Target'] );
555
556 # This might have been a hidden field or a checkbox, so interesting data
557 # can come from it
558 $data['Confirm'] = !in_array( $data['Confirm'], array( '', '0', null, false ), true );
559
560 list( $target, $type ) = self::getTargetAndType( $data['Target'] );
561 if( $type == Block::TYPE_USER ){
562 $user = $target;
563 $target = $user->getName();
564 $userId = $user->getId();
565
566 # Give admins a heads-up before they go and block themselves. Much messier
567 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
568 # permission anyway, although the code does allow for it.
569 # Note: Important to use $target instead of $data['Target']
570 # since both $data['PreviousTarget'] and $target are normalized
571 # but $data['target'] gets overriden by (non-normalized) request variable
572 # from previous request.
573 if( $target === $performer->getName() &&
574 ( $data['PreviousTarget'] !== $target || !$data['Confirm'] ) )
575 {
576 return array( 'ipb-blockingself' );
577 }
578 } elseif( $type == Block::TYPE_RANGE ){
579 $userId = 0;
580 } elseif( $type == Block::TYPE_IP ){
581 $target = $target->getName();
582 $userId = 0;
583 } else {
584 # This should have been caught in the form field validation
585 return array( 'badipaddress' );
586 }
587
588 if( ( strlen( $data['Expiry'] ) == 0) || ( strlen( $data['Expiry'] ) > 50 )
589 || !self::parseExpiryInput( $data['Expiry'] ) )
590 {
591 return array( 'ipb_expiry_invalid' );
592 }
593
594 if( !isset( $data['DisableEmail'] ) ){
595 $data['DisableEmail'] = false;
596 }
597
598 # If the user has done the form 'properly', they won't even have been given the
599 # option to suppress-block unless they have the 'hideuser' permission
600 if( !isset( $data['HideUser'] ) ){
601 $data['HideUser'] = false;
602 }
603
604 if( $data['HideUser'] ) {
605 if( !$performer->isAllowed('hideuser') ){
606 # this codepath is unreachable except by a malicious user spoofing forms,
607 # or by race conditions (user has oversight and sysop, loads block form,
608 # and is de-oversighted before submission); so need to fail completely
609 # rather than just silently disable hiding
610 return array( 'badaccess-group0' );
611 }
612
613 # Recheck params here...
614 if( $type != Block::TYPE_USER ) {
615 $data['HideUser'] = false; # IP users should not be hidden
616 } elseif( !in_array( $data['Expiry'], array( 'infinite', 'infinity', 'indefinite' ) ) ) {
617 # Bad expiry.
618 return array( 'ipb_expiry_temp' );
619 } elseif( $user->getEditCount() > self::HIDEUSER_CONTRIBLIMIT ) {
620 # Typically, the user should have a handful of edits.
621 # Disallow hiding users with many edits for performance.
622 return array( 'ipb_hide_invalid' );
623 } elseif( !$data['Confirm'] ){
624 return array( 'ipb-confirmhideuser' );
625 }
626 }
627
628 # Create block object.
629 $block = new Block();
630 $block->setTarget( $target );
631 $block->setBlocker( $performer );
632 $block->mReason = $data['Reason'][0];
633 $block->mExpiry = self::parseExpiryInput( $data['Expiry'] );
634 $block->prevents( 'createaccount', $data['CreateAccount'] );
635 $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit || $data['DisableUTEdit'] ) );
636 $block->prevents( 'sendemail', $data['DisableEmail'] );
637 $block->isHardblock( $data['HardBlock'] );
638 $block->isAutoblocking( $data['AutoBlock'] );
639 $block->mHideName = $data['HideUser'];
640
641 if( !wfRunHooks( 'BlockIp', array( &$block, &$performer ) ) ) {
642 return array( 'hookaborted' );
643 }
644
645 # Try to insert block. Is there a conflicting block?
646 $status = $block->insert();
647 if( !$status ) {
648 # Show form unless the user is already aware of this...
649 if( !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
650 && $data['PreviousTarget'] !== $target ) )
651 {
652 return array( array( 'ipb_already_blocked', $block->getTarget() ) );
653 # Otherwise, try to update the block...
654 } else {
655 # This returns direct blocks before autoblocks/rangeblocks, since we should
656 # be sure the user is blocked by now it should work for our purposes
657 $currentBlock = Block::newFromTarget( $target );
658
659 if( $block->equals( $currentBlock ) ) {
660 return array( array( 'ipb_already_blocked', $block->getTarget() ) );
661 }
662
663 # If the name was hidden and the blocking user cannot hide
664 # names, then don't allow any block changes...
665 if( $currentBlock->mHideName && !$performer->isAllowed( 'hideuser' ) ) {
666 return array( 'cant-see-hidden-user' );
667 }
668
669 $currentBlock->delete();
670 $status = $block->insert();
671 $logaction = 'reblock';
672
673 # Unset _deleted fields if requested
674 if( $currentBlock->mHideName && !$data['HideUser'] ) {
675 RevisionDeleteUser::unsuppressUserName( $target, $userId );
676 }
677
678 # If hiding/unhiding a name, this should go in the private logs
679 if( (bool)$currentBlock->mHideName ){
680 $data['HideUser'] = true;
681 }
682 }
683 } else {
684 $logaction = 'block';
685 }
686
687 wfRunHooks( 'BlockIpComplete', array( $block, $performer ) );
688
689 # Set *_deleted fields if requested
690 if( $data['HideUser'] ) {
691 RevisionDeleteUser::suppressUserName( $target, $userId );
692 }
693
694 # Can't watch a rangeblock
695 if( $type != Block::TYPE_RANGE && $data['Watch'] ) {
696 $performer->addWatch( Title::makeTitle( NS_USER, $target ) );
697 }
698
699 # Block constructor sanitizes certain block options on insert
700 $data['BlockEmail'] = $block->prevents( 'sendemail' );
701 $data['AutoBlock'] = $block->isAutoblocking();
702
703 # Prepare log parameters
704 $logParams = array();
705 $logParams[] = $data['Expiry'];
706 $logParams[] = self::blockLogFlags( $data, $type );
707
708 # Make log entry, if the name is hidden, put it in the oversight log
709 $log_type = $data['HideUser'] ? 'suppress' : 'block';
710 $log = new LogPage( $log_type );
711 $log_id = $log->addEntry(
712 $logaction,
713 Title::makeTitle( NS_USER, $target ),
714 $data['Reason'][0],
715 $logParams
716 );
717 # Relate log ID to block IDs (bug 25763)
718 $blockIds = array_merge( array( $status['id'] ), $status['autoIds'] );
719 $log->addRelations( 'ipb_id', $blockIds, $log_id );
720
721 # Report to the user
722 return true;
723 }
724
725 /**
726 * Get an array of suggested block durations from MediaWiki:Ipboptions
727 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
728 * to the standard "**<duration>|<displayname>" format?
729 * @param $lang Language|null the language to get the durations in, or null to use
730 * the wiki's content language
731 * @return Array
732 */
733 public static function getSuggestedDurations( $lang = null ){
734 $a = array();
735 $msg = $lang === null
736 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
737 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
738
739 if( $msg == '-' ){
740 return array();
741 }
742
743 foreach( explode( ',', $msg ) as $option ) {
744 if( strpos( $option, ':' ) === false ){
745 $option = "$option:$option";
746 }
747
748 list( $show, $value ) = explode( ':', $option );
749 $a[htmlspecialchars( $show )] = htmlspecialchars( $value );
750 }
751
752 return $a;
753 }
754
755 /**
756 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
757 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
758 * @param $expiry String: whatever was typed into the form
759 * @return String: timestamp or "infinity" string for the DB implementation
760 */
761 public static function parseExpiryInput( $expiry ) {
762 static $infinity;
763 if( $infinity == null ){
764 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
765 }
766
767 if ( $expiry == 'infinite' || $expiry == 'indefinite' ) {
768 $expiry = $infinity;
769 } else {
770 $expiry = strtotime( $expiry );
771
772 if ( $expiry < 0 || $expiry === false ) {
773 return false;
774 }
775
776 $expiry = wfTimestamp( TS_MW, $expiry );
777 }
778
779 return $expiry;
780 }
781
782 /**
783 * Can we do an email block?
784 * @param $user User: the sysop wanting to make a block
785 * @return Boolean
786 */
787 public static function canBlockEmail( $user ) {
788 global $wgEnableUserEmail, $wgSysopEmailBans;
789
790 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
791 }
792
793 /**
794 * bug 15810: blocked admins should not be able to block/unblock
795 * others, and probably shouldn't be able to unblock themselves
796 * either.
797 * @param $user User|Int|String
798 * @param $performer User user doing the request
799 * @return Bool|String true or error message key
800 */
801 public static function checkUnblockSelf( $user, User $performer ) {
802 if ( is_int( $user ) ) {
803 $user = User::newFromId( $user );
804 } elseif ( is_string( $user ) ) {
805 $user = User::newFromName( $user );
806 }
807
808 if( $performer->isBlocked() ){
809 if( $user instanceof User && $user->getId() == $performer->getId() ) {
810 # User is trying to unblock themselves
811 if ( $performer->isAllowed( 'unblockself' ) ) {
812 return true;
813 # User blocked themselves and is now trying to reverse it
814 } elseif ( $performer->blockedBy() === $performer->getName() ) {
815 return true;
816 } else {
817 return 'ipbnounblockself';
818 }
819 } else {
820 # User is trying to block/unblock someone else
821 return 'ipbblocked';
822 }
823 } else {
824 return true;
825 }
826 }
827
828 /**
829 * Return a comma-delimited list of "flags" to be passed to the log
830 * reader for this block, to provide more information in the logs
831 * @param $data Array from HTMLForm data
832 * @param $type Block::TYPE_ constant (USER, RANGE, or IP)
833 * @return array
834 */
835 protected static function blockLogFlags( array $data, $type ) {
836 global $wgBlockAllowsUTEdit;
837 $flags = array();
838
839 # when blocking a user the option 'anononly' is not available/has no effect -> do not write this into log
840 if( !$data['HardBlock'] && $type != Block::TYPE_USER ){
841 // For grepping: message block-log-flags-anononly
842 $flags[] = 'anononly';
843 }
844
845 if( $data['CreateAccount'] ){
846 // For grepping: message block-log-flags-nocreate
847 $flags[] = 'nocreate';
848 }
849
850 # Same as anononly, this is not displayed when blocking an IP address
851 if( !$data['AutoBlock'] && $type == Block::TYPE_USER ){
852 // For grepping: message block-log-flags-noautoblock
853 $flags[] = 'noautoblock';
854 }
855
856 if( $data['DisableEmail'] ){
857 // For grepping: message block-log-flags-noemail
858 $flags[] = 'noemail';
859 }
860
861 if( $wgBlockAllowsUTEdit && $data['DisableUTEdit'] ){
862 // For grepping: message block-log-flags-nousertalk
863 $flags[] = 'nousertalk';
864 }
865
866 if( $data['HideUser'] ){
867 // For grepping: message block-log-flags-hiddenname
868 $flags[] = 'hiddenname';
869 }
870
871 return implode( ',', $flags );
872 }
873
874 /**
875 * Process the form on POST submission.
876 * @param $data Array
877 * @return Bool|Array true for success, false for didn't-try, array of errors on failure
878 */
879 public function onSubmit( array $data ) {
880 // This isn't used since we need that HTMLForm that's passed in the
881 // second parameter. See alterForm for the real function
882 }
883
884 /**
885 * Do something exciting on successful processing of the form, most likely to show a
886 * confirmation message
887 */
888 public function onSuccess() {
889 $out = $this->getOutput();
890 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
891 $out->addWikiMsg( 'blockipsuccesstext', $this->target );
892 }
893 }
894
895 # BC @since 1.18
896 class IPBlockForm extends SpecialBlock {}