* Do not display empty columns on Special:UserRights if all groups are changeable...
[lhc/web/wiklou.git] / includes / Block.php
1 <?php
2 /**
3 * Blocks and bans object
4 */
5
6 /**
7 * The block class
8 * All the functions in this class assume the object is either explicitly
9 * loaded or filled. It is not load-on-demand. There are no accessors.
10 *
11 * Globals used: $wgAutoblockExpiry, $wgAntiLockFlags
12 *
13 * @todo This could be used everywhere, but it isn't.
14 */
15 class Block
16 {
17 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
18 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock, $mHideName,
19 $mBlockEmail, $mByName;
20 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster;
21
22 const EB_KEEP_EXPIRED = 1;
23 const EB_FOR_UPDATE = 2;
24 const EB_RANGE_ONLY = 4;
25
26 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
27 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
28 $hideName = 0, $blockEmail = 0 )
29 {
30 $this->mId = 0;
31 # Expand valid IPv6 addresses
32 $address = IP::sanitizeIP( $address );
33 $this->mAddress = $address;
34 $this->mUser = $user;
35 $this->mBy = $by;
36 $this->mReason = $reason;
37 $this->mTimestamp = wfTimestamp(TS_MW,$timestamp);
38 $this->mAuto = $auto;
39 $this->mAnonOnly = $anonOnly;
40 $this->mCreateAccount = $createAccount;
41 $this->mExpiry = self::decodeExpiry( $expiry );
42 $this->mEnableAutoblock = $enableAutoblock;
43 $this->mHideName = $hideName;
44 $this->mBlockEmail = $blockEmail;
45 $this->mForUpdate = false;
46 $this->mFromMaster = false;
47 $this->mByName = false;
48 $this->initialiseRange();
49 }
50
51 static function newFromDB( $address, $user = 0, $killExpired = true )
52 {
53 $block = new Block();
54 $block->load( $address, $user, $killExpired );
55 if ( $block->isValid() ) {
56 return $block;
57 } else {
58 return null;
59 }
60 }
61
62 static function newFromID( $id )
63 {
64 $dbr = wfGetDB( DB_SLAVE );
65 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
66 array( 'ipb_id' => $id ), __METHOD__ ) );
67 $block = new Block;
68 if ( $block->loadFromResult( $res ) ) {
69 return $block;
70 } else {
71 return null;
72 }
73 }
74
75 function clear()
76 {
77 $this->mAddress = $this->mReason = $this->mTimestamp = '';
78 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
79 $this->mEnableAutoblock = $this->mAuto = $this->mUser =
80 $this->mBy = $this->mHideName = $this->mBlockEmail = 0;
81 $this->mByName = false;
82 }
83
84 /**
85 * Get the DB object and set the reference parameter to the query options
86 */
87 function &getDBOptions( &$options )
88 {
89 global $wgAntiLockFlags;
90 if ( $this->mForUpdate || $this->mFromMaster ) {
91 $db = wfGetDB( DB_MASTER );
92 if ( !$this->mForUpdate || ($wgAntiLockFlags & ALF_NO_BLOCK_LOCK) ) {
93 $options = array();
94 } else {
95 $options = array( 'FOR UPDATE' );
96 }
97 } else {
98 $db = wfGetDB( DB_SLAVE );
99 $options = array();
100 }
101 return $db;
102 }
103
104 /**
105 * Get a ban from the DB, with either the given address or the given username
106 *
107 * @param string $address The IP address of the user, or blank to skip IP blocks
108 * @param integer $user The user ID, or zero for anonymous users
109 * @param bool $killExpired Whether to delete expired rows while loading
110 *
111 */
112 function load( $address = '', $user = 0, $killExpired = true )
113 {
114 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
115
116 $options = array();
117 $db =& $this->getDBOptions( $options );
118
119 if ( 0 == $user && $address == '' ) {
120 # Invalid user specification, not blocked
121 $this->clear();
122 return false;
123 }
124
125 # Try user block
126 if ( $user ) {
127 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
128 __METHOD__, $options ) );
129 if ( $this->loadFromResult( $res, $killExpired ) ) {
130 return true;
131 }
132 }
133
134 # Try IP block
135 # TODO: improve performance by merging this query with the autoblock one
136 # Slightly tricky while handling killExpired as well
137 if ( $address ) {
138 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
139 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
140 if ( $this->loadFromResult( $res, $killExpired ) ) {
141 if ( $user && $this->mAnonOnly ) {
142 # Block is marked anon-only
143 # Whitelist this IP address against autoblocks and range blocks
144 $this->clear();
145 return false;
146 } else {
147 return true;
148 }
149 }
150 }
151
152 # Try range block
153 if ( $this->loadRange( $address, $killExpired, $user ) ) {
154 if ( $user && $this->mAnonOnly ) {
155 $this->clear();
156 return false;
157 } else {
158 return true;
159 }
160 }
161
162 # Try autoblock
163 if ( $address ) {
164 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
165 if ( $user ) {
166 $conds['ipb_anon_only'] = 0;
167 }
168 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
169 if ( $this->loadFromResult( $res, $killExpired ) ) {
170 return true;
171 }
172 }
173
174 # Give up
175 $this->clear();
176 return false;
177 }
178
179 /**
180 * Fill in member variables from a result wrapper
181 */
182 function loadFromResult( ResultWrapper $res, $killExpired = true )
183 {
184 $ret = false;
185 if ( 0 != $res->numRows() ) {
186 # Get first block
187 $row = $res->fetchObject();
188 $this->initFromRow( $row );
189
190 if ( $killExpired ) {
191 # If requested, delete expired rows
192 do {
193 $killed = $this->deleteIfExpired();
194 if ( $killed ) {
195 $row = $res->fetchObject();
196 if ( $row ) {
197 $this->initFromRow( $row );
198 }
199 }
200 } while ( $killed && $row );
201
202 # If there were any left after the killing finished, return true
203 if ( $row ) {
204 $ret = true;
205 }
206 } else {
207 $ret = true;
208 }
209 }
210 $res->free();
211 return $ret;
212 }
213
214 /**
215 * Search the database for any range blocks matching the given address, and
216 * load the row if one is found.
217 */
218 function loadRange( $address, $killExpired = true, $user = 0 )
219 {
220 $iaddr = IP::toHex( $address );
221 if ( $iaddr === false ) {
222 # Invalid address
223 return false;
224 }
225
226 # Only scan ranges which start in this /16, this improves search speed
227 # Blocks should not cross a /16 boundary.
228 $range = substr( $iaddr, 0, 4 );
229
230 $options = array();
231 $db =& $this->getDBOptions( $options );
232 $conds = array(
233 "ipb_range_start LIKE '$range%'",
234 "ipb_range_start <= '$iaddr'",
235 "ipb_range_end >= '$iaddr'"
236 );
237
238 if ( $user ) {
239 $conds['ipb_anon_only'] = 0;
240 }
241
242 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
243 $success = $this->loadFromResult( $res, $killExpired );
244 return $success;
245 }
246
247 /**
248 * Determine if a given integer IPv4 address is in a given CIDR network
249 * @deprecated Use IP::isInRange
250 */
251 function isAddressInRange( $addr, $range ) {
252 return IP::isInRange( $addr, $range );
253 }
254
255 function initFromRow( $row )
256 {
257 $this->mAddress = $row->ipb_address;
258 $this->mReason = $row->ipb_reason;
259 $this->mTimestamp = wfTimestamp(TS_MW,$row->ipb_timestamp);
260 $this->mUser = $row->ipb_user;
261 $this->mBy = $row->ipb_by;
262 $this->mAuto = $row->ipb_auto;
263 $this->mAnonOnly = $row->ipb_anon_only;
264 $this->mCreateAccount = $row->ipb_create_account;
265 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
266 $this->mBlockEmail = $row->ipb_block_email;
267 $this->mHideName = $row->ipb_deleted;
268 $this->mId = $row->ipb_id;
269 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
270 if ( isset( $row->user_name ) ) {
271 $this->mByName = $row->user_name;
272 } else {
273 $this->mByName = $row->ipb_by_text;
274 }
275 $this->mRangeStart = $row->ipb_range_start;
276 $this->mRangeEnd = $row->ipb_range_end;
277 }
278
279 function initialiseRange()
280 {
281 $this->mRangeStart = '';
282 $this->mRangeEnd = '';
283
284 if ( $this->mUser == 0 ) {
285 list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress );
286 }
287 }
288
289 /**
290 * Callback with a Block object for every block
291 * @return integer number of blocks;
292 */
293 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
294 {
295 global $wgAntiLockFlags;
296
297 $block = new Block();
298 if ( $flags & Block::EB_FOR_UPDATE ) {
299 $db = wfGetDB( DB_MASTER );
300 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK ) {
301 $options = '';
302 } else {
303 $options = 'FOR UPDATE';
304 }
305 $block->forUpdate( true );
306 } else {
307 $db = wfGetDB( DB_SLAVE );
308 $options = '';
309 }
310 if ( $flags & Block::EB_RANGE_ONLY ) {
311 $cond = " AND ipb_range_start <> ''";
312 } else {
313 $cond = '';
314 }
315
316 $now = wfTimestampNow();
317
318 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
319
320 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
321 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
322 $res = $db->query( $sql, 'Block::enumBlocks' );
323 $num_rows = $db->numRows( $res );
324
325 while ( $row = $db->fetchObject( $res ) ) {
326 $block->initFromRow( $row );
327 if ( ( $flags & Block::EB_RANGE_ONLY ) && $block->mRangeStart == '' ) {
328 continue;
329 }
330
331 if ( !( $flags & Block::EB_KEEP_EXPIRED ) ) {
332 if ( $block->mExpiry && $now > $block->mExpiry ) {
333 $block->delete();
334 } else {
335 call_user_func( $callback, $block, $tag );
336 }
337 } else {
338 call_user_func( $callback, $block, $tag );
339 }
340 }
341 $db->freeResult( $res );
342 return $num_rows;
343 }
344
345 function delete()
346 {
347 if (wfReadOnly()) {
348 return false;
349 }
350 if ( !$this->mId ) {
351 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
352 }
353
354 $dbw = wfGetDB( DB_MASTER );
355 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
356 return $dbw->affectedRows() > 0;
357 }
358
359 /**
360 * Insert a block into the block table.
361 * @return Whether or not the insertion was successful.
362 */
363 function insert()
364 {
365 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
366 $dbw = wfGetDB( DB_MASTER );
367
368 # Unset ipb_anon_only for user blocks, makes no sense
369 if ( $this->mUser ) {
370 $this->mAnonOnly = 0;
371 }
372
373 # Unset ipb_enable_autoblock for IP blocks, makes no sense
374 if ( !$this->mUser ) {
375 $this->mEnableAutoblock = 0;
376 $this->mBlockEmail = 0; //Same goes for email...
377 }
378
379 if( !$this->mByName ) {
380 if( $this->mBy ) {
381 $this->mByName = User::whoIs( $this->mBy );
382 } else {
383 global $wgUser;
384 $this->mByName = $wgUser->getName();
385 }
386 }
387
388 # Don't collide with expired blocks
389 Block::purgeExpired();
390
391 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
392 $dbw->insert( 'ipblocks',
393 array(
394 'ipb_id' => $ipb_id,
395 'ipb_address' => $this->mAddress,
396 'ipb_user' => $this->mUser,
397 'ipb_by' => $this->mBy,
398 'ipb_by_text' => $this->mByName,
399 'ipb_reason' => $this->mReason,
400 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
401 'ipb_auto' => $this->mAuto,
402 'ipb_anon_only' => $this->mAnonOnly,
403 'ipb_create_account' => $this->mCreateAccount,
404 'ipb_enable_autoblock' => $this->mEnableAutoblock,
405 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
406 'ipb_range_start' => $this->mRangeStart,
407 'ipb_range_end' => $this->mRangeEnd,
408 'ipb_deleted' => $this->mHideName,
409 'ipb_block_email' => $this->mBlockEmail
410 ), 'Block::insert', array( 'IGNORE' )
411 );
412 $affected = $dbw->affectedRows();
413
414 if ($affected)
415 $this->doRetroactiveAutoblock();
416
417 return $affected;
418 }
419
420 /**
421 * Retroactively autoblocks the last IP used by the user (if it is a user)
422 * blocked by this Block.
423 *@return Whether or not a retroactive autoblock was made.
424 */
425 function doRetroactiveAutoblock() {
426 $dbr = wfGetDB( DB_SLAVE );
427 #If autoblock is enabled, autoblock the LAST IP used
428 # - stolen shamelessly from CheckUser_body.php
429
430 if ($this->mEnableAutoblock && $this->mUser) {
431 wfDebug("Doing retroactive autoblocks for " . $this->mAddress . "\n");
432
433 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress ),
434 __METHOD__ , array( 'ORDER BY' => 'rc_timestamp DESC' ) );
435
436 if ( !$row || !$row->rc_ip ) {
437 #No results, don't autoblock anything
438 wfDebug("No IP found to retroactively autoblock\n");
439 } else {
440 #Limit is 1, so no loop needed.
441 $retroblockip = $row->rc_ip;
442 return $this->doAutoblock( $retroblockip, true );
443 }
444 }
445 }
446
447 /**
448 * Autoblocks the given IP, referring to this Block.
449 * @param string $autoblockip The IP to autoblock.
450 * @param bool $justInserted The main block was just inserted
451 * @return bool Whether or not an autoblock was inserted.
452 */
453 function doAutoblock( $autoblockip, $justInserted = false ) {
454 # If autoblocks are disabled, go away.
455 if ( !$this->mEnableAutoblock ) {
456 return;
457 }
458
459 # Check for presence on the autoblock whitelist
460 # TODO cache this?
461 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
462
463 $ip = $autoblockip;
464
465 wfDebug("Checking the autoblock whitelist..\n");
466
467 foreach( $lines as $line ) {
468 # List items only
469 if ( substr( $line, 0, 1 ) !== '*' ) {
470 continue;
471 }
472
473 $wlEntry = substr($line, 1);
474 $wlEntry = trim($wlEntry);
475
476 wfDebug("Checking $ip against $wlEntry...");
477
478 # Is the IP in this range?
479 if (IP::isInRange( $ip, $wlEntry )) {
480 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
481 #$autoblockip = null; # Don't autoblock a whitelisted IP.
482 return; #This /SHOULD/ introduce a dummy block - but
483 # I don't know a safe way to do so. -werdna
484 } else {
485 wfDebug( " No match\n" );
486 }
487 }
488
489 # It's okay to autoblock. Go ahead and create/insert the block.
490
491 $ipblock = Block::newFromDB( $autoblockip );
492 if ( $ipblock ) {
493 # If the user is already blocked. Then check if the autoblock would
494 # exceed the user block. If it would exceed, then do nothing, else
495 # prolong block time
496 if ($this->mExpiry &&
497 ($this->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
498 return;
499 }
500 # Just update the timestamp
501 if ( !$justInserted ) {
502 $ipblock->updateTimestamp();
503 }
504 return;
505 } else {
506 $ipblock = new Block;
507 }
508
509 # Make a new block object with the desired properties
510 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
511 $ipblock->mAddress = $autoblockip;
512 $ipblock->mUser = 0;
513 $ipblock->mBy = $this->mBy;
514 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
515 $ipblock->mTimestamp = wfTimestampNow();
516 $ipblock->mAuto = 1;
517 $ipblock->mCreateAccount = $this->mCreateAccount;
518 # Continue suppressing the name if needed
519 $ipblock->mHideName = $this->mHideName;
520
521 # If the user is already blocked with an expiry date, we don't
522 # want to pile on top of that!
523 if($this->mExpiry) {
524 $ipblock->mExpiry = min ( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ));
525 } else {
526 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
527 }
528 # Insert it
529 return $ipblock->insert();
530 }
531
532 function deleteIfExpired()
533 {
534 $fname = 'Block::deleteIfExpired';
535 wfProfileIn( $fname );
536 if ( $this->isExpired() ) {
537 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
538 $this->delete();
539 $retVal = true;
540 } else {
541 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
542 $retVal = false;
543 }
544 wfProfileOut( $fname );
545 return $retVal;
546 }
547
548 function isExpired()
549 {
550 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
551 if ( !$this->mExpiry ) {
552 return false;
553 } else {
554 return wfTimestampNow() > $this->mExpiry;
555 }
556 }
557
558 function isValid()
559 {
560 return $this->mAddress != '';
561 }
562
563 function updateTimestamp()
564 {
565 if ( $this->mAuto ) {
566 $this->mTimestamp = wfTimestamp();
567 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
568
569 $dbw = wfGetDB( DB_MASTER );
570 $dbw->update( 'ipblocks',
571 array( /* SET */
572 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
573 'ipb_expiry' => $dbw->timestamp($this->mExpiry),
574 ), array( /* WHERE */
575 'ipb_address' => $this->mAddress
576 ), 'Block::updateTimestamp'
577 );
578 }
579 }
580
581 /*
582 function getIntegerAddr()
583 {
584 return $this->mIntegerAddr;
585 }
586
587 function getNetworkBits()
588 {
589 return $this->mNetworkBits;
590 }*/
591
592 /**
593 * @return The blocker user ID.
594 */
595 public function getBy() {
596 return $this->mBy;
597 }
598
599 /**
600 * @return The blocker user name.
601 */
602 function getByName()
603 {
604 return $this->mByName;
605 }
606
607 function forUpdate( $x = NULL ) {
608 return wfSetVar( $this->mForUpdate, $x );
609 }
610
611 function fromMaster( $x = NULL ) {
612 return wfSetVar( $this->mFromMaster, $x );
613 }
614
615 function getRedactedName() {
616 if ( $this->mAuto ) {
617 return '#' . $this->mId;
618 } else {
619 return $this->mAddress;
620 }
621 }
622
623 /**
624 * Encode expiry for DB
625 */
626 static function encodeExpiry( $expiry, $db ) {
627 if ( $expiry == '' || $expiry == Block::infinity() ) {
628 return Block::infinity();
629 } else {
630 return $db->timestamp( $expiry );
631 }
632 }
633
634 /**
635 * Decode expiry which has come from the DB
636 */
637 static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
638 if ( $expiry == '' || $expiry == Block::infinity() ) {
639 return Block::infinity();
640 } else {
641 return wfTimestamp( $timestampType, $expiry );
642 }
643 }
644
645 static function getAutoblockExpiry( $timestamp )
646 {
647 global $wgAutoblockExpiry;
648 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
649 }
650
651 /**
652 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
653 * For example, 127.111.113.151/24 -> 127.111.113.0/24
654 */
655 static function normaliseRange( $range ) {
656 $parts = explode( '/', $range );
657 if ( count( $parts ) == 2 ) {
658 // IPv6
659 if ( IP::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
660 $bits = $parts[1];
661 $ipint = IP::toUnsigned6( $parts[0] );
662 # Native 32 bit functions WONT work here!!!
663 # Convert to a padded binary number
664 $network = wfBaseConvert( $ipint, 10, 2, 128 );
665 # Truncate the last (128-$bits) bits and replace them with zeros
666 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
667 # Convert back to an integer
668 $network = wfBaseConvert( $network, 2, 10 );
669 # Reform octet address
670 $newip = IP::toOctet( $network );
671 $range = "$newip/{$parts[1]}";
672 } // IPv4
673 else if ( IP::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
674 $shift = 32 - $parts[1];
675 $ipint = IP::toUnsigned( $parts[0] );
676 $ipint = $ipint >> $shift << $shift;
677 $newip = long2ip( $ipint );
678 $range = "$newip/{$parts[1]}";
679 }
680 }
681 return $range;
682 }
683
684 /**
685 * Purge expired blocks from the ipblocks table
686 */
687 static function purgeExpired() {
688 $dbw = wfGetDB( DB_MASTER );
689 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
690 }
691
692 static function infinity() {
693 # This is a special keyword for timestamps in PostgreSQL, and
694 # works with CHAR(14) as well because "i" sorts after all numbers.
695 return 'infinity';
696
697 /*
698 static $infinity;
699 if ( !isset( $infinity ) ) {
700 $dbr = wfGetDB( DB_SLAVE );
701 $infinity = $dbr->bigTimestamp();
702 }
703 return $infinity;
704 */
705 }
706
707 }