(bug 28017) Unblocking a user with a space in their name does not work. This fix...
[lhc/web/wiklou.git] / includes / specials / SpecialIpblocklist.php
1 <?php
2 /**
3 * Implements Special:ipblocklist
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 lists existing blocks and allows users with the 'block'
26 * permission to remove blocks
27 *
28 * @ingroup SpecialPage
29 */
30 class IPUnblockForm extends SpecialPage {
31 var $ip, $reason, $id;
32 var $hideuserblocks, $hidetempblocks, $hideaddressblocks;
33
34 function __construct() {
35 parent::__construct( 'Ipblocklist' );
36 }
37
38 /**
39 * Main execution point
40 *
41 * @param $ip part of title: Special:Ipblocklist/<ip>.
42 */
43 function execute( $ip ) {
44 global $wgUser, $wgOut, $wgRequest;
45
46 $this->setHeaders();
47 $this->outputHeader();
48
49 $ip = $wgRequest->getVal( 'ip', $ip );
50 $this->ip = trim( $wgRequest->getVal( 'wpUnblockAddress', $ip ) );
51 $this->id = $wgRequest->getVal( 'id' );
52 $this->reason = $wgRequest->getText( 'wpUnblockReason' );
53 $this->hideuserblocks = $wgRequest->getBool( 'hideuserblocks' );
54 $this->hidetempblocks = $wgRequest->getBool( 'hidetempblocks' );
55 $this->hideaddressblocks = $wgRequest->getBool( 'hideaddressblocks' );
56
57 $action = $wgRequest->getText( 'action' );
58 $successip = $wgRequest->getVal( 'successip' );
59
60 if( $action == 'unblock' || $action == 'submit' && $wgRequest->wasPosted() ) {
61 # Check permissions
62 if( !$wgUser->isAllowed( 'block' ) ) {
63 $wgOut->permissionRequired( 'block' );
64 return;
65 }
66 # Check for database lock
67 if( wfReadOnly() ) {
68 $wgOut->readOnlyPage();
69 return;
70 }
71
72 # bug 15810: blocked admins should have limited access here
73 if ( $wgUser->isBlocked() ) {
74 if ( $this->id ) {
75 # This doesn't pick up on autoblocks, but admins
76 # should have the ipblock-exempt permission anyway
77 $block = Block::newFromID( $this->id );
78 $user = User::newFromName( $block->mAddress );
79 } else {
80 $user = User::newFromName( $ip );
81 }
82 $status = SpecialBlock::checkUnblockSelf( $user );
83 if ( $status !== true ) {
84 throw new ErrorPageError( 'badaccess', $status );
85 }
86 }
87
88 if( $action == 'unblock' ){
89 # Show unblock form
90 $this->showForm();
91 } elseif( $action == 'submit'
92 && $wgRequest->wasPosted()
93 && $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) ) )
94 {
95 # Remove blocks and redirect user to success page
96 $this->doSubmit();
97 }
98
99 } elseif( $action == 'success' ) {
100 # Inform the user of a successful unblock
101 # (No need to check permissions or locks here,
102 # if something was done, then it's too late!)
103 if ( substr( $successip, 0, 1) == '#' ) {
104 // A block ID was unblocked
105 $this->showList( $wgOut->parse( wfMsg( 'unblocked-id', $successip ) ) );
106 } else {
107 // A username/IP was unblocked
108 $this->showList( $wgOut->parse( wfMsg( 'unblocked', $successip ) ) );
109 }
110 } else {
111 # Just show the block list
112 $this->showList( '' );
113 }
114 }
115
116 /**
117 * Generates the unblock form
118 *
119 * @param $err String, Array or null: error message name or an array if
120 * there are parameters. Null indicates no error.
121 * @return $out string: HTML form
122 */
123 function showForm( $err = null ) {
124 global $wgOut, $wgUser;
125
126 $wgOut->addWikiMsg( 'unblockiptext' );
127
128 $action = $this->getTitle()->getLocalURL( 'action=submit' );
129
130 if ( $err !== null ) {
131 $wgOut->setSubtitle( wfMsg( 'formerror' ) );
132 $wgOut->wrapWikiMsg( "<span class='error'>$1</span>\n", $err );
133 }
134
135 $addressPart = false;
136 if ( $this->id ) {
137 $block = Block::newFromID( $this->id );
138 if ( $block ) {
139 $encName = htmlspecialchars( $block->getRedactedName() );
140 $encId = $this->id;
141 $addressPart = $encName . Html::hidden( 'id', $encId );
142 $ipa = wfMsgHtml( 'ipadressorusername' );
143 }
144 }
145 if ( !$addressPart ) {
146 $addressPart = Xml::input( 'wpUnblockAddress', 40, $this->ip, array( 'type' => 'text', 'tabindex' => '1' ) );
147 $ipa = Xml::label( wfMsg( 'ipadressorusername' ), 'wpUnblockAddress' );
148 }
149
150 $wgOut->addHTML(
151 Html::openElement( 'form', array( 'method' => 'post', 'action' => $action, 'id' => 'unblockip' ) ) .
152 Html::openElement( 'fieldset' ) .
153 Html::element( 'legend', null, wfMsg( 'ipb-unblock' ) ) .
154 Html::openElement( 'table', array( 'id' => 'mw-unblock-table' ) ).
155 "<tr>
156 <td class='mw-label'>
157 {$ipa}
158 </td>
159 <td class='mw-input'>
160 {$addressPart}
161 </td>
162 </tr>
163 <tr>
164 <td class='mw-label'>" .
165 Xml::label( wfMsg( 'ipbreason' ), 'wpUnblockReason' ) .
166 "</td>
167 <td class='mw-input'>" .
168 Xml::input( 'wpUnblockReason', 40, $this->reason, array( 'type' => 'text', 'tabindex' => '2' ) ) .
169 "</td>
170 </tr>
171 <tr>
172 <td>&#160;</td>
173 <td class='mw-submit'>" .
174 Xml::submitButton( wfMsg( 'ipusubmit' ), array( 'name' => 'wpBlock', 'tabindex' => '3' ) ) .
175 "</td>
176 </tr>" .
177 Html::closeElement( 'table' ) .
178 Html::closeElement( 'fieldset' ) .
179 Html::hidden( 'wpEditToken', $wgUser->editToken() ) .
180 Html::closeElement( 'form' ) . "\n"
181 );
182
183 }
184
185 const UNBLOCK_SUCCESS = 0; // Success
186 const UNBLOCK_NO_SUCH_ID = 1; // No such block ID
187 const UNBLOCK_USER_NOT_BLOCKED = 2; // IP wasn't blocked
188 const UNBLOCK_BLOCKED_AS_RANGE = 3; // IP is part of a range block
189 const UNBLOCK_UNKNOWNERR = 4; // Unknown error
190
191 /**
192 * Backend code for unblocking. doSubmit() wraps around this.
193 * $range is only used when UNBLOCK_BLOCKED_AS_RANGE is returned, in which
194 * case it contains the range $ip is part of.
195 * @return array array(message key, parameters) on failure, empty array on success
196 */
197 public static function doUnblock( &$id, &$ip, &$reason, &$range = null, $blocker = null ) {
198 if ( $id ) {
199 $block = Block::newFromID( $id );
200 if ( !$block ) {
201 return array( 'ipb_cant_unblock', htmlspecialchars( $id ) );
202 }
203 $ip = $block->getRedactedName();
204 } else {
205 $ip = trim( $ip );
206 if ( substr( $ip, 0, 1 ) == "#" ) {
207 $id = substr( $ip, 1 );
208 $block = Block::newFromID( $id );
209 if( !$block ) {
210 return array( 'ipb_cant_unblock', htmlspecialchars( $id ) );
211 }
212 $ip = $block->getRedactedName();
213 } else {
214 # FIXME: do proper sanitisation/cleanup here
215 $ip = str_replace( '_', ' ', $ip );
216
217 $block = Block::newFromDB( $ip );
218 if ( !$block ) {
219 return array( 'ipb_cant_unblock', htmlspecialchars( $id ) );
220 }
221 if( $block->mRangeStart != $block->mRangeEnd && !strstr( $ip, "/" ) ) {
222 /* If the specified IP is a single address, and the block is
223 * a range block, don't unblock the range. */
224 $range = $block->mAddress;
225 return array( 'ipb_blocked_as_range', $ip, $range );
226 }
227 }
228 }
229 // Yes, this is really necessary
230 $id = $block->mId;
231
232 # If the name was hidden and the blocking user cannot hide
233 # names, then don't allow any block removals...
234 if( $blocker && $block->mHideName && !$blocker->isAllowed( 'hideuser' ) ) {
235 return array( 'ipb_cant_unblock', htmlspecialchars( $id ) );
236 }
237
238 # Delete block
239 if ( !$block->delete() ) {
240 return array( 'ipb_cant_unblock', htmlspecialchars( $id ) );
241 }
242
243 # Unset _deleted fields as needed
244 if( $block->mHideName ) {
245 RevisionDeleteUser::unsuppressUserName( $block->mAddress, $block->mUser );
246 }
247
248 # Make log entry
249 $log = new LogPage( 'block' );
250 $log->addEntry( 'unblock', Title::makeTitle( NS_USER, $ip ), $reason );
251 return array();
252 }
253
254 function doSubmit() {
255 global $wgOut, $wgUser;
256
257 $retval = self::doUnblock( $this->id, $this->ip, $this->reason, $range, $wgUser );
258 if ( count( $retval ) ) {
259 $this->showForm( $retval );
260 return;
261 }
262
263 # Report to the user
264 $success = $this->getTitle()->getFullURL( 'action=success&successip=' . urlencode( $this->ip ) );
265 $wgOut->redirect( $success );
266 }
267
268 function showList( $msg ) {
269 global $wgOut, $wgUser;
270
271 if ( $msg != '' ) {
272 $wgOut->setSubtitle( $msg );
273 }
274
275 // Purge expired entries on one in every 10 queries
276 if ( !mt_rand( 0, 10 ) ) {
277 Block::purgeExpired();
278 }
279
280 $conds = array();
281 // Is user allowed to see all the blocks?
282 if ( !$wgUser->isAllowed( 'hideuser' ) )
283 $conds['ipb_deleted'] = 0;
284 if ( $this->ip == '' ) {
285 // No extra conditions
286 } elseif ( substr( $this->ip, 0, 1 ) == '#' ) {
287 $conds['ipb_id'] = substr( $this->ip, 1 );
288 // Single IPs
289 } elseif ( IP::isIPAddress( $this->ip ) && strpos( $this->ip, '/' ) === false ) {
290 $iaddr = IP::toHex( $this->ip );
291 if( $iaddr ) {
292 # Only scan ranges which start in this /16, this improves search speed
293 # Blocks should not cross a /16 boundary.
294 $range = substr( $iaddr, 0, 4 );
295 // Fixme -- encapsulate this sort of query-building.
296 $dbr = wfGetDB( DB_SLAVE );
297 $encIp = $dbr->addQuotes( IP::sanitizeIP( $this->ip ) );
298 $encAddr = $dbr->addQuotes( $iaddr );
299 $conds[] = "(ipb_address = $encIp) OR
300 (ipb_range_start" . $dbr->buildLike( $range, $dbr->anyString() ) . " AND
301 ipb_range_start <= $encAddr
302 AND ipb_range_end >= $encAddr)";
303 } else {
304 $conds['ipb_address'] = IP::sanitizeIP( $this->ip );
305 }
306 $conds['ipb_auto'] = 0;
307 // IP range
308 } elseif ( IP::isIPAddress( $this->ip ) ) {
309 $conds['ipb_address'] = Block::normaliseRange( $this->ip );
310 $conds['ipb_auto'] = 0;
311 } else {
312 $user = User::newFromName( $this->ip );
313 if ( $user && ( $id = $user->getId() ) != 0 ) {
314 $conds['ipb_user'] = $id;
315 } else {
316 // Uh...?
317 $conds['ipb_address'] = $this->ip;
318 $conds['ipb_auto'] = 0;
319 }
320 }
321 // Apply filters
322 if( $this->hideuserblocks ) {
323 $conds['ipb_user'] = 0;
324 }
325 if( $this->hidetempblocks ) {
326 $conds['ipb_expiry'] = 'infinity';
327 }
328 if( $this->hideaddressblocks ) {
329 $conds[] = "ipb_user != 0 OR ipb_range_end > ipb_range_start";
330 }
331
332 // Search form
333 $wgOut->addHTML( $this->searchForm() );
334
335 // Check for other blocks, i.e. global/tor blocks
336 $otherBlockLink = array();
337 wfRunHooks( 'OtherBlockLogLink', array( &$otherBlockLink, $this->ip ) );
338
339 // Show additional header for the local block only when other blocks exists.
340 // Not necessary in a standard installation without such extensions enabled
341 if( count( $otherBlockLink ) ) {
342 $wgOut->addHTML(
343 Html::rawElement( 'h2', array(), wfMsg( 'ipblocklist-localblock' ) ) . "\n"
344 );
345 }
346 $pager = new IPBlocklistPager( $this, $conds );
347 if ( $pager->getNumRows() ) {
348 $wgOut->addHTML(
349 $pager->getNavigationBar() .
350 Html::rawElement( 'ul', null, $pager->getBody() ) .
351 $pager->getNavigationBar()
352 );
353 } elseif ( $this->ip != '') {
354 $wgOut->addWikiMsg( 'ipblocklist-no-results' );
355 } else {
356 $wgOut->addWikiMsg( 'ipblocklist-empty' );
357 }
358
359 if( count( $otherBlockLink ) ) {
360 $wgOut->addHTML(
361 Html::rawElement( 'h2', array(), wfMsgExt( 'ipblocklist-otherblocks', 'parseinline', count( $otherBlockLink ) ) ) . "\n"
362 );
363 $list = '';
364 foreach( $otherBlockLink as $link ) {
365 $list .= Html::rawElement( 'li', array(), $link ) . "\n";
366 }
367 $wgOut->addHTML( Html::rawElement( 'ul', array( 'class' => 'mw-ipblocklist-otherblocks' ), $list ) . "\n" );
368 }
369
370 }
371
372 function searchForm() {
373 global $wgScript, $wgLang;
374
375 $showhide = array( wfMsg( 'show' ), wfMsg( 'hide' ) );
376 $nondefaults = array();
377 if( $this->hideuserblocks ) {
378 $nondefaults['hideuserblocks'] = $this->hideuserblocks;
379 }
380 if( $this->hidetempblocks ) {
381 $nondefaults['hidetempblocks'] = $this->hidetempblocks;
382 }
383 if( $this->hideaddressblocks ) {
384 $nondefaults['hideaddressblocks'] = $this->hideaddressblocks;
385 }
386 $ubLink = $this->makeOptionsLink( $showhide[1-$this->hideuserblocks],
387 array( 'hideuserblocks' => 1-$this->hideuserblocks ), $nondefaults);
388 $tbLink = $this->makeOptionsLink( $showhide[1-$this->hidetempblocks],
389 array( 'hidetempblocks' => 1-$this->hidetempblocks ), $nondefaults);
390 $sipbLink = $this->makeOptionsLink( $showhide[1-$this->hideaddressblocks],
391 array( 'hideaddressblocks' => 1-$this->hideaddressblocks ), $nondefaults);
392
393 $links = array();
394 $links[] = wfMsgHtml( 'ipblocklist-sh-userblocks', $ubLink );
395 $links[] = wfMsgHtml( 'ipblocklist-sh-tempblocks', $tbLink );
396 $links[] = wfMsgHtml( 'ipblocklist-sh-addressblocks', $sipbLink );
397 $hl = $wgLang->pipeList( $links );
398
399 return
400 Html::rawElement( 'form', array( 'action' => $wgScript ),
401 Html::hidden( 'title', $this->getTitle()->getPrefixedDbKey() ) .
402 Html::openElement( 'fieldset' ) .
403 Html::element( 'legend', null, wfMsg( 'ipblocklist-legend' ) ) .
404 Xml::inputLabel( wfMsg( 'ipblocklist-username' ), 'ip', 'ip', /* size */ false, $this->ip ) .
405 '&#160;' .
406 Xml::submitButton( wfMsg( 'ipblocklist-submit' ) ) . '<br />' .
407 $hl .
408 Html::closeElement( 'fieldset' )
409 );
410 }
411
412 /**
413 * Makes change an option link which carries all the other options
414 *
415 * @param $title see Title
416 * @param $override Array: special query string options, will override the
417 * ones in $options
418 * @param $options Array: query string options
419 * @param $active Boolean: whether to display the link in bold
420 */
421 function makeOptionsLink( $title, $override, $options, $active = false ) {
422 global $wgUser;
423 $sk = $wgUser->getSkin();
424 $params = $override + $options;
425 return $sk->link( $this->getTitle(), htmlspecialchars( $title ),
426 ( $active ? array( 'style'=>'font-weight: bold;' ) : array() ), $params, array( 'known' ) );
427 }
428
429 /**
430 * Callback function to output a block
431 *
432 * @param $block Block
433 */
434 function formatRow( $block ) {
435 global $wgUser, $wgLang, $wgBlockAllowsUTEdit;
436
437 wfProfileIn( __METHOD__ );
438
439 static $sk=null, $msg=null;
440
441 if( is_null( $sk ) )
442 $sk = $wgUser->getSkin();
443 if( is_null( $msg ) ) {
444 $msg = array();
445 $keys = array( 'infiniteblock', 'expiringblock', 'unblocklink', 'change-blocklink',
446 'anononlyblock', 'createaccountblock', 'noautoblockblock', 'emailblock', 'blocklist-nousertalk', 'blocklistline' );
447 foreach( $keys as $key ) {
448 $msg[$key] = wfMsgHtml( $key );
449 }
450 }
451
452 # Prepare links to the blocker's user and talk pages
453 $blocker_id = $block->getBy();
454 $blocker_name = $block->getByName();
455 $blocker = $sk->userLink( $blocker_id, $blocker_name );
456 $blocker .= $sk->userToolLinks( $blocker_id, $blocker_name );
457
458 # Prepare links to the block target's user and contribs. pages (as applicable, don't do it for autoblocks)
459 if( $block->mAuto ) {
460 $target = $block->getRedactedName(); # Hide the IP addresses of auto-blocks; privacy
461 } else {
462 $target = $sk->userLink( $block->mUser, $block->mAddress )
463 . $sk->userToolLinks( $block->mUser, $block->mAddress, false, Linker::TOOL_LINKS_NOBLOCK );
464 }
465
466 $formattedTime = htmlspecialchars( $wgLang->timeanddate( $block->mTimestamp, true ) );
467
468 $properties = array();
469 $properties[] = Block::formatExpiry( $block->mExpiry );
470 if ( $block->mAnonOnly ) {
471 $properties[] = $msg['anononlyblock'];
472 }
473 if ( $block->mCreateAccount ) {
474 $properties[] = $msg['createaccountblock'];
475 }
476 if (!$block->mEnableAutoblock && $block->mUser ) {
477 $properties[] = $msg['noautoblockblock'];
478 }
479
480 if ( $block->mBlockEmail && $block->mUser ) {
481 $properties[] = $msg['emailblock'];
482 }
483
484 if ( !$block->mAllowUsertalk && $wgBlockAllowsUTEdit ) {
485 $properties[] = $msg['blocklist-nousertalk'];
486 }
487
488 $properties = $wgLang->commaList( $properties );
489
490 $line = wfMsgReplaceArgs( $msg['blocklistline'], array( $formattedTime, $blocker, $target, $properties ) );
491
492 $changeblocklink = '';
493 $toolLinks = '';
494 if ( $wgUser->isAllowed( 'block' ) ) {
495 $unblocklink = $sk->link( $this->getTitle(),
496 $msg['unblocklink'],
497 array(),
498 array( 'action' => 'unblock', 'id' => $block->mId ),
499 'known' );
500
501 # Create changeblocklink for all blocks with exception of autoblocks
502 if( !$block->mAuto ) {
503 $changeblocklink = wfMsgExt( 'pipe-separator', 'escapenoentities' ) .
504 $sk->link( SpecialPage::getTitleFor( 'Block', $block->mAddress ),
505 $msg['change-blocklink'],
506 array(), array(), 'known' );
507 }
508 $toolLinks = "($unblocklink$changeblocklink)";
509 }
510
511 $comment = $sk->commentBlock( htmlspecialchars($block->mReason) );
512
513 $s = "{$line} $comment";
514 if ( $block->mHideName )
515 $s = '<span class="history-deleted">' . $s . '</span>';
516
517 wfProfileOut( __METHOD__ );
518 return "<li>$s $toolLinks</li>\n";
519 }
520 }
521
522 /**
523 * @todo document
524 * @ingroup Pager
525 */
526 class IPBlocklistPager extends ReverseChronologicalPager {
527 public $mForm, $mConds;
528
529 function __construct( $form, $conds = array() ) {
530 $this->mForm = $form;
531 $this->mConds = $conds;
532 parent::__construct();
533 }
534
535 function getStartBody() {
536 wfProfileIn( __METHOD__ );
537 # Do a link batch query
538 $this->mResult->seek( 0 );
539 $lb = new LinkBatch;
540
541 /*
542 while ( $row = $this->mResult->fetchObject() ) {
543 $lb->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) );
544 $lb->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->user_name ) );
545 $lb->addObj( Title::makeTitleSafe( NS_USER, $row->ipb_address ) );
546 $lb->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->ipb_address ) );
547 }*/
548 # Faster way
549 # Usernames and titles are in fact related by a simple substitution of space -> underscore
550 # The last few lines of Title::secureAndSplit() tell the story.
551 foreach ( $this->mResult as $row ) {
552 $name = str_replace( ' ', '_', $row->ipb_by_text );
553 $lb->add( NS_USER, $name );
554 $lb->add( NS_USER_TALK, $name );
555 $name = str_replace( ' ', '_', $row->ipb_address );
556 $lb->add( NS_USER, $name );
557 $lb->add( NS_USER_TALK, $name );
558 }
559 $lb->execute();
560 wfProfileOut( __METHOD__ );
561 return '';
562 }
563
564 function formatRow( $row ) {
565 $block = new Block;
566 $block->initFromRow( $row );
567 return $this->mForm->formatRow( $block );
568 }
569
570 function getQueryInfo() {
571 $conds = $this->mConds;
572 $conds[] = 'ipb_expiry>' . $this->mDb->addQuotes( $this->mDb->timestamp() );
573 return array(
574 'tables' => 'ipblocks',
575 'fields' => '*',
576 'conds' => $conds,
577 );
578 }
579
580 function getIndexField() {
581 return 'ipb_timestamp';
582 }
583 }