3 * Blocks and bans object
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.
11 * Globals used: $wgAutoblockExpiry, $wgAntiLockFlags
13 * @todo This could be used everywhere, but it isn't.
17 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
18 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock, $mHideName;
19 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster, $mByName;
21 const EB_KEEP_EXPIRED
= 1;
22 const EB_FOR_UPDATE
= 2;
23 const EB_RANGE_ONLY
= 4;
25 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
26 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
30 # Expand valid IPv6 addresses
31 $address = IP
::sanitizeIP( $address );
32 $this->mAddress
= $address;
35 $this->mReason
= $reason;
36 $this->mTimestamp
= wfTimestamp(TS_MW
,$timestamp);
38 $this->mAnonOnly
= $anonOnly;
39 $this->mCreateAccount
= $createAccount;
40 $this->mExpiry
= self
::decodeExpiry( $expiry );
41 $this->mEnableAutoblock
= $enableAutoblock;
42 $this->mHideName
= $hideName;
44 $this->mForUpdate
= false;
45 $this->mFromMaster
= false;
46 $this->mByName
= false;
47 $this->initialiseRange();
50 static function newFromDB( $address, $user = 0, $killExpired = true )
53 $block->load( $address, $user, $killExpired );
54 if ( $block->isValid() ) {
61 static function newFromID( $id )
63 $dbr = wfGetDB( DB_SLAVE
);
64 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
65 array( 'ipb_id' => $id ), __METHOD__
) );
67 if ( $block->loadFromResult( $res ) ) {
76 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
77 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
78 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
79 $this->mBy
= $this->mHideName
= 0;
80 $this->mByName
= false;
84 * Get the DB object and set the reference parameter to the query options
86 function &getDBOptions( &$options )
88 global $wgAntiLockFlags;
89 if ( $this->mForUpdate ||
$this->mFromMaster
) {
90 $db = wfGetDB( DB_MASTER
);
91 if ( !$this->mForUpdate ||
($wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) ) {
94 $options = array( 'FOR UPDATE' );
97 $db = wfGetDB( DB_SLAVE
);
104 * Get a ban from the DB, with either the given address or the given username
106 * @param string $address The IP address of the user, or blank to skip IP blocks
107 * @param integer $user The user ID, or zero for anonymous users
108 * @param bool $killExpired Whether to delete expired rows while loading
111 function load( $address = '', $user = 0, $killExpired = true )
113 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
116 $db =& $this->getDBOptions( $options );
118 if ( 0 == $user && $address == '' ) {
119 # Invalid user specification, not blocked
126 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
127 __METHOD__
, $options ) );
128 if ( $this->loadFromResult( $res, $killExpired ) ) {
134 # TODO: improve performance by merging this query with the autoblock one
135 # Slightly tricky while handling killExpired as well
137 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
138 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
139 if ( $this->loadFromResult( $res, $killExpired ) ) {
140 if ( $user && $this->mAnonOnly
) {
141 # Block is marked anon-only
142 # Whitelist this IP address against autoblocks and range blocks
152 if ( $this->loadRange( $address, $killExpired, $user ) ) {
153 if ( $user && $this->mAnonOnly
) {
163 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
165 $conds['ipb_anon_only'] = 0;
167 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
168 if ( $this->loadFromResult( $res, $killExpired ) ) {
179 * Fill in member variables from a result wrapper
181 function loadFromResult( ResultWrapper
$res, $killExpired = true )
184 if ( 0 != $res->numRows() ) {
186 $row = $res->fetchObject();
187 $this->initFromRow( $row );
189 if ( $killExpired ) {
190 # If requested, delete expired rows
192 $killed = $this->deleteIfExpired();
194 $row = $res->fetchObject();
196 $this->initFromRow( $row );
199 } while ( $killed && $row );
201 # If there were any left after the killing finished, return true
214 * Search the database for any range blocks matching the given address, and
215 * load the row if one is found.
217 function loadRange( $address, $killExpired = true, $user = 0 )
219 $iaddr = IP
::toHex( $address );
220 if ( $iaddr === false ) {
225 # Only scan ranges which start in this /16, this improves search speed
226 # Blocks should not cross a /16 boundary.
227 $range = substr( $iaddr, 0, 4 );
230 $db =& $this->getDBOptions( $options );
232 "ipb_range_start LIKE '$range%'",
233 "ipb_range_start <= '$iaddr'",
234 "ipb_range_end >= '$iaddr'"
238 $conds['ipb_anon_only'] = 0;
241 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
242 $success = $this->loadFromResult( $res, $killExpired );
247 * Determine if a given integer IPv4 address is in a given CIDR network
248 * @deprecated Use IP::isInRange
250 function isAddressInRange( $addr, $range ) {
251 return IP
::isInRange( $addr, $range );
254 function initFromRow( $row )
256 $this->mAddress
= $row->ipb_address
;
257 $this->mReason
= $row->ipb_reason
;
258 $this->mTimestamp
= wfTimestamp(TS_MW
,$row->ipb_timestamp
);
259 $this->mUser
= $row->ipb_user
;
260 $this->mBy
= $row->ipb_by
;
261 $this->mAuto
= $row->ipb_auto
;
262 $this->mAnonOnly
= $row->ipb_anon_only
;
263 $this->mCreateAccount
= $row->ipb_create_account
;
264 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
265 $this->mHideName
= $row->ipb_deleted
;
266 $this->mId
= $row->ipb_id
;
267 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
268 if ( isset( $row->user_name
) ) {
269 $this->mByName
= $row->user_name
;
271 $this->mByName
= false;
273 $this->mRangeStart
= $row->ipb_range_start
;
274 $this->mRangeEnd
= $row->ipb_range_end
;
277 function initialiseRange()
279 $this->mRangeStart
= '';
280 $this->mRangeEnd
= '';
282 if ( $this->mUser
== 0 ) {
283 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
288 * Callback with a Block object for every block
289 * @return integer number of blocks;
291 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
293 global $wgAntiLockFlags;
295 $block = new Block();
296 if ( $flags & Block
::EB_FOR_UPDATE
) {
297 $db = wfGetDB( DB_MASTER
);
298 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
301 $options = 'FOR UPDATE';
303 $block->forUpdate( true );
305 $db = wfGetDB( DB_SLAVE
);
308 if ( $flags & Block
::EB_RANGE_ONLY
) {
309 $cond = " AND ipb_range_start <> ''";
314 $now = wfTimestampNow();
316 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
318 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
319 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
320 $res = $db->query( $sql, 'Block::enumBlocks' );
321 $num_rows = $db->numRows( $res );
323 while ( $row = $db->fetchObject( $res ) ) {
324 $block->initFromRow( $row );
325 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
329 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
330 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
333 call_user_func( $callback, $block, $tag );
336 call_user_func( $callback, $block, $tag );
339 $db->freeResult( $res );
349 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
352 $dbw = wfGetDB( DB_MASTER
);
353 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
354 return $dbw->affectedRows() > 0;
358 * Insert a block into the block table.
359 *@return Whether or not the insertion was successful.
363 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
364 $dbw = wfGetDB( DB_MASTER
);
366 # Unset ipb_anon_only for user blocks, makes no sense
367 if ( $this->mUser
) {
368 $this->mAnonOnly
= 0;
371 # Unset ipb_enable_autoblock for IP blocks, makes no sense
372 if ( !$this->mUser
) {
373 $this->mEnableAutoblock
= 0;
376 # Don't collide with expired blocks
377 Block
::purgeExpired();
379 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
380 $dbw->insert( 'ipblocks',
383 'ipb_address' => $this->mAddress
,
384 'ipb_user' => $this->mUser
,
385 'ipb_by' => $this->mBy
,
386 'ipb_reason' => $this->mReason
,
387 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
388 'ipb_auto' => $this->mAuto
,
389 'ipb_anon_only' => $this->mAnonOnly
,
390 'ipb_create_account' => $this->mCreateAccount
,
391 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
392 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
393 'ipb_range_start' => $this->mRangeStart
,
394 'ipb_range_end' => $this->mRangeEnd
,
395 'ipb_deleted' => $this->mHideName
396 ), 'Block::insert', array( 'IGNORE' )
398 $affected = $dbw->affectedRows();
402 $this->doRetroactiveAutoblock();
408 * Retroactively autoblocks the last IP used by the user (if it is a user)
409 * blocked by this Block.
410 *@return Whether or not a retroactive autoblock was made.
412 function doRetroactiveAutoblock() {
413 $dbr = wfGetDB( DB_SLAVE
);
414 #If autoblock is enabled, autoblock the LAST IP used
415 # - stolen shamelessly from CheckUser_body.php
417 if ($this->mEnableAutoblock
&& $this->mUser
) {
418 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
420 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress
),
421 __METHOD__
, array( 'ORDER BY' => 'rc_timestamp DESC' ) );
423 if ( !$row ||
!$row->rc_ip
) {
424 #No results, don't autoblock anything
425 wfDebug("No IP found to retroactively autoblock\n");
427 #Limit is 1, so no loop needed.
428 $retroblockip = $row->rc_ip
;
429 return $this->doAutoblock( $retroblockip, true );
435 * Autoblocks the given IP, referring to this Block.
436 * @param string $autoblockip The IP to autoblock.
437 * @param bool $justInserted The main block was just inserted
438 * @return bool Whether or not an autoblock was inserted.
440 function doAutoblock( $autoblockip, $justInserted = false ) {
441 # If autoblocks are disabled, go away.
442 if ( !$this->mEnableAutoblock
) {
446 # Check for presence on the autoblock whitelist
448 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
452 wfDebug("Checking the autoblock whitelist..\n");
454 foreach( $lines as $line ) {
456 if ( substr( $line, 0, 1 ) !== '*' ) {
460 $wlEntry = substr($line, 1);
461 $wlEntry = trim($wlEntry);
463 wfDebug("Checking $ip against $wlEntry...");
465 # Is the IP in this range?
466 if (IP
::isInRange( $ip, $wlEntry )) {
467 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
468 #$autoblockip = null; # Don't autoblock a whitelisted IP.
469 return; #This /SHOULD/ introduce a dummy block - but
470 # I don't know a safe way to do so. -werdna
472 wfDebug( " No match\n" );
476 # It's okay to autoblock. Go ahead and create/insert the block.
478 $ipblock = Block
::newFromDB( $autoblockip );
480 # If the user is already blocked. Then check if the autoblock would
481 # exceed the user block. If it would exceed, then do nothing, else
483 if ($this->mExpiry
&&
484 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
487 # Just update the timestamp
488 if ( !$justInserted ) {
489 $ipblock->updateTimestamp();
493 $ipblock = new Block
;
496 # Make a new block object with the desired properties
497 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
498 $ipblock->mAddress
= $autoblockip;
500 $ipblock->mBy
= $this->mBy
;
501 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
502 $ipblock->mTimestamp
= wfTimestampNow();
504 $ipblock->mCreateAccount
= $this->mCreateAccount
;
505 # Continue suppressing the name if needed
506 $ipblock->mHideName
= $this->mHideName
;
508 # If the user is already blocked with an expiry date, we don't
509 # want to pile on top of that!
511 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
513 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
516 return $ipblock->insert();
519 function deleteIfExpired()
521 $fname = 'Block::deleteIfExpired';
522 wfProfileIn( $fname );
523 if ( $this->isExpired() ) {
524 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
528 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
531 wfProfileOut( $fname );
537 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
538 if ( !$this->mExpiry
) {
541 return wfTimestampNow() > $this->mExpiry
;
547 return $this->mAddress
!= '';
550 function updateTimestamp()
552 if ( $this->mAuto
) {
553 $this->mTimestamp
= wfTimestamp();
554 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
556 $dbw = wfGetDB( DB_MASTER
);
557 $dbw->update( 'ipblocks',
559 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
560 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
561 ), array( /* WHERE */
562 'ipb_address' => $this->mAddress
563 ), 'Block::updateTimestamp'
569 function getIntegerAddr()
571 return $this->mIntegerAddr;
574 function getNetworkBits()
576 return $this->mNetworkBits;
580 * @return The blocker user ID.
582 public function getBy() {
587 * @return The blocker user name.
591 if ( $this->mByName
=== false ) {
592 $this->mByName
= User
::whoIs( $this->mBy
);
594 return $this->mByName
;
597 function forUpdate( $x = NULL ) {
598 return wfSetVar( $this->mForUpdate
, $x );
601 function fromMaster( $x = NULL ) {
602 return wfSetVar( $this->mFromMaster
, $x );
605 function getRedactedName() {
606 if ( $this->mAuto
) {
607 return '#' . $this->mId
;
609 return $this->mAddress
;
614 * Encode expiry for DB
616 static function encodeExpiry( $expiry, $db ) {
617 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
618 return Block
::infinity();
620 return $db->timestamp( $expiry );
625 * Decode expiry which has come from the DB
627 static function decodeExpiry( $expiry ) {
628 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
629 return Block
::infinity();
631 return wfTimestamp( TS_MW
, $expiry );
635 static function getAutoblockExpiry( $timestamp )
637 global $wgAutoblockExpiry;
638 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
642 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
643 * For example, 127.111.113.151/24 -> 127.111.113.0/24
645 static function normaliseRange( $range ) {
646 $parts = explode( '/', $range );
647 if ( count( $parts ) == 2 ) {
649 if ( IP
::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
651 $ipint = IP
::toUnsigned6( $parts[0] );
652 # Native 32 bit functions WONT work here!!!
653 # Convert to a padded binary number
654 $network = wfBaseConvert( $ipint, 10, 2, 128 );
655 # Truncate the last (128-$bits) bits and replace them with zeros
656 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
657 # Convert back to an integer
658 $network = wfBaseConvert( $network, 2, 10 );
659 # Reform octet address
660 $newip = IP
::toOctet( $network );
661 $range = "$newip/{$parts[1]}";
663 else if ( IP
::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
664 $shift = 32 - $parts[1];
665 $ipint = IP
::toUnsigned( $parts[0] );
666 $ipint = $ipint >> $shift << $shift;
667 $newip = long2ip( $ipint );
668 $range = "$newip/{$parts[1]}";
675 * Purge expired blocks from the ipblocks table
677 static function purgeExpired() {
678 $dbw = wfGetDB( DB_MASTER
);
679 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
682 static function infinity() {
683 # This is a special keyword for timestamps in PostgreSQL, and
684 # works with CHAR(14) as well because "i" sorts after all numbers.
689 if ( !isset( $infinity ) ) {
690 $dbr = wfGetDB( DB_SLAVE );
691 $infinity = $dbr->bigTimestamp();