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 );
116 if ( 0 == $user && $address == '' ) {
117 # Invalid user specification, not blocked
124 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
125 __METHOD__
, $options ) );
126 if ( $this->loadFromResult( $res, $killExpired ) ) {
130 $userObject = User
::newFromId($user);
132 if ($userObject->isAllowed('ipblock-exempt') ) {
138 # TODO: improve performance by merging this query with the autoblock one
139 # Slightly tricky while handling killExpired as well
141 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
142 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
143 if ( $this->loadFromResult( $res, $killExpired ) ) {
144 if ( $user && $this->mAnonOnly
) {
145 # Block is marked anon-only
146 # Whitelist this IP address against autoblocks and range blocks
156 if ( $this->loadRange( $address, $killExpired, $user == 0 ) ) {
157 if ( $user && $this->mAnonOnly
) {
167 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
169 $conds['ipb_anon_only'] = 0;
171 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
172 if ( $this->loadFromResult( $res, $killExpired ) ) {
183 * Fill in member variables from a result wrapper
185 function loadFromResult( ResultWrapper
$res, $killExpired = true ) {
187 if ( 0 != $res->numRows() ) {
189 $row = $res->fetchObject();
190 $this->initFromRow( $row );
192 if ( $killExpired ) {
193 # If requested, delete expired rows
195 $killed = $this->deleteIfExpired();
197 $row = $res->fetchObject();
199 $this->initFromRow( $row );
202 } while ( $killed && $row );
204 # If there were any left after the killing finished, return true
217 * Search the database for any range blocks matching the given address, and
218 * load the row if one is found.
220 function loadRange( $address, $killExpired = true )
222 $iaddr = IP
::toHex( $address );
223 if ( $iaddr === false ) {
228 # Only scan ranges which start in this /16, this improves search speed
229 # Blocks should not cross a /16 boundary.
230 $range = substr( $iaddr, 0, 4 );
233 $db =& $this->getDBOptions( $options );
235 "ipb_range_start LIKE '$range%'",
236 "ipb_range_start <= '$iaddr'",
237 "ipb_range_end >= '$iaddr'"
240 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
241 $success = $this->loadFromResult( $res, $killExpired );
246 * Determine if a given integer IPv4 address is in a given CIDR network
247 * @deprecated Use IP::isInRange
249 function isAddressInRange( $addr, $range ) {
250 return IP
::isInRange( $addr, $range );
253 function initFromRow( $row )
255 $this->mAddress
= $row->ipb_address
;
256 $this->mReason
= $row->ipb_reason
;
257 $this->mTimestamp
= wfTimestamp(TS_MW
,$row->ipb_timestamp
);
258 $this->mUser
= $row->ipb_user
;
259 $this->mBy
= $row->ipb_by
;
260 $this->mAuto
= $row->ipb_auto
;
261 $this->mAnonOnly
= $row->ipb_anon_only
;
262 $this->mCreateAccount
= $row->ipb_create_account
;
263 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
264 $this->mId
= $row->ipb_id
;
265 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
266 if ( isset( $row->user_name
) ) {
267 $this->mByName
= $row->user_name
;
269 $this->mByName
= false;
271 $this->mRangeStart
= $row->ipb_range_start
;
272 $this->mRangeEnd
= $row->ipb_range_end
;
275 function initialiseRange()
277 $this->mRangeStart
= '';
278 $this->mRangeEnd
= '';
280 if ( $this->mUser
== 0 ) {
281 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
286 * Callback with a Block object for every block
287 * @return integer number of blocks;
289 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
291 global $wgAntiLockFlags;
293 $block = new Block();
294 if ( $flags & Block
::EB_FOR_UPDATE
) {
295 $db =& wfGetDB( DB_MASTER
);
296 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
299 $options = 'FOR UPDATE';
301 $block->forUpdate( true );
303 $db =& wfGetDB( DB_SLAVE
);
306 if ( $flags & Block
::EB_RANGE_ONLY
) {
307 $cond = " AND ipb_range_start <> ''";
312 $now = wfTimestampNow();
314 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
316 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
317 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
318 $res = $db->query( $sql, 'Block::enumBlocks' );
319 $num_rows = $db->numRows( $res );
321 while ( $row = $db->fetchObject( $res ) ) {
322 $block->initFromRow( $row );
323 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
327 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
328 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
331 call_user_func( $callback, $block, $tag );
334 call_user_func( $callback, $block, $tag );
337 $db->freeResult( $res );
347 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
350 $dbw =& wfGetDB( DB_MASTER
);
351 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
352 return $dbw->affectedRows() > 0;
356 * Insert a block into the block table.
357 *@return Whether or not the insertion was successful.
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();
400 $this->doRetroactiveAutoblock();
406 * Retroactively autoblocks the last IP used by the user (if it is a user)
407 * blocked by this Block.
408 *@return Whether or not a retroactive autoblock was made.
410 function doRetroactiveAutoblock() {
411 $dbr = wfGetDB( DB_SLAVE
);
412 #If autoblock is enabled, autoblock the LAST IP used
413 # - stolen shamelessly from CheckUser_body.php
415 if ($this->mEnableAutoblock
&& $this->mUser
) {
416 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
418 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress
),
419 __METHOD__
, array( 'ORDER BY' => 'rc_timestamp DESC' ) );
421 if ( !$row ||
!$row->rc_ip
) {
422 #No results, don't autoblock anything
423 wfDebug("No IP found to retroactively autoblock\n");
425 #Limit is 1, so no loop needed.
426 $retroblockip = $row->rc_ip
;
427 return $this->doAutoblock($retroblockip);
433 * Autoblocks the given IP, referring to this Block.
434 * @param $autoblockip The IP to autoblock.
435 * @return bool Whether or not an autoblock was inserted.
437 function doAutoblock( $autoblockip ) {
438 # Check if this IP address is already blocked
439 $dbw =& wfGetDB( DB_MASTER
);
442 # If autoblocks are disabled, go away.
443 if ( !$this->mEnableAutoblock
) {
447 # Check for presence on the autoblock whitelist
449 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
453 wfDebug("Checking the autoblock whitelist..\n");
455 foreach( $lines as $line ) {
457 if ( substr( $line, 0, 1 ) !== '*' ) {
461 $wlEntry = substr($line, 1);
462 $wlEntry = trim($wlEntry);
464 wfDebug("Checking $ip against $wlEntry...");
466 # Is the IP in this range?
467 if (IP
::isInRange( $ip, $wlEntry )) {
468 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
469 #$autoblockip = null; # Don't autoblock a whitelisted IP.
470 return; #This /SHOULD/ introduce a dummy block - but
471 # I don't know a safe way to do so. -werdna
473 wfDebug( " No match\n" );
477 # It's okay to autoblock. Go ahead and create/insert the block.
479 $ipblock = Block
::newFromDB( $autoblockip );
481 # If the user is already blocked. Then check if the autoblock would
482 # exceed the user block. If it would exceed, then do nothing, else
484 if ($this->mExpiry
&&
485 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
488 # Just update the timestamp
489 $ipblock->updateTimestamp();
492 $ipblock = new Block
;
495 # Make a new block object with the desired properties
496 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
497 $ipblock->mAddress
= $autoblockip;
499 $ipblock->mBy
= $this->mBy
;
500 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
501 $ipblock->mTimestamp
= wfTimestampNow();
503 $ipblock->mCreateAccount
= $this->mCreateAccount
;
505 # If the user is already blocked with an expiry date, we don't
506 # want to pile on top of that!
508 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
510 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
513 return $ipblock->insert();
516 function deleteIfExpired()
518 $fname = 'Block::deleteIfExpired';
519 wfProfileIn( $fname );
520 if ( $this->isExpired() ) {
521 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
525 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
528 wfProfileOut( $fname );
534 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
535 if ( !$this->mExpiry
) {
538 return wfTimestampNow() > $this->mExpiry
;
544 return $this->mAddress
!= '';
547 function updateTimestamp()
549 if ( $this->mAuto
) {
550 $this->mTimestamp
= wfTimestamp();
551 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
553 $dbw =& wfGetDB( DB_MASTER
);
554 $dbw->update( 'ipblocks',
556 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
557 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
558 ), array( /* WHERE */
559 'ipb_address' => $this->mAddress
560 ), 'Block::updateTimestamp'
566 function getIntegerAddr()
568 return $this->mIntegerAddr;
571 function getNetworkBits()
573 return $this->mNetworkBits;
577 * @return The blocker user ID.
579 public function getBy() {
584 * @return The blocker user name.
588 if ( $this->mByName
=== false ) {
589 $this->mByName
= User
::whoIs( $this->mBy
);
591 return $this->mByName
;
594 function forUpdate( $x = NULL ) {
595 return wfSetVar( $this->mForUpdate
, $x );
598 function fromMaster( $x = NULL ) {
599 return wfSetVar( $this->mFromMaster
, $x );
602 function getRedactedName() {
603 if ( $this->mAuto
) {
604 return '#' . $this->mId
;
606 return $this->mAddress
;
611 * Encode expiry for DB
613 static function encodeExpiry( $expiry, $db ) {
614 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
615 return Block
::infinity();
617 return $db->timestamp( $expiry );
622 * Decode expiry which has come from the DB
624 static function decodeExpiry( $expiry ) {
625 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
626 return Block
::infinity();
628 return wfTimestamp( TS_MW
, $expiry );
632 static function getAutoblockExpiry( $timestamp )
634 global $wgAutoblockExpiry;
635 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
638 static function normaliseRange( $range )
640 $parts = explode( '/', $range );
641 if ( count( $parts ) == 2 ) {
642 $shift = 32 - $parts[1];
643 $ipint = IP
::toUnsigned( $parts[0] );
644 $ipint = $ipint >> $shift << $shift;
645 $newip = long2ip( $ipint );
646 $range = "$newip/{$parts[1]}";
652 * Purge expired blocks from the ipblocks table
654 static function purgeExpired() {
655 $dbw =& wfGetDB( DB_MASTER
);
656 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
659 static function infinity() {
660 # This is a special keyword for timestamps in PostgreSQL, and
661 # works with CHAR(14) as well because "i" sorts after all numbers.
666 if ( !isset( $infinity ) ) {
667 $dbr =& wfGetDB( DB_SLAVE );
668 $infinity = $dbr->bigTimestamp();