1e2fd5eea3c558e8b924117005b473fbafb8c1b1
[lhc/web/wiklou.git] / includes / specials / SpecialBlockip.php
1 <?php
2 /**
3 * Implements Special:Blockip
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 IPBlockForm extends SpecialPage {
31 var $BlockAddress, $BlockExpiry, $BlockReason, $BlockReasonList, $BlockOther, $BlockAnonOnly, $BlockCreateAccount,
32 $BlockEnableAutoblock, $BlockEmail, $BlockHideName, $BlockAllowUsertalk, $BlockReblock, $BlockWatchUser;
33 // The maximum number of edits a user can have and still be hidden
34 const HIDEUSER_CONTRIBLIMIT = 1000;
35
36 public function __construct() {
37 parent::__construct( 'Blockip', 'block' );
38 }
39
40 public function execute( $par ) {
41 global $wgUser, $wgOut, $wgRequest;
42
43 # Can't block when the database is locked
44 if( wfReadOnly() ) {
45 $wgOut->readOnlyPage();
46 return;
47 }
48 # Permission check
49 if( !$this->userCanExecute( $wgUser ) ) {
50 $wgOut->permissionRequired( 'block' );
51 return;
52 }
53
54 $this->setup( $par );
55
56 # bug 15810: blocked admins should have limited access here
57 if ( $wgUser->isBlocked() ) {
58 $status = IPBlockForm::checkUnblockSelf( $this->BlockAddress );
59 if ( $status !== true ) {
60 throw new ErrorPageError( 'badaccess', $status );
61 }
62 }
63
64 $action = $wgRequest->getVal( 'action' );
65 if( 'success' == $action ) {
66 $this->showSuccess();
67 } elseif( $wgRequest->wasPosted() && 'submit' == $action &&
68 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) ) ) {
69 $this->doSubmit();
70 } else {
71 $this->showForm( '' );
72 }
73 }
74
75 private function setup( $par ) {
76 global $wgRequest, $wgUser, $wgBlockAllowsUTEdit;
77
78 $this->BlockAddress = $wgRequest->getVal( 'wpBlockAddress', $wgRequest->getVal( 'ip', $par ) );
79 $this->BlockAddress = strtr( $this->BlockAddress, '_', ' ' );
80 $this->BlockReason = $wgRequest->getText( 'wpBlockReason' );
81 $this->BlockReasonList = $wgRequest->getText( 'wpBlockReasonList' );
82 $this->BlockExpiry = $wgRequest->getVal( 'wpBlockExpiry', wfMsg( 'ipbotheroption' ) );
83 $this->BlockOther = $wgRequest->getVal( 'wpBlockOther', '' );
84
85 # Unchecked checkboxes are not included in the form data at all, so having one
86 # that is true by default is a bit tricky
87 $byDefault = !$wgRequest->wasPosted();
88 $this->BlockAnonOnly = $wgRequest->getBool( 'wpAnonOnly', $byDefault );
89 $this->BlockCreateAccount = $wgRequest->getBool( 'wpCreateAccount', $byDefault );
90 $this->BlockEnableAutoblock = $wgRequest->getBool( 'wpEnableAutoblock', $byDefault );
91 $this->BlockEmail = false;
92 if( self::canBlockEmail( $wgUser ) ) {
93 $this->BlockEmail = $wgRequest->getBool( 'wpEmailBan', false );
94 }
95 $this->BlockWatchUser = $wgRequest->getBool( 'wpWatchUser', false ) && $wgUser->isLoggedIn();
96 # Re-check user's rights to hide names, very serious, defaults to null
97 if( $wgUser->isAllowed( 'hideuser' ) ) {
98 $this->BlockHideName = $wgRequest->getBool( 'wpHideName', null );
99 } else {
100 $this->BlockHideName = false;
101 }
102 $this->BlockAllowUsertalk = ( $wgRequest->getBool( 'wpAllowUsertalk', $byDefault ) && $wgBlockAllowsUTEdit );
103 $this->BlockReblock = $wgRequest->getBool( 'wpChangeBlock', false );
104
105 $this->wasPosted = $wgRequest->wasPosted();
106 }
107
108 public function showForm( $err ) {
109 global $wgOut, $wgUser, $wgSysopUserBans;
110
111 $wgOut->setPageTitle( wfMsg( 'blockip-title' ) );
112 $wgOut->addWikiMsg( 'blockiptext' );
113
114 if( $wgSysopUserBans ) {
115 $mIpaddress = Xml::label( wfMsg( 'ipadressorusername' ), 'mw-bi-target' );
116 } else {
117 $mIpaddress = Xml::label( wfMsg( 'ipaddress' ), 'mw-bi-target' );
118 }
119 $mIpbexpiry = Xml::label( wfMsg( 'ipbexpiry' ), 'wpBlockExpiry' );
120 $mIpbother = Xml::label( wfMsg( 'ipbother' ), 'mw-bi-other' );
121 $mIpbreasonother = Xml::label( wfMsg( 'ipbreason' ), 'wpBlockReasonList' );
122 $mIpbreason = Xml::label( wfMsg( 'ipbotherreason' ), 'mw-bi-reason' );
123
124 $titleObj = SpecialPage::getTitleFor( 'Blockip' );
125 $user = User::newFromName( $this->BlockAddress );
126 if ( is_object( $user ) || User::isIP( $this->BlockAddress ) ) {
127 $wgUser->getSkin()->setRelevantUser( is_object($user) ? $user : User::newFromName( $this->BlockAddress, false ) );
128 }
129
130 $alreadyBlocked = false;
131 $otherBlockedMsgs = array();
132 if( $err && $err[0] != 'ipb_already_blocked' ) {
133 $key = array_shift( $err );
134 $msg = wfMsgExt( $key, 'parsemag', $err );
135 $wgOut->setSubtitle( wfMsgHtml( 'formerror' ) );
136 $wgOut->addHTML( Xml::tags( 'p', array( 'class' => 'error' ), $msg ) );
137 } elseif( $this->BlockAddress !== null ) {
138 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
139 wfRunHooks( 'OtherBlockLogLink', array( &$otherBlockedMsgs, $this->BlockAddress ) );
140
141 $userId = is_object( $user ) ? $user->getId() : 0;
142 $currentBlock = Block::newFromDB( $this->BlockAddress, $userId );
143 if( !is_null( $currentBlock ) && !$currentBlock->mAuto && # The block exists and isn't an autoblock
144 ( $currentBlock->mRangeStart == $currentBlock->mRangeEnd || # The block isn't a rangeblock
145 # or if it is, the range is what we're about to block
146 ( $currentBlock->mAddress == $this->BlockAddress ) )
147 ) {
148 $alreadyBlocked = true;
149 # Set the block form settings to the existing block
150 if( !$this->wasPosted ) {
151 $this->BlockAnonOnly = $currentBlock->mAnonOnly;
152 $this->BlockCreateAccount = $currentBlock->mCreateAccount;
153 $this->BlockEnableAutoblock = $currentBlock->mEnableAutoblock;
154 $this->BlockEmail = $currentBlock->mBlockEmail;
155 $this->BlockHideName = $currentBlock->mHideName;
156 $this->BlockAllowUsertalk = $currentBlock->mAllowUsertalk;
157 if( $currentBlock->mExpiry == 'infinity' ) {
158 $this->BlockOther = 'indefinite';
159 } else {
160 $this->BlockOther = wfTimestamp( TS_ISO_8601, $currentBlock->mExpiry );
161 }
162 $this->BlockReason = $currentBlock->mReason;
163 }
164 }
165 }
166
167 # Show other blocks from extensions, i.e. GlockBlocking and TorBlock
168 if( count( $otherBlockedMsgs ) ) {
169 $wgOut->addHTML(
170 Html::rawElement( 'h2', array(), wfMsgExt( 'ipb-otherblocks-header', 'parseinline', count( $otherBlockedMsgs ) ) ) . "\n"
171 );
172 $list = '';
173 foreach( $otherBlockedMsgs as $link ) {
174 $list .= Html::rawElement( 'li', array(), $link ) . "\n";
175 }
176 $wgOut->addHTML( Html::rawElement( 'ul', array( 'class' => 'mw-blockip-alreadyblocked' ), $list ) . "\n" );
177 }
178
179 # Username/IP is blocked already locally
180 if( $alreadyBlocked ) {
181 $wgOut->wrapWikiMsg( "<div class='mw-ipb-needreblock'>\n$1\n</div>", array( 'ipb-needreblock', $this->BlockAddress ) );
182 }
183
184 $scBlockExpiryOptions = wfMsgForContent( 'ipboptions' );
185
186 $showblockoptions = $scBlockExpiryOptions != '-';
187 if( !$showblockoptions ) $mIpbother = $mIpbexpiry;
188
189 $blockExpiryFormOptions = Xml::option( wfMsg( 'ipbotheroption' ), 'other' );
190 foreach( explode( ',', $scBlockExpiryOptions ) as $option ) {
191 if( strpos( $option, ':' ) === false ) $option = "$option:$option";
192 list( $show, $value ) = explode( ':', $option );
193 $show = htmlspecialchars( $show );
194 $value = htmlspecialchars( $value );
195 $blockExpiryFormOptions .= Xml::option( $show, $value, $this->BlockExpiry === $value ) . "\n";
196 }
197
198 $reasonDropDown = Xml::listDropDown( 'wpBlockReasonList',
199 wfMsgForContent( 'ipbreason-dropdown' ),
200 wfMsgForContent( 'ipbreasonotherlist' ), $this->BlockReasonList, 'wpBlockDropDown', 4 );
201
202 # FIXME: this should actually use HTMLForm, not just some of its JavaScript
203 $wgOut->addModules( array( 'mediawiki.special.block', 'mediawiki.htmlform' ) );
204
205 $wgOut->addHTML(
206 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ), 'id' => 'blockip' ) ) .
207 Xml::openElement( 'fieldset' ) .
208 Xml::element( 'legend', null, wfMsg( 'blockip-legend' ) ) .
209 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-blockip-table' ) ) .
210 "<tr>
211 <td class='mw-label'>
212 {$mIpaddress}
213 </td>
214 <td class='mw-input'>" .
215 Html::input( 'wpBlockAddress', $this->BlockAddress, 'text', array(
216 'tabindex' => '1',
217 'id' => 'mw-bi-target',
218 'size' => '45',
219 'required' => ''
220 ) + ( $this->BlockAddress ? array() : array( 'autofocus' ) ) ). "
221 </td>
222 </tr>
223 <tr>
224 <td class='mw-label'>
225 {$mIpbexpiry}
226 </td>
227 <td class='mw-input'>"
228 );
229 if( $showblockoptions ) {
230 $wgOut->addHTML(
231 Xml::tags( 'select',
232 array(
233 'id' => 'wpBlockExpiry',
234 'name' => 'wpBlockExpiry',
235 'class' => 'mw-htmlform-select-or-other', # FIXME: actually make this use HTMLForm
236 'tabindex' => '2' ),
237 $blockExpiryFormOptions
238 ) . "<br/>\n"
239 );
240 }
241 $wgOut->addHTML(
242 Xml::input(
243 'wpBlockOther',
244 45,
245 $this->BlockOther,
246 array(
247 'tabindex' => '3',
248 'id' => 'wpBlockExpiry-other'
249 )
250 ) . "
251 </td>
252 </tr>
253 <tr>
254 <td class='mw-label'>
255 {$mIpbreasonother}
256 </td>
257 <td class='mw-input'>
258 {$reasonDropDown}
259 </td>
260 </tr>
261 <tr id=\"wpBlockReason\">
262 <td class='mw-label'>
263 {$mIpbreason}
264 </td>
265 <td class='mw-input'>" .
266 Html::input( 'wpBlockReason', $this->BlockReason, 'text', array(
267 'tabindex' => '5',
268 'id' => 'mw-bi-reason',
269 'maxlength' => '200',
270 'size' => '45'
271 ) + ( $this->BlockAddress ? array( 'autofocus' ) : array() ) ) . "
272 </td>
273 </tr>
274 <tr id='wpCreateAccountRow'>
275 <td>&#160;</td>
276 <td class='mw-input'>" .
277 Xml::checkLabel( wfMsg( 'ipbcreateaccount' ),
278 'wpCreateAccount', 'wpCreateAccount', $this->BlockCreateAccount,
279 array( 'tabindex' => '7' ) ) . "
280 </td>
281 </tr>"
282 );
283
284 if( self::canBlockEmail( $wgUser ) ) {
285 $wgOut->addHTML("
286 <tr id='wpEnableEmailBan'>
287 <td>&#160;</td>
288 <td class='mw-input'>" .
289 Xml::checkLabel( wfMsg( 'ipbemailban' ),
290 'wpEmailBan', 'wpEmailBan', $this->BlockEmail,
291 array( 'tabindex' => '9' ) ) . "
292 </td>
293 </tr>"
294 );
295 }
296
297 # Can we explicitly disallow the use of user_talk?
298 global $wgBlockAllowsUTEdit;
299 if( $wgBlockAllowsUTEdit ){
300 $wgOut->addHTML("
301 <tr id='wpAllowUsertalkRow'>
302 <td>&#160;</td>
303 <td class='mw-input'>" .
304 Xml::checkLabel( wfMsg( 'ipballowusertalk' ),
305 'wpAllowUsertalk', 'wpAllowUsertalk', $this->BlockAllowUsertalk,
306 array( 'tabindex' => '12' ) ) . "
307 </td>
308 </tr>"
309 );
310 }
311
312 $wgOut->addHTML( "
313 <tr id='wpEnableAutoblockRow'>
314 <td>&#160;</td>
315 <td class='mw-input'>" .
316 Xml::checkLabel( wfMsg( 'ipbenableautoblock' ),
317 'wpEnableAutoblock', 'wpEnableAutoblock', $this->BlockEnableAutoblock,
318 array( 'tabindex' => '8' ) ) . "
319 </td>
320 </tr>"
321 );
322
323 // Allow some users to hide name from block log, blocklist and listusers
324 if( $wgUser->isAllowed( 'hideuser' ) ) {
325 $wgOut->addHTML("
326 <tr id='wpEnableHideUser'>
327 <td>&#160;</td>
328 <td class='mw-input'><strong>" .
329 Xml::checkLabel( wfMsg( 'ipbhidename' ),
330 'wpHideName', 'wpHideName', $this->BlockHideName,
331 array( 'tabindex' => '10' )
332 ) . "
333 </strong></td>
334 </tr>"
335 );
336 }
337
338 # Watchlist their user page? (Only if user is logged in)
339 if( $wgUser->isLoggedIn() ) {
340 $wgOut->addHTML("
341 <tr id='wpEnableWatchUser'>
342 <td>&#160;</td>
343 <td class='mw-input'>" .
344 Xml::checkLabel( wfMsg( 'ipbwatchuser' ),
345 'wpWatchUser', 'wpWatchUser', $this->BlockWatchUser,
346 array( 'tabindex' => '11' ) ) . "
347 </td>
348 </tr>"
349 );
350 }
351
352 $wgOut->addHTML("
353 <tr id='wpAnonOnlyRow'>
354 <td>&#160;</td>
355 <td class='mw-input'>" .
356 Xml::checkLabel( wfMsg( 'ipbanononly' ),
357 'wpAnonOnly', 'wpAnonOnly', $this->BlockAnonOnly,
358 array( 'tabindex' => '6' ) ) . "
359 </td>
360 </tr>
361 <tr>
362 <td style='padding-top: 1em'>&#160;</td>
363 <td class='mw-submit' style='padding-top: 1em'>" .
364 Xml::submitButton( wfMsg( $alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit' ),
365 array( 'name' => 'wpBlock', 'tabindex' => '13' )
366 + $wgUser->getSkin()->tooltipAndAccessKeyAttribs( 'blockip-block' ) ). "
367 </td>
368 </tr>" .
369 Xml::closeElement( 'table' ) .
370 Html::hidden( 'wpEditToken', $wgUser->editToken() ) .
371 ( $alreadyBlocked ? Html::hidden( 'wpChangeBlock', 1 ) : "" ) .
372 Xml::closeElement( 'fieldset' ) .
373 Xml::closeElement( 'form' )
374 );
375
376 $wgOut->addHTML( $this->getConvenienceLinks() );
377
378 if( is_object( $user ) ) {
379 $this->showLogFragment( $wgOut, $user->getUserPage() );
380 } elseif( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $this->BlockAddress ) ) {
381 $this->showLogFragment( $wgOut, Title::makeTitle( NS_USER, $this->BlockAddress ) );
382 } elseif( preg_match( '/^\w{1,4}:\w{1,4}:\w{1,4}:\w{1,4}:\w{1,4}:\w{1,4}:\w{1,4}:\w{1,4}/', $this->BlockAddress ) ) {
383 $this->showLogFragment( $wgOut, Title::makeTitle( NS_USER, $this->BlockAddress ) );
384 }
385 }
386
387 /**
388 * Can we do an email block?
389 * @param $user User: the sysop wanting to make a block
390 * @return Boolean
391 */
392 public static function canBlockEmail( $user ) {
393 global $wgEnableUserEmail, $wgSysopEmailBans;
394 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
395 }
396
397 /**
398 * bug 15810: blocked admins should not be able to block/unblock
399 * others, and probably shouldn't be able to unblock themselves
400 * either.
401 * @param $user User, Int or String
402 */
403 public static function checkUnblockSelf( $user ) {
404 global $wgUser;
405 if ( is_int( $user ) ) {
406 $user = User::newFromId( $user );
407 } elseif ( is_string( $user ) ) {
408 $user = User::newFromName( $user );
409 }
410 if( $user instanceof User && $user->getId() == $wgUser->getId() ) {
411 # User is trying to unblock themselves
412 if ( $wgUser->isAllowed( 'unblockself' ) ) {
413 return true;
414 } else {
415 return 'ipbnounblockself';
416 }
417 } else {
418 # User is trying to block/unblock someone else
419 return 'ipbblocked';
420 }
421 }
422
423 /**
424 * Backend block code.
425 * $userID and $expiry will be filled accordingly
426 * @return array(message key, arguments) on failure, empty array on success
427 */
428 function doBlock( &$userId = null, &$expiry = null ) {
429 global $wgUser, $wgSysopUserBans, $wgSysopRangeBans, $wgBlockAllowsUTEdit, $wgBlockCIDRLimit;
430
431 $userId = 0;
432 # Expand valid IPv6 addresses, usernames are left as is
433 $this->BlockAddress = IP::sanitizeIP( $this->BlockAddress );
434 # isIPv4() and IPv6() are used for final validation
435 $rxIP4 = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
436 $rxIP6 = '\w{1,4}:\w{1,4}:\w{1,4}:\w{1,4}:\w{1,4}:\w{1,4}:\w{1,4}:\w{1,4}';
437 $rxIP = "($rxIP4|$rxIP6)";
438
439 # Check for invalid specifications
440 if( !preg_match( "/^$rxIP$/", $this->BlockAddress ) ) {
441 $matches = array();
442 if( preg_match( "/^($rxIP4)\\/(\\d{1,2})$/", $this->BlockAddress, $matches ) ) {
443 # IPv4
444 if( $wgSysopRangeBans ) {
445 if( !IP::isIPv4( $this->BlockAddress ) || $matches[2] > 32 ) {
446 return array( 'ip_range_invalid' );
447 } elseif ( $matches[2] < $wgBlockCIDRLimit['IPv4'] ) {
448 return array( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
449 }
450 $this->BlockAddress = Block::normaliseRange( $this->BlockAddress );
451 } else {
452 # Range block illegal
453 return array( 'range_block_disabled' );
454 }
455 } elseif( preg_match( "/^($rxIP6)\\/(\\d{1,3})$/", $this->BlockAddress, $matches ) ) {
456 # IPv6
457 if( $wgSysopRangeBans ) {
458 if( !IP::isIPv6( $this->BlockAddress ) || $matches[2] > 128 ) {
459 return array( 'ip_range_invalid' );
460 } elseif( $matches[2] < $wgBlockCIDRLimit['IPv6'] ) {
461 return array( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
462 }
463 $this->BlockAddress = Block::normaliseRange( $this->BlockAddress );
464 } else {
465 # Range block illegal
466 return array('range_block_disabled');
467 }
468 } else {
469 # Username block
470 if( $wgSysopUserBans ) {
471 $user = User::newFromName( $this->BlockAddress );
472 if( $user instanceof User && $user->getId() ) {
473 # Use canonical name
474 $userId = $user->getId();
475 $this->BlockAddress = $user->getName();
476 } else {
477 return array( 'nosuchusershort', htmlspecialchars( $user ? $user->getName() : $this->BlockAddress ) );
478 }
479 } else {
480 return array( 'badipaddress' );
481 }
482 }
483 }
484
485 if( $wgUser->isBlocked() && ( $wgUser->getId() !== $userId ) ) {
486 return array( 'cant-block-while-blocked' );
487 }
488
489 $reasonstr = $this->BlockReasonList;
490 if( $reasonstr != 'other' && $this->BlockReason != '' ) {
491 // Entry from drop down menu + additional comment
492 $reasonstr .= wfMsgForContent( 'colon-separator' ) . $this->BlockReason;
493 } elseif( $reasonstr == 'other' ) {
494 $reasonstr = $this->BlockReason;
495 }
496
497 $expirestr = $this->BlockExpiry;
498 if( $expirestr == 'other' )
499 $expirestr = $this->BlockOther;
500
501 if( ( strlen( $expirestr ) == 0) || ( strlen( $expirestr ) > 50 ) ) {
502 return array( 'ipb_expiry_invalid' );
503 }
504
505 if( false === ( $expiry = Block::parseExpiryInput( $expirestr ) ) ) {
506 // Bad expiry.
507 return array( 'ipb_expiry_invalid' );
508 }
509
510 if( $this->BlockHideName ) {
511 // Recheck params here...
512 if( !$userId || !$wgUser->isAllowed('hideuser') ) {
513 $this->BlockHideName = false; // IP users should not be hidden
514 } elseif( $expiry !== 'infinity' ) {
515 // Bad expiry.
516 return array( 'ipb_expiry_temp' );
517 } elseif( User::edits( $userId ) > self::HIDEUSER_CONTRIBLIMIT ) {
518 // Typically, the user should have a handful of edits.
519 // Disallow hiding users with many edits for performance.
520 return array( 'ipb_hide_invalid' );
521 }
522 }
523
524 # Create block object
525 # Note: for a user block, ipb_address is only for display purposes
526 $block = new Block( $this->BlockAddress, $userId, $wgUser->getId(),
527 $reasonstr, wfTimestampNow(), 0, $expiry, $this->BlockAnonOnly,
528 $this->BlockCreateAccount, $this->BlockEnableAutoblock, $this->BlockHideName,
529 $this->BlockEmail,
530 isset( $this->BlockAllowUsertalk ) ? $this->BlockAllowUsertalk : $wgBlockAllowsUTEdit
531 );
532
533 # Should this be privately logged?
534 $suppressLog = (bool)$this->BlockHideName;
535 if( wfRunHooks( 'BlockIp', array( &$block, &$wgUser ) ) ) {
536 # Try to insert block. Is there a conflicting block?
537 if( !$block->insert() ) {
538 # Show form unless the user is already aware of this...
539 if( !$this->BlockReblock ) {
540 return array( 'ipb_already_blocked' );
541 # Otherwise, try to update the block...
542 } else {
543 # This returns direct blocks before autoblocks/rangeblocks, since we should
544 # be sure the user is blocked by now it should work for our purposes
545 $currentBlock = Block::newFromDB( $this->BlockAddress, $userId );
546 if( $block->equals( $currentBlock ) ) {
547 return array( 'ipb_already_blocked' );
548 }
549 # If the name was hidden and the blocking user cannot hide
550 # names, then don't allow any block changes...
551 if( $currentBlock->mHideName && !$wgUser->isAllowed( 'hideuser' ) ) {
552 return array( 'cant-see-hidden-user' );
553 }
554 $currentBlock->delete();
555 $block->insert();
556 # If hiding/unhiding a name, this should go in the private logs
557 $suppressLog = $suppressLog || (bool)$currentBlock->mHideName;
558 $log_action = 'reblock';
559 # Unset _deleted fields if requested
560 if( $currentBlock->mHideName && !$this->BlockHideName ) {
561 self::unsuppressUserName( $this->BlockAddress, $userId );
562 }
563 }
564 } else {
565 $log_action = 'block';
566 }
567 wfRunHooks( 'BlockIpComplete', array( $block, $wgUser ) );
568
569 # Set *_deleted fields if requested
570 if( $this->BlockHideName ) {
571 self::suppressUserName( $this->BlockAddress, $userId );
572 }
573
574 # Only show watch link when this is no range block
575 if( $this->BlockWatchUser && $block->mRangeStart == $block->mRangeEnd ) {
576 $wgUser->addWatch( Title::makeTitle( NS_USER, $this->BlockAddress ) );
577 }
578
579 # Block constructor sanitizes certain block options on insert
580 $this->BlockEmail = $block->mBlockEmail;
581 $this->BlockEnableAutoblock = $block->mEnableAutoblock;
582
583 # Prepare log parameters
584 $logParams = array();
585 $logParams[] = $expirestr;
586 $logParams[] = $this->blockLogFlags();
587
588 # Make log entry, if the name is hidden, put it in the oversight log
589 $log_type = $suppressLog ? 'suppress' : 'block';
590 $log = new LogPage( $log_type );
591 $log->addEntry( $log_action, Title::makeTitle( NS_USER, $this->BlockAddress ),
592 $reasonstr, $logParams );
593
594 # Report to the user
595 return array();
596 } else {
597 return array( 'hookaborted' );
598 }
599 }
600
601 public static function suppressUserName( $name, $userId, $dbw = null ) {
602 $op = '|'; // bitwise OR
603 return self::setUsernameBitfields( $name, $userId, $op, $dbw );
604 }
605
606 public static function unsuppressUserName( $name, $userId, $dbw = null ) {
607 $op = '&'; // bitwise AND
608 return self::setUsernameBitfields( $name, $userId, $op, $dbw );
609 }
610
611 private static function setUsernameBitfields( $name, $userId, $op, $dbw ) {
612 if( $op !== '|' && $op !== '&' ) return false; // sanity check
613 if( !$dbw )
614 $dbw = wfGetDB( DB_MASTER );
615 $delUser = Revision::DELETED_USER | Revision::DELETED_RESTRICTED;
616 $delAction = LogPage::DELETED_ACTION | Revision::DELETED_RESTRICTED;
617 # Normalize user name
618 $userTitle = Title::makeTitleSafe( NS_USER, $name );
619 $userDbKey = $userTitle->getDBkey();
620 # To suppress, we OR the current bitfields with Revision::DELETED_USER
621 # to put a 1 in the username *_deleted bit. To unsuppress we AND the
622 # current bitfields with the inverse of Revision::DELETED_USER. The
623 # username bit is made to 0 (x & 0 = 0), while others are unchanged (x & 1 = x).
624 # The same goes for the sysop-restricted *_deleted bit.
625 if( $op == '&' ) {
626 $delUser = "~{$delUser}";
627 $delAction = "~{$delAction}";
628 }
629 # Hide name from live edits
630 $dbw->update( 'revision', array( "rev_deleted = rev_deleted $op $delUser" ),
631 array( 'rev_user' => $userId ), __METHOD__ );
632 # Hide name from deleted edits
633 $dbw->update( 'archive', array( "ar_deleted = ar_deleted $op $delUser" ),
634 array( 'ar_user_text' => $name ), __METHOD__ );
635 # Hide name from logs
636 $dbw->update( 'logging', array( "log_deleted = log_deleted $op $delUser" ),
637 array( 'log_user' => $userId, "log_type != 'suppress'" ), __METHOD__ );
638 $dbw->update( 'logging', array( "log_deleted = log_deleted $op $delAction" ),
639 array( 'log_namespace' => NS_USER, 'log_title' => $userDbKey,
640 "log_type != 'suppress'" ), __METHOD__ );
641 # Hide name from RC
642 $dbw->update( 'recentchanges', array( "rc_deleted = rc_deleted $op $delUser" ),
643 array( 'rc_user_text' => $name ), __METHOD__ );
644 $dbw->update( 'recentchanges', array( "rc_deleted = rc_deleted $op $delAction" ),
645 array( 'rc_namespace' => NS_USER, 'rc_title' => $userDbKey, 'rc_logid > 0' ), __METHOD__ );
646 # Hide name from live images
647 $dbw->update( 'oldimage', array( "oi_deleted = oi_deleted $op $delUser" ),
648 array( 'oi_user_text' => $name ), __METHOD__ );
649 # Hide name from deleted images
650 # WMF - schema change pending
651 # $dbw->update( 'filearchive', array( "fa_deleted = fa_deleted $op $delUser" ),
652 # array( 'fa_user_text' => $name ), __METHOD__ );
653 # Done!
654 return true;
655 }
656
657 /**
658 * UI entry point for blocking
659 * Wraps around doBlock()
660 */
661 public function doSubmit() {
662 global $wgOut;
663 $retval = $this->doBlock();
664 if( empty( $retval ) ) {
665 $titleObj = SpecialPage::getTitleFor( 'Blockip' );
666 $wgOut->redirect( $titleObj->getFullURL( 'action=success&ip=' .
667 urlencode( $this->BlockAddress ) ) );
668 return;
669 }
670 $this->showForm( $retval );
671 }
672
673 public function showSuccess() {
674 global $wgOut;
675
676 $wgOut->setPageTitle( wfMsg( 'blockip-title' ) );
677 $wgOut->setSubtitle( wfMsg( 'blockipsuccesssub' ) );
678 $text = wfMsgExt( 'blockipsuccesstext', array( 'parse' ), $this->BlockAddress );
679 $wgOut->addHTML( $text );
680 }
681
682 private function showLogFragment( $out, $title ) {
683 global $wgUser;
684
685 // Used to support GENDER in 'blocklog-showlog' and 'blocklog-showsuppresslog'
686 $userBlocked = $title->getText();
687
688 LogEventsList::showLogExtract(
689 $out,
690 'block',
691 $title->getPrefixedText(),
692 '',
693 array(
694 'lim' => 10,
695 'msgKey' => array(
696 'blocklog-showlog',
697 $userBlocked
698 ),
699 'showIfEmpty' => false
700 )
701 );
702
703 // Add suppression block entries if allowed
704 if( $wgUser->isAllowed( 'suppressionlog' ) ) {
705 LogEventsList::showLogExtract( $out, 'suppress', $title->getPrefixedText(), '',
706 array(
707 'lim' => 10,
708 'conds' => array(
709 'log_action' => array(
710 'block',
711 'reblock',
712 'unblock'
713 )
714 ),
715 'msgKey' => array(
716 'blocklog-showsuppresslog',
717 $userBlocked
718 ),
719 'showIfEmpty' => false
720 )
721 );
722 }
723 }
724
725 /**
726 * Return a comma-delimited list of "flags" to be passed to the log
727 * reader for this block, to provide more information in the logs
728 *
729 * @return array
730 */
731 private function blockLogFlags() {
732 global $wgBlockAllowsUTEdit;
733 $flags = array();
734 if( $this->BlockAnonOnly && IP::isIPAddress( $this->BlockAddress ) )
735 // when blocking a user the option 'anononly' is not available/has no effect -> do not write this into log
736 $flags[] = 'anononly';
737 if( $this->BlockCreateAccount )
738 $flags[] = 'nocreate';
739 if( !$this->BlockEnableAutoblock && !IP::isIPAddress( $this->BlockAddress ) )
740 // Same as anononly, this is not displayed when blocking an IP address
741 $flags[] = 'noautoblock';
742 if( $this->BlockEmail )
743 $flags[] = 'noemail';
744 if( !$this->BlockAllowUsertalk && $wgBlockAllowsUTEdit )
745 $flags[] = 'nousertalk';
746 if( $this->BlockHideName )
747 $flags[] = 'hiddenname';
748 return implode( ',', $flags );
749 }
750
751 /**
752 * Builds unblock and block list links
753 *
754 * @return string
755 */
756 private function getConvenienceLinks() {
757 global $wgUser, $wgLang;
758 $skin = $wgUser->getSkin();
759 if( $this->BlockAddress )
760 $links[] = $this->getContribsLink( $skin );
761 $links[] = $this->getUnblockLink( $skin );
762 $links[] = $this->getBlockListLink( $skin );
763 if ( $wgUser->isAllowed( 'editinterface' ) ) {
764 $title = Title::makeTitle( NS_MEDIAWIKI, 'Ipbreason-dropdown' );
765 $links[] = $skin->link(
766 $title,
767 wfMsgHtml( 'ipb-edit-dropdown' ),
768 array(),
769 array( 'action' => 'edit' )
770 );
771 }
772 return '<p class="mw-ipb-conveniencelinks">' . $wgLang->pipeList( $links ) . '</p>';
773 }
774
775 /**
776 * Build a convenient link to a user or IP's contribs
777 * form
778 *
779 * @param $skin Skin to use
780 * @return string
781 */
782 private function getContribsLink( $skin ) {
783 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->BlockAddress );
784 return $skin->link( $contribsPage, wfMsgExt( 'ipb-blocklist-contribs', 'escape', $this->BlockAddress ) );
785 }
786
787 /**
788 * Build a convenient link to unblock the given username or IP
789 * address, if available; otherwise link to a blank unblock
790 * form
791 *
792 * @param $skin Skin to use
793 * @return string
794 */
795 private function getUnblockLink( $skin ) {
796 $list = SpecialPage::getTitleFor( 'Ipblocklist' );
797 $query = array( 'action' => 'unblock' );
798
799 if( $this->BlockAddress ) {
800 $addr = strtr( $this->BlockAddress, '_', ' ' );
801 $message = wfMsg( 'ipb-unblock-addr', $addr );
802 $query['ip'] = $this->BlockAddress;
803 } else {
804 $message = wfMsg( 'ipb-unblock' );
805 }
806 return $skin->linkKnown(
807 $list,
808 htmlspecialchars( $message ),
809 array(),
810 $query
811 );
812 }
813
814 /**
815 * Build a convenience link to the block list
816 *
817 * @param $skin Skin to use
818 * @return string
819 */
820 private function getBlockListLink( $skin ) {
821 return $skin->linkKnown(
822 SpecialPage::getTitleFor( 'Ipblocklist' ),
823 wfMsg( 'ipb-blocklist' )
824 );
825 }
826
827 /**
828 * Block a list of selected users
829 *
830 * @param $users Array
831 * @param $reason String
832 * @param $tag String: replaces user pages
833 * @param $talkTag String: replaces user talk pages
834 * @return Array: list of html-safe usernames
835 */
836 public static function doMassUserBlock( $users, $reason = '', $tag = '', $talkTag = '' ) {
837 global $wgUser;
838 $counter = $blockSize = 0;
839 $safeUsers = array();
840 $log = new LogPage( 'block' );
841 foreach( $users as $name ) {
842 # Enforce limits
843 $counter++;
844 $blockSize++;
845 # Lets not go *too* fast
846 if( $blockSize >= 20 ) {
847 $blockSize = 0;
848 wfWaitForSlaves( 5 );
849 }
850 $u = User::newFromName( $name, false );
851 // If user doesn't exist, it ought to be an IP then
852 if( is_null( $u ) || ( !$u->getId() && !IP::isIPAddress( $u->getName() ) ) ) {
853 continue;
854 }
855 $userTitle = $u->getUserPage();
856 $userTalkTitle = $u->getTalkPage();
857 $userpage = new Article( $userTitle );
858 $usertalk = new Article( $userTalkTitle );
859 $safeUsers[] = '[[' . $userTitle->getPrefixedText() . '|' . $userTitle->getText() . ']]';
860 $expirestr = $u->getId() ? 'indefinite' : '1 week';
861 $expiry = Block::parseExpiryInput( $expirestr );
862 $anonOnly = IP::isIPAddress( $u->getName() ) ? 1 : 0;
863 // Create the block
864 $block = new Block( $u->getName(), // victim
865 $u->getId(), // uid
866 $wgUser->getId(), // blocker
867 $reason, // comment
868 wfTimestampNow(), // block time
869 0, // auto ?
870 $expiry, // duration
871 $anonOnly, // anononly?
872 1, // block account creation?
873 1, // autoblocking?
874 0, // suppress name?
875 0 // block from sending email?
876 );
877 $oldblock = Block::newFromDB( $u->getName(), $u->getId() );
878 if( !$oldblock ) {
879 $block->insert();
880 # Prepare log parameters
881 $logParams = array();
882 $logParams[] = $expirestr;
883 if( $anonOnly ) {
884 $logParams[] = 'anononly';
885 }
886 $logParams[] = 'nocreate';
887 # Add log entry
888 $log->addEntry( 'block', $userTitle, $reason, $logParams );
889 }
890 # Tag userpage! (check length to avoid mistakes)
891 if( strlen( $tag ) > 2 ) {
892 $userpage->doEdit( $tag, $reason, EDIT_MINOR );
893 }
894 if( strlen( $talkTag ) > 2 ) {
895 $usertalk->doEdit( $talkTag, $reason, EDIT_MINOR );
896 }
897 }
898 return $safeUsers;
899 }
900 }