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 ) ) {
132 # TODO: improve performance by merging this query with the autoblock one
133 # Slightly tricky while handling killExpired as well
135 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
136 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
137 if ( $this->loadFromResult( $res, $killExpired ) ) {
138 if ( $user && $this->mAnonOnly
) {
139 # Block is marked anon-only
140 # Whitelist this IP address against autoblocks and range blocks
150 if ( $this->loadRange( $address, $killExpired, $user == 0 ) ) {
151 if ( $user && $this->mAnonOnly
) {
161 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
163 $conds['ipb_anon_only'] = 0;
165 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
166 if ( $this->loadFromResult( $res, $killExpired ) ) {
177 * Fill in member variables from a result wrapper
179 function loadFromResult( ResultWrapper
$res, $killExpired = true ) {
181 if ( 0 != $res->numRows() ) {
183 $row = $res->fetchObject();
184 $this->initFromRow( $row );
186 if ( $killExpired ) {
187 # If requested, delete expired rows
189 $killed = $this->deleteIfExpired();
191 $row = $res->fetchObject();
193 $this->initFromRow( $row );
196 } while ( $killed && $row );
198 # If there were any left after the killing finished, return true
211 * Search the database for any range blocks matching the given address, and
212 * load the row if one is found.
214 function loadRange( $address, $killExpired = true )
216 $iaddr = IP
::toHex( $address );
217 if ( $iaddr === false ) {
222 # Only scan ranges which start in this /16, this improves search speed
223 # Blocks should not cross a /16 boundary.
224 $range = substr( $iaddr, 0, 4 );
227 $db =& $this->getDBOptions( $options );
229 "ipb_range_start LIKE '$range%'",
230 "ipb_range_start <= '$iaddr'",
231 "ipb_range_end >= '$iaddr'"
234 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
235 $success = $this->loadFromResult( $res, $killExpired );
240 * Determine if a given integer IPv4 address is in a given CIDR network
241 * @deprecated Use IP::isInRange
243 function isAddressInRange( $addr, $range ) {
244 return IP
::isInRange( $addr, $range );
247 function initFromRow( $row )
249 $this->mAddress
= $row->ipb_address
;
250 $this->mReason
= $row->ipb_reason
;
251 $this->mTimestamp
= wfTimestamp(TS_MW
,$row->ipb_timestamp
);
252 $this->mUser
= $row->ipb_user
;
253 $this->mBy
= $row->ipb_by
;
254 $this->mAuto
= $row->ipb_auto
;
255 $this->mAnonOnly
= $row->ipb_anon_only
;
256 $this->mCreateAccount
= $row->ipb_create_account
;
257 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
258 $this->mId
= $row->ipb_id
;
259 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
260 if ( isset( $row->user_name
) ) {
261 $this->mByName
= $row->user_name
;
263 $this->mByName
= false;
265 $this->mRangeStart
= $row->ipb_range_start
;
266 $this->mRangeEnd
= $row->ipb_range_end
;
269 function initialiseRange()
271 $this->mRangeStart
= '';
272 $this->mRangeEnd
= '';
274 if ( $this->mUser
== 0 ) {
275 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
280 * Callback with a Block object for every block
281 * @return integer number of blocks;
283 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
285 global $wgAntiLockFlags;
287 $block = new Block();
288 if ( $flags & Block
::EB_FOR_UPDATE
) {
289 $db =& wfGetDB( DB_MASTER
);
290 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
293 $options = 'FOR UPDATE';
295 $block->forUpdate( true );
297 $db =& wfGetDB( DB_SLAVE
);
300 if ( $flags & Block
::EB_RANGE_ONLY
) {
301 $cond = " AND ipb_range_start <> ''";
306 $now = wfTimestampNow();
308 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
310 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
311 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
312 $res = $db->query( $sql, 'Block::enumBlocks' );
313 $num_rows = $db->numRows( $res );
315 while ( $row = $db->fetchObject( $res ) ) {
316 $block->initFromRow( $row );
317 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
321 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
322 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
325 call_user_func( $callback, $block, $tag );
328 call_user_func( $callback, $block, $tag );
331 $db->freeResult( $res );
341 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
344 $dbw =& wfGetDB( DB_MASTER
);
345 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
346 return $dbw->affectedRows() > 0;
350 * Insert a block into the block table.
351 *@return Whether or not the insertion was successful.
355 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
356 $dbw =& wfGetDB( DB_MASTER
);
359 # Unset ipb_anon_only for user blocks, makes no sense
360 if ( $this->mUser
) {
361 $this->mAnonOnly
= 0;
364 # Unset ipb_enable_autoblock for IP blocks, makes no sense
365 if ( !$this->mUser
) {
366 $this->mEnableAutoblock
= 0;
369 # Don't collide with expired blocks
370 Block
::purgeExpired();
372 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
373 $dbw->insert( 'ipblocks',
376 'ipb_address' => $this->mAddress
,
377 'ipb_user' => $this->mUser
,
378 'ipb_by' => $this->mBy
,
379 'ipb_reason' => $this->mReason
,
380 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
381 'ipb_auto' => $this->mAuto
,
382 'ipb_anon_only' => $this->mAnonOnly
,
383 'ipb_create_account' => $this->mCreateAccount
,
384 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
385 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
386 'ipb_range_start' => $this->mRangeStart
,
387 'ipb_range_end' => $this->mRangeEnd
,
388 ), 'Block::insert', array( 'IGNORE' )
390 $affected = $dbw->affectedRows();
394 $this->doRetroactiveAutoblock();
400 * Retroactively autoblocks the last IP used by the user (if it is a user)
401 * blocked by this Block.
402 *@return Whether or not a retroactive autoblock was made.
404 function doRetroactiveAutoblock() {
405 $dbr = wfGetDB( DB_SLAVE
);
406 #If autoblock is enabled, autoblock the LAST IP used
407 # - stolen shamelessly from CheckUser_body.php
409 if ($this->mEnableAutoblock
&& $this->mUser
) {
410 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
412 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress
),
413 __METHOD__
, array( 'ORDER BY' => 'rc_timestamp DESC' ) );
415 if ( !$row ||
!$row->rc_ip
) {
416 #No results, don't autoblock anything
417 wfDebug("No IP found to retroactively autoblock\n");
419 #Limit is 1, so no loop needed.
420 $retroblockip = $row->rc_ip
;
421 return $this->doAutoblock($retroblockip);
427 * Autoblocks the given IP, referring to this Block.
428 * @param $autoblockip The IP to autoblock.
429 * @return bool Whether or not an autoblock was inserted.
431 function doAutoblock( $autoblockip ) {
432 # Check if this IP address is already blocked
433 $dbw =& wfGetDB( DB_MASTER
);
436 # If autoblocks are disabled, go away.
437 if ( !$this->mEnableAutoblock
) {
441 # Check for presence on the autoblock whitelist
443 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
447 wfDebug("Checking the autoblock whitelist..\n");
449 foreach( $lines as $line ) {
451 if ( substr( $line, 0, 1 ) !== '*' ) {
455 $wlEntry = substr($line, 1);
456 $wlEntry = trim($wlEntry);
458 wfDebug("Checking $ip against $wlEntry...");
460 # Is the IP in this range?
461 if (IP
::isInRange( $ip, $wlEntry )) {
462 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
463 #$autoblockip = null; # Don't autoblock a whitelisted IP.
464 return; #This /SHOULD/ introduce a dummy block - but
465 # I don't know a safe way to do so. -werdna
467 wfDebug( " No match\n" );
471 # It's okay to autoblock. Go ahead and create/insert the block.
473 $ipblock = Block
::newFromDB( $autoblockip );
475 # If the user is already blocked. Then check if the autoblock would
476 # exceed the user block. If it would exceed, then do nothing, else
478 if ($this->mExpiry
&&
479 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
482 # Just update the timestamp
483 $ipblock->updateTimestamp();
486 $ipblock = new Block
;
489 # Make a new block object with the desired properties
490 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
491 $ipblock->mAddress
= $autoblockip;
493 $ipblock->mBy
= $this->mBy
;
494 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
495 $ipblock->mTimestamp
= wfTimestampNow();
497 $ipblock->mCreateAccount
= $this->mCreateAccount
;
499 # If the user is already blocked with an expiry date, we don't
500 # want to pile on top of that!
502 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
504 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
507 return $ipblock->insert();
510 function deleteIfExpired()
512 $fname = 'Block::deleteIfExpired';
513 wfProfileIn( $fname );
514 if ( $this->isExpired() ) {
515 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
519 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
522 wfProfileOut( $fname );
528 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
529 if ( !$this->mExpiry
) {
532 return wfTimestampNow() > $this->mExpiry
;
538 return $this->mAddress
!= '';
541 function updateTimestamp()
543 if ( $this->mAuto
) {
544 $this->mTimestamp
= wfTimestamp();
545 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
547 $dbw =& wfGetDB( DB_MASTER
);
548 $dbw->update( 'ipblocks',
550 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
551 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
552 ), array( /* WHERE */
553 'ipb_address' => $this->mAddress
554 ), 'Block::updateTimestamp'
560 function getIntegerAddr()
562 return $this->mIntegerAddr;
565 function getNetworkBits()
567 return $this->mNetworkBits;
571 * @return The blocker user ID.
573 public function getBy() {
578 * @return The blocker user name.
582 if ( $this->mByName
=== false ) {
583 $this->mByName
= User
::whoIs( $this->mBy
);
585 return $this->mByName
;
588 function forUpdate( $x = NULL ) {
589 return wfSetVar( $this->mForUpdate
, $x );
592 function fromMaster( $x = NULL ) {
593 return wfSetVar( $this->mFromMaster
, $x );
596 function getRedactedName() {
597 if ( $this->mAuto
) {
598 return '#' . $this->mId
;
600 return $this->mAddress
;
605 * Encode expiry for DB
607 static function encodeExpiry( $expiry, $db ) {
608 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
609 return Block
::infinity();
611 return $db->timestamp( $expiry );
616 * Decode expiry which has come from the DB
618 static function decodeExpiry( $expiry ) {
619 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
620 return Block
::infinity();
622 return wfTimestamp( TS_MW
, $expiry );
626 static function getAutoblockExpiry( $timestamp )
628 global $wgAutoblockExpiry;
629 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
632 static function normaliseRange( $range )
634 $parts = explode( '/', $range );
635 if ( count( $parts ) == 2 ) {
636 $shift = 32 - $parts[1];
637 $ipint = IP
::toUnsigned( $parts[0] );
638 $ipint = $ipint >> $shift << $shift;
639 $newip = long2ip( $ipint );
640 $range = "$newip/{$parts[1]}";
646 * Purge expired blocks from the ipblocks table
648 static function purgeExpired() {
649 $dbw =& wfGetDB( DB_MASTER
);
650 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
653 static function infinity() {
654 # This is a special keyword for timestamps in PostgreSQL, and
655 # works with CHAR(14) as well because "i" sorts after all numbers.
660 if ( !isset( $infinity ) ) {
661 $dbr =& wfGetDB( DB_SLAVE );
662 $infinity = $dbr->bigTimestamp();