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