3 * Blocks and bans object
9 * All the functions in this class assume the object is either explicitly
10 * loaded or filled. It is not load-on-demand. There are no accessors.
12 * Globals used: $wgAutoblockExpiry, $wgAntiLockFlags
14 * @todo This could be used everywhere, but it isn't.
19 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
20 $mRangeStart, $mRangeEnd, $mAnonOnly;
21 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster, $mByName;
23 const EB_KEEP_EXPIRED
= 1;
24 const EB_FOR_UPDATE
= 2;
25 const EB_RANGE_ONLY
= 4;
27 function Block( $address = '', $user = 0, $by = 0, $reason = '',
28 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0 )
31 $this->mAddress
= $address;
34 $this->mReason
= $reason;
35 $this->mTimestamp
= wfTimestamp(TS_MW
,$timestamp);
37 $this->mAnonOnly
= $anonOnly;
38 $this->mCreateAccount
= $createAccount;
39 $this->mExpiry
= self
::decodeExpiry( $expiry );
41 $this->mForUpdate
= false;
42 $this->mFromMaster
= false;
43 $this->mByName
= false;
44 $this->initialiseRange();
47 static function newFromDB( $address, $user = 0, $killExpired = true )
50 $block->load( $address, $user, $killExpired );
51 if ( $block->isValid() ) {
58 static function newFromID( $id )
60 $dbr =& wfGetDB( DB_SLAVE
);
61 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
62 array( 'ipb_id' => $id ), __METHOD__
) );
64 if ( $block->loadFromResult( $res ) ) {
73 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
74 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
75 $this->mAuto
= $this->mUser
= $this->mBy
= 0;
76 $this->mByName
= false;
80 * Get the DB object and set the reference parameter to the query options
82 function &getDBOptions( &$options )
84 global $wgAntiLockFlags;
85 if ( $this->mForUpdate ||
$this->mFromMaster
) {
86 $db =& wfGetDB( DB_MASTER
);
87 if ( !$this->mForUpdate ||
($wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) ) {
90 $options = array( 'FOR UPDATE' );
93 $db =& wfGetDB( DB_SLAVE
);
100 * Get a ban from the DB, with either the given address or the given username
102 * @param string $address The IP address of the user, or blank to skip IP blocks
103 * @param integer $user The user ID, or zero for anonymous users
104 * @param bool $killExpired Whether to delete expired rows while loading
107 function load( $address = '', $user = 0, $killExpired = true )
109 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
112 $db =& $this->getDBOptions( $options );
117 if ( 0 == $user && $address == '' ) {
118 # Invalid user specification, not blocked
125 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
126 __METHOD__
, $options ) );
127 if ( $this->loadFromResult( $res, $killExpired ) ) {
133 # TODO: improve performance by merging this query with the autoblock one
134 # Slightly tricky while handling killExpired as well
136 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
137 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
138 if ( $this->loadFromResult( $res, $killExpired ) ) {
139 if ( $user && $this->mAnonOnly
) {
140 # Block is marked anon-only
141 # Whitelist this IP address against autoblocks and range blocks
151 if ( $this->loadRange( $address, $killExpired, $user == 0 ) ) {
152 if ( $user && $this->mAnonOnly
) {
162 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
164 $conds['ipb_anon_only'] = 0;
166 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
167 if ( $this->loadFromResult( $res, $killExpired ) ) {
178 * Fill in member variables from a result wrapper
180 function loadFromResult( ResultWrapper
$res, $killExpired = true ) {
182 if ( 0 != $res->numRows() ) {
184 $row = $res->fetchObject();
185 $this->initFromRow( $row );
187 if ( $killExpired ) {
188 # If requested, delete expired rows
190 $killed = $this->deleteIfExpired();
192 $row = $res->fetchObject();
194 $this->initFromRow( $row );
197 } while ( $killed && $row );
199 # If there were any left after the killing finished, return true
212 * Search the database for any range blocks matching the given address, and
213 * load the row if one is found.
215 function loadRange( $address, $killExpired = true )
217 $iaddr = IP
::toHex( $address );
218 if ( $iaddr === false ) {
223 # Only scan ranges which start in this /16, this improves search speed
224 # Blocks should not cross a /16 boundary.
225 $range = substr( $iaddr, 0, 4 );
228 $db =& $this->getDBOptions( $options );
230 "ipb_range_start LIKE '$range%'",
231 "ipb_range_start <= '$iaddr'",
232 "ipb_range_end >= '$iaddr'"
235 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
236 $success = $this->loadFromResult( $res, $killExpired );
241 * Determine if a given integer IPv4 address is in a given CIDR network
243 function isAddressInRange( $addr, $range ) {
244 list( $network, $bits ) = wfParseCIDR( $range );
245 if ( $network !== false && $addr >> ( 32 - $bits ) == $network >> ( 32 - $bits ) ) {
252 function initFromRow( $row )
254 $this->mAddress
= $row->ipb_address
;
255 $this->mReason
= $row->ipb_reason
;
256 $this->mTimestamp
= wfTimestamp(TS_MW
,$row->ipb_timestamp
);
257 $this->mUser
= $row->ipb_user
;
258 $this->mBy
= $row->ipb_by
;
259 $this->mAuto
= $row->ipb_auto
;
260 $this->mAnonOnly
= $row->ipb_anon_only
;
261 $this->mCreateAccount
= $row->ipb_create_account
;
262 $this->mId
= $row->ipb_id
;
263 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
264 if ( isset( $row->user_name
) ) {
265 $this->mByName
= $row->user_name
;
267 $this->mByName
= false;
269 $this->mRangeStart
= $row->ipb_range_start
;
270 $this->mRangeEnd
= $row->ipb_range_end
;
273 function initialiseRange()
275 $this->mRangeStart
= '';
276 $this->mRangeEnd
= '';
277 if ( $this->mUser
== 0 ) {
278 list( $network, $bits ) = wfParseCIDR( $this->mAddress
);
279 if ( $network !== false ) {
280 $this->mRangeStart
= sprintf( '%08X', $network );
281 $this->mRangeEnd
= sprintf( '%08X', $network +
(1 << (32 - $bits)) - 1 );
287 * Callback with a Block object for every block
288 * @return integer number of blocks;
290 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
292 global $wgAntiLockFlags;
294 $block = new Block();
295 if ( $flags & Block
::EB_FOR_UPDATE
) {
296 $db =& wfGetDB( DB_MASTER
);
297 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
300 $options = 'FOR UPDATE';
302 $block->forUpdate( true );
304 $db =& wfGetDB( DB_SLAVE
);
307 if ( $flags & Block
::EB_RANGE_ONLY
) {
308 $cond = " AND ipb_range_start <> ''";
313 $now = wfTimestampNow();
315 extract( $db->tableNames( 'ipblocks', 'user' ) );
317 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
318 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
319 $res = $db->query( $sql, 'Block::enumBlocks' );
320 $num_rows = $db->numRows( $res );
322 while ( $row = $db->fetchObject( $res ) ) {
323 $block->initFromRow( $row );
324 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
328 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
329 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
332 call_user_func( $callback, $block, $tag );
335 call_user_func( $callback, $block, $tag );
338 wfFreeResult( $res );
348 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
351 $dbw =& wfGetDB( DB_MASTER
);
352 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
353 return $dbw->affectedRows() > 0;
358 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
359 $dbw =& wfGetDB( DB_MASTER
);
362 # Unset ipb_anon_only for user blocks, makes no sense
363 if ( $this->mUser
) {
364 $this->mAnonOnly
= 0;
367 # Don't collide with expired blocks
368 Block
::purgeExpired();
370 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
371 $dbw->insert( 'ipblocks',
374 'ipb_address' => $this->mAddress
,
375 'ipb_user' => $this->mUser
,
376 'ipb_by' => $this->mBy
,
377 'ipb_reason' => $this->mReason
,
378 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
379 'ipb_auto' => $this->mAuto
,
380 'ipb_anon_only' => $this->mAnonOnly
,
381 'ipb_create_account' => $this->mCreateAccount
,
382 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
383 'ipb_range_start' => $this->mRangeStart
,
384 'ipb_range_end' => $this->mRangeEnd
,
385 ), 'Block::insert', array( 'IGNORE' )
387 $affected = $dbw->affectedRows();
392 function deleteIfExpired()
394 $fname = 'Block::deleteIfExpired';
395 wfProfileIn( $fname );
396 if ( $this->isExpired() ) {
397 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
401 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
404 wfProfileOut( $fname );
410 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
411 if ( !$this->mExpiry
) {
414 return wfTimestampNow() > $this->mExpiry
;
420 return $this->mAddress
!= '';
423 function updateTimestamp()
425 if ( $this->mAuto
) {
426 $this->mTimestamp
= wfTimestamp();
427 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
429 $dbw =& wfGetDB( DB_MASTER
);
430 $dbw->update( 'ipblocks',
432 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
433 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
434 ), array( /* WHERE */
435 'ipb_address' => $this->mAddress
436 ), 'Block::updateTimestamp'
442 function getIntegerAddr()
444 return $this->mIntegerAddr;
447 function getNetworkBits()
449 return $this->mNetworkBits;
454 if ( $this->mByName
=== false ) {
455 $this->mByName
= User
::whoIs( $this->mBy
);
457 return $this->mByName
;
460 function forUpdate( $x = NULL ) {
461 return wfSetVar( $this->mForUpdate
, $x );
464 function fromMaster( $x = NULL ) {
465 return wfSetVar( $this->mFromMaster
, $x );
468 function getRedactedName() {
469 if ( $this->mAuto
) {
470 return '#' . $this->mId
;
472 return $this->mAddress
;
477 * Encode expiry for DB
479 static function encodeExpiry( $expiry, $db ) {
480 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
481 return Block
::infinity();
483 return $db->timestamp( $expiry );
488 * Decode expiry which has come from the DB
490 static function decodeExpiry( $expiry ) {
491 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
492 return Block
::infinity();
494 return wfTimestamp( TS_MW
, $expiry );
498 static function getAutoblockExpiry( $timestamp )
500 global $wgAutoblockExpiry;
501 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
504 static function normaliseRange( $range )
506 $parts = explode( '/', $range );
507 if ( count( $parts ) == 2 ) {
508 $shift = 32 - $parts[1];
509 $ipint = IP
::toUnsigned( $parts[0] );
510 $ipint = $ipint >> $shift << $shift;
511 $newip = long2ip( $ipint );
512 $range = "$newip/{$parts[1]}";
518 * Purge expired blocks from the ipblocks table
520 static function purgeExpired() {
521 $dbw =& wfGetDB( DB_MASTER
);
522 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
525 static function infinity() {
526 # This is a special keyword for timestamps in PostgreSQL, and
527 # works with CHAR(14) as well because "i" sorts after all numbers.
532 if ( !isset( $infinity ) ) {
533 $dbr =& wfGetDB( DB_SLAVE );
534 $infinity = $dbr->bigTimestamp();