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;
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 )
29 # Expand valid IPv6 addresses
30 $address = IP
::sanitizeIP( $address );
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 ) ) {
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 )
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, $user = 0 )
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'"
236 $conds['ipb_anon_only'] = 0;
239 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
240 $success = $this->loadFromResult( $res, $killExpired );
245 * Determine if a given integer IPv4 address is in a given CIDR network
246 * @deprecated Use IP::isInRange
248 function isAddressInRange( $addr, $range ) {
249 return IP
::isInRange( $addr, $range );
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->mEnableAutoblock
= $row->ipb_enable_autoblock
;
263 $this->mId
= $row->ipb_id
;
264 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
265 if ( isset( $row->user_name
) ) {
266 $this->mByName
= $row->user_name
;
268 $this->mByName
= false;
270 $this->mRangeStart
= $row->ipb_range_start
;
271 $this->mRangeEnd
= $row->ipb_range_end
;
274 function initialiseRange()
276 $this->mRangeStart
= '';
277 $this->mRangeEnd
= '';
279 if ( $this->mUser
== 0 ) {
280 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
285 * Callback with a Block object for every block
286 * @return integer number of blocks;
288 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
290 global $wgAntiLockFlags;
292 $block = new Block();
293 if ( $flags & Block
::EB_FOR_UPDATE
) {
294 $db = wfGetDB( DB_MASTER
);
295 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
298 $options = 'FOR UPDATE';
300 $block->forUpdate( true );
302 $db = wfGetDB( DB_SLAVE
);
305 if ( $flags & Block
::EB_RANGE_ONLY
) {
306 $cond = " AND ipb_range_start <> ''";
311 $now = wfTimestampNow();
313 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
315 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
316 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
317 $res = $db->query( $sql, 'Block::enumBlocks' );
318 $num_rows = $db->numRows( $res );
320 while ( $row = $db->fetchObject( $res ) ) {
321 $block->initFromRow( $row );
322 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
326 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
327 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
330 call_user_func( $callback, $block, $tag );
333 call_user_func( $callback, $block, $tag );
336 $db->freeResult( $res );
346 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
349 $dbw = wfGetDB( DB_MASTER
);
350 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
351 return $dbw->affectedRows() > 0;
355 * Insert a block into the block table.
356 *@return Whether or not the insertion was successful.
360 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
361 $dbw = wfGetDB( DB_MASTER
);
364 # Unset ipb_anon_only for user blocks, makes no sense
365 if ( $this->mUser
) {
366 $this->mAnonOnly
= 0;
369 # Unset ipb_enable_autoblock for IP blocks, makes no sense
370 if ( !$this->mUser
) {
371 $this->mEnableAutoblock
= 0;
374 # Don't collide with expired blocks
375 Block
::purgeExpired();
377 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
378 $dbw->insert( 'ipblocks',
381 'ipb_address' => $this->mAddress
,
382 'ipb_user' => $this->mUser
,
383 'ipb_by' => $this->mBy
,
384 'ipb_reason' => $this->mReason
,
385 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
386 'ipb_auto' => $this->mAuto
,
387 'ipb_anon_only' => $this->mAnonOnly
,
388 'ipb_create_account' => $this->mCreateAccount
,
389 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
390 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
391 'ipb_range_start' => $this->mRangeStart
,
392 'ipb_range_end' => $this->mRangeEnd
,
393 ), 'Block::insert', array( 'IGNORE' )
395 $affected = $dbw->affectedRows();
399 $this->doRetroactiveAutoblock();
405 * Retroactively autoblocks the last IP used by the user (if it is a user)
406 * blocked by this Block.
407 *@return Whether or not a retroactive autoblock was made.
409 function doRetroactiveAutoblock() {
410 $dbr = wfGetDB( DB_SLAVE
);
411 #If autoblock is enabled, autoblock the LAST IP used
412 # - stolen shamelessly from CheckUser_body.php
414 if ($this->mEnableAutoblock
&& $this->mUser
) {
415 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
417 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress
),
418 __METHOD__
, array( 'ORDER BY' => 'rc_timestamp DESC' ) );
420 if ( !$row ||
!$row->rc_ip
) {
421 #No results, don't autoblock anything
422 wfDebug("No IP found to retroactively autoblock\n");
424 #Limit is 1, so no loop needed.
425 $retroblockip = $row->rc_ip
;
426 return $this->doAutoblock($retroblockip);
432 * Autoblocks the given IP, referring to this Block.
433 * @param $autoblockip The IP to autoblock.
434 * @return bool Whether or not an autoblock was inserted.
436 function doAutoblock( $autoblockip ) {
437 # Check if this IP address is already blocked
438 $dbw = wfGetDB( DB_MASTER
);
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 $ipblock->updateTimestamp();
491 $ipblock = new Block
;
494 # Make a new block object with the desired properties
495 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
496 $ipblock->mAddress
= $autoblockip;
498 $ipblock->mBy
= $this->mBy
;
499 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
500 $ipblock->mTimestamp
= wfTimestampNow();
502 $ipblock->mCreateAccount
= $this->mCreateAccount
;
504 # If the user is already blocked with an expiry date, we don't
505 # want to pile on top of that!
507 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
509 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
512 return $ipblock->insert();
515 function deleteIfExpired()
517 $fname = 'Block::deleteIfExpired';
518 wfProfileIn( $fname );
519 if ( $this->isExpired() ) {
520 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
524 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
527 wfProfileOut( $fname );
533 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
534 if ( !$this->mExpiry
) {
537 return wfTimestampNow() > $this->mExpiry
;
543 return $this->mAddress
!= '';
546 function updateTimestamp()
548 if ( $this->mAuto
) {
549 $this->mTimestamp
= wfTimestamp();
550 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
552 $dbw = wfGetDB( DB_MASTER
);
553 $dbw->update( 'ipblocks',
555 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
556 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
557 ), array( /* WHERE */
558 'ipb_address' => $this->mAddress
559 ), 'Block::updateTimestamp'
565 function getIntegerAddr()
567 return $this->mIntegerAddr;
570 function getNetworkBits()
572 return $this->mNetworkBits;
576 * @return The blocker user ID.
578 public function getBy() {
583 * @return The blocker user name.
587 if ( $this->mByName
=== false ) {
588 $this->mByName
= User
::whoIs( $this->mBy
);
590 return $this->mByName
;
593 function forUpdate( $x = NULL ) {
594 return wfSetVar( $this->mForUpdate
, $x );
597 function fromMaster( $x = NULL ) {
598 return wfSetVar( $this->mFromMaster
, $x );
601 function getRedactedName() {
602 if ( $this->mAuto
) {
603 return '#' . $this->mId
;
605 return $this->mAddress
;
610 * Encode expiry for DB
612 static function encodeExpiry( $expiry, $db ) {
613 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
614 return Block
::infinity();
616 return $db->timestamp( $expiry );
621 * Decode expiry which has come from the DB
623 static function decodeExpiry( $expiry ) {
624 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
625 return Block
::infinity();
627 return wfTimestamp( TS_MW
, $expiry );
631 static function getAutoblockExpiry( $timestamp )
633 global $wgAutoblockExpiry;
634 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
637 static function normaliseRange( $range )
639 $parts = explode( '/', $range );
640 if ( count( $parts ) == 2 ) {
641 $shift = 32 - $parts[1];
642 $ipint = IP
::toUnsigned( $parts[0] );
643 $ipint = $ipint >> $shift << $shift;
644 $newip = long2ip( $ipint );
645 $range = "$newip/{$parts[1]}";
651 static function normaliseRange6( $range ) {
652 $parts = explode( '/', $range );
653 if ( count( $parts ) == 2 ) {
655 $ipint = IP
::toUnsigned6( $parts[0] );
656 # Native 32 bit functions WONT work here!!!
657 # Convert to a padded binary number
658 $network = wfBaseConvert( $ipint, 10, 2, 128 );
659 # Truncate the last (128-$bits) bits and replace them with zeros
660 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
661 # Convert back to an integer
662 $network = wfBaseConvert( $network, 2, 10 );
663 # Reform octet address
664 $newip = IP
::toOctet( $network );
665 $range = "$newip/{$parts[1]}";
671 * Purge expired blocks from the ipblocks table
673 static function purgeExpired() {
674 $dbw = wfGetDB( DB_MASTER
);
675 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
678 static function infinity() {
679 # This is a special keyword for timestamps in PostgreSQL, and
680 # works with CHAR(14) as well because "i" sorts after all numbers.
685 if ( !isset( $infinity ) ) {
686 $dbr = wfGetDB( DB_SLAVE );
687 $infinity = $dbr->bigTimestamp();