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, $mEnableAutoblock;
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, $enableAutoblock = 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 );
40 $this->mEnableAutoblock
= $enableAutoblock;
42 $this->mForUpdate
= false;
43 $this->mFromMaster
= false;
44 $this->mByName
= false;
45 $this->initialiseRange();
48 static function newFromDB( $address, $user = 0, $killExpired = true )
51 $block->load( $address, $user, $killExpired );
52 if ( $block->isValid() ) {
59 static function newFromID( $id )
61 $dbr =& wfGetDB( DB_SLAVE
);
62 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
63 array( 'ipb_id' => $id ), __METHOD__
) );
65 if ( $block->loadFromResult( $res ) ) {
74 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
75 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
76 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
78 $this->mByName
= false;
82 * Get the DB object and set the reference parameter to the query options
84 function &getDBOptions( &$options )
86 global $wgAntiLockFlags;
87 if ( $this->mForUpdate ||
$this->mFromMaster
) {
88 $db =& wfGetDB( DB_MASTER
);
89 if ( !$this->mForUpdate ||
($wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) ) {
92 $options = array( 'FOR UPDATE' );
95 $db =& wfGetDB( DB_SLAVE
);
102 * Get a ban from the DB, with either the given address or the given username
104 * @param string $address The IP address of the user, or blank to skip IP blocks
105 * @param integer $user The user ID, or zero for anonymous users
106 * @param bool $killExpired Whether to delete expired rows while loading
109 function load( $address = '', $user = 0, $killExpired = true )
111 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
114 $db =& $this->getDBOptions( $options );
119 if ( 0 == $user && $address == '' ) {
120 # Invalid user specification, not blocked
127 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
128 __METHOD__
, $options ) );
129 if ( $this->loadFromResult( $res, $killExpired ) ) {
135 # TODO: improve performance by merging this query with the autoblock one
136 # Slightly tricky while handling killExpired as well
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
153 if ( $this->loadRange( $address, $killExpired, $user == 0 ) ) {
154 if ( $user && $this->mAnonOnly
) {
164 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
166 $conds['ipb_anon_only'] = 0;
168 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
169 if ( $this->loadFromResult( $res, $killExpired ) ) {
180 * Fill in member variables from a result wrapper
182 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 )
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'"
237 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
238 $success = $this->loadFromResult( $res, $killExpired );
243 * Determine if a given integer IPv4 address is in a given CIDR network
245 function isAddressInRange( $addr, $range ) {
246 list( $network, $bits ) = wfParseCIDR( $range );
247 if ( $network !== false && $addr >> ( 32 - $bits ) == $network >> ( 32 - $bits ) ) {
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->mId
= $row->ipb_id
;
266 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
267 if ( isset( $row->user_name
) ) {
268 $this->mByName
= $row->user_name
;
270 $this->mByName
= false;
272 $this->mRangeStart
= $row->ipb_range_start
;
273 $this->mRangeEnd
= $row->ipb_range_end
;
276 function initialiseRange()
278 $this->mRangeStart
= '';
279 $this->mRangeEnd
= '';
280 if ( $this->mUser
== 0 ) {
281 list( $network, $bits ) = wfParseCIDR( $this->mAddress
);
282 if ( $network !== false ) {
283 $this->mRangeStart
= sprintf( '%08X', $network );
284 $this->mRangeEnd
= sprintf( '%08X', $network +
(1 << (32 - $bits)) - 1 );
290 * Callback with a Block object for every block
291 * @return integer number of blocks;
293 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
295 global $wgAntiLockFlags;
297 $block = new Block();
298 if ( $flags & Block
::EB_FOR_UPDATE
) {
299 $db =& wfGetDB( DB_MASTER
);
300 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
303 $options = 'FOR UPDATE';
305 $block->forUpdate( true );
307 $db =& wfGetDB( DB_SLAVE
);
310 if ( $flags & Block
::EB_RANGE_ONLY
) {
311 $cond = " AND ipb_range_start <> ''";
316 $now = wfTimestampNow();
318 extract( $db->tableNames( 'ipblocks', 'user' ) );
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 );
325 while ( $row = $db->fetchObject( $res ) ) {
326 $block->initFromRow( $row );
327 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
331 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
332 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
335 call_user_func( $callback, $block, $tag );
338 call_user_func( $callback, $block, $tag );
341 wfFreeResult( $res );
351 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
354 $dbw =& wfGetDB( DB_MASTER
);
355 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
356 return $dbw->affectedRows() > 0;
361 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
362 $dbw =& wfGetDB( DB_MASTER
);
365 # Unset ipb_anon_only for user blocks, makes no sense
366 if ( $this->mUser
) {
367 $this->mAnonOnly
= 0;
370 # Unset ipb_enable_autoblock for IP blocks, makes no sense
371 if ( !$this->mUser
) {
372 $this->mEnableAutoblock
= 0;
375 # Don't collide with expired blocks
376 Block
::purgeExpired();
378 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
379 $dbw->insert( 'ipblocks',
382 'ipb_address' => $this->mAddress
,
383 'ipb_user' => $this->mUser
,
384 'ipb_by' => $this->mBy
,
385 'ipb_reason' => $this->mReason
,
386 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
387 'ipb_auto' => $this->mAuto
,
388 'ipb_anon_only' => $this->mAnonOnly
,
389 'ipb_create_account' => $this->mCreateAccount
,
390 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
391 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
392 'ipb_range_start' => $this->mRangeStart
,
393 'ipb_range_end' => $this->mRangeEnd
,
394 ), 'Block::insert', array( 'IGNORE' )
396 $affected = $dbw->affectedRows();
401 function deleteIfExpired()
403 $fname = 'Block::deleteIfExpired';
404 wfProfileIn( $fname );
405 if ( $this->isExpired() ) {
406 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
410 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
413 wfProfileOut( $fname );
419 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
420 if ( !$this->mExpiry
) {
423 return wfTimestampNow() > $this->mExpiry
;
429 return $this->mAddress
!= '';
432 function updateTimestamp()
434 if ( $this->mAuto
) {
435 $this->mTimestamp
= wfTimestamp();
436 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
438 $dbw =& wfGetDB( DB_MASTER
);
439 $dbw->update( 'ipblocks',
441 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
442 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
443 ), array( /* WHERE */
444 'ipb_address' => $this->mAddress
445 ), 'Block::updateTimestamp'
451 function getIntegerAddr()
453 return $this->mIntegerAddr;
456 function getNetworkBits()
458 return $this->mNetworkBits;
463 if ( $this->mByName
=== false ) {
464 $this->mByName
= User
::whoIs( $this->mBy
);
466 return $this->mByName
;
469 function forUpdate( $x = NULL ) {
470 return wfSetVar( $this->mForUpdate
, $x );
473 function fromMaster( $x = NULL ) {
474 return wfSetVar( $this->mFromMaster
, $x );
477 function getRedactedName() {
478 if ( $this->mAuto
) {
479 return '#' . $this->mId
;
481 return $this->mAddress
;
486 * Encode expiry for DB
488 static function encodeExpiry( $expiry, $db ) {
489 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
490 return Block
::infinity();
492 return $db->timestamp( $expiry );
497 * Decode expiry which has come from the DB
499 static function decodeExpiry( $expiry ) {
500 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
501 return Block
::infinity();
503 return wfTimestamp( TS_MW
, $expiry );
507 static function getAutoblockExpiry( $timestamp )
509 global $wgAutoblockExpiry;
510 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
513 static function normaliseRange( $range )
515 $parts = explode( '/', $range );
516 if ( count( $parts ) == 2 ) {
517 $shift = 32 - $parts[1];
518 $ipint = IP
::toUnsigned( $parts[0] );
519 $ipint = $ipint >> $shift << $shift;
520 $newip = long2ip( $ipint );
521 $range = "$newip/{$parts[1]}";
527 * Purge expired blocks from the ipblocks table
529 static function purgeExpired() {
530 $dbw =& wfGetDB( DB_MASTER
);
531 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
534 static function infinity() {
535 # This is a special keyword for timestamps in PostgreSQL, and
536 # works with CHAR(14) as well because "i" sorts after all numbers.
541 if ( !isset( $infinity ) ) {
542 $dbr =& wfGetDB( DB_SLAVE );
543 $infinity = $dbr->bigTimestamp();