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