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, $mHideName;
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,
30 # Expand valid IPv6 addresses
31 $address = IP
::sanitizeIP( $address );
32 $this->mAddress
= $address;
35 $this->mReason
= $reason;
36 $this->mTimestamp
= wfTimestamp(TS_MW
,$timestamp);
38 $this->mAnonOnly
= $anonOnly;
39 $this->mCreateAccount
= $createAccount;
40 $this->mExpiry
= self
::decodeExpiry( $expiry );
41 $this->mEnableAutoblock
= $enableAutoblock;
42 $this->mHideName
= $hideName;
44 $this->mForUpdate
= false;
45 $this->mFromMaster
= false;
46 $this->mByName
= false;
47 $this->initialiseRange();
50 static function newFromDB( $address, $user = 0, $killExpired = true )
53 $block->load( $address, $user, $killExpired );
54 if ( $block->isValid() ) {
61 static function newFromID( $id )
63 $dbr = wfGetDB( DB_SLAVE
);
64 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
65 array( 'ipb_id' => $id ), __METHOD__
) );
67 if ( $block->loadFromResult( $res ) ) {
76 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
77 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
78 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
79 $this->mBy
= $this->mHideName
= 0;
80 $this->mByName
= false;
84 * Get the DB object and set the reference parameter to the query options
86 function &getDBOptions( &$options )
88 global $wgAntiLockFlags;
89 if ( $this->mForUpdate ||
$this->mFromMaster
) {
90 $db = wfGetDB( DB_MASTER
);
91 if ( !$this->mForUpdate ||
($wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) ) {
94 $options = array( 'FOR UPDATE' );
97 $db = wfGetDB( DB_SLAVE
);
104 * Get a ban from the DB, with either the given address or the given username
106 * @param string $address The IP address of the user, or blank to skip IP blocks
107 * @param integer $user The user ID, or zero for anonymous users
108 * @param bool $killExpired Whether to delete expired rows while loading
111 function load( $address = '', $user = 0, $killExpired = true )
113 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
116 $db =& $this->getDBOptions( $options );
118 if ( 0 == $user && $address == '' ) {
119 # Invalid user specification, not blocked
126 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
127 __METHOD__
, $options ) );
128 if ( $this->loadFromResult( $res, $killExpired ) ) {
134 # TODO: improve performance by merging this query with the autoblock one
135 # Slightly tricky while handling killExpired as well
137 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
138 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
139 if ( $this->loadFromResult( $res, $killExpired ) ) {
140 if ( $user && $this->mAnonOnly
) {
141 # Block is marked anon-only
142 # Whitelist this IP address against autoblocks and range blocks
152 if ( $this->loadRange( $address, $killExpired, $user == 0 ) ) {
153 if ( $user && $this->mAnonOnly
) {
163 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
165 $conds['ipb_anon_only'] = 0;
167 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
168 if ( $this->loadFromResult( $res, $killExpired ) ) {
179 * Fill in member variables from a result wrapper
181 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, $user = 0 )
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'"
238 $conds['ipb_anon_only'] = 0;
241 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
242 $success = $this->loadFromResult( $res, $killExpired );
247 * Determine if a given integer IPv4 address is in a given CIDR network
248 * @deprecated Use IP::isInRange
250 function isAddressInRange( $addr, $range ) {
251 return IP
::isInRange( $addr, $range );
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->mHideName
= $row->ipb_deleted
;
266 $this->mId
= $row->ipb_id
;
267 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
268 if ( isset( $row->user_name
) ) {
269 $this->mByName
= $row->user_name
;
271 $this->mByName
= false;
273 $this->mRangeStart
= $row->ipb_range_start
;
274 $this->mRangeEnd
= $row->ipb_range_end
;
277 function initialiseRange()
279 $this->mRangeStart
= '';
280 $this->mRangeEnd
= '';
282 if ( $this->mUser
== 0 ) {
283 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
288 * Callback with a Block object for every block
289 * @return integer number of blocks;
291 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
293 global $wgAntiLockFlags;
295 $block = new Block();
296 if ( $flags & Block
::EB_FOR_UPDATE
) {
297 $db = wfGetDB( DB_MASTER
);
298 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
301 $options = 'FOR UPDATE';
303 $block->forUpdate( true );
305 $db = wfGetDB( DB_SLAVE
);
308 if ( $flags & Block
::EB_RANGE_ONLY
) {
309 $cond = " AND ipb_range_start <> ''";
314 $now = wfTimestampNow();
316 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
318 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
319 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
320 $res = $db->query( $sql, 'Block::enumBlocks' );
321 $num_rows = $db->numRows( $res );
323 while ( $row = $db->fetchObject( $res ) ) {
324 $block->initFromRow( $row );
325 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
329 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
330 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
333 call_user_func( $callback, $block, $tag );
336 call_user_func( $callback, $block, $tag );
339 $db->freeResult( $res );
349 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
352 $dbw = wfGetDB( DB_MASTER
);
353 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
354 return $dbw->affectedRows() > 0;
358 * Insert a block into the block table.
359 *@return Whether or not the insertion was successful.
363 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
364 $dbw = wfGetDB( DB_MASTER
);
367 # Unset ipb_anon_only for user blocks, makes no sense
368 if ( $this->mUser
) {
369 $this->mAnonOnly
= 0;
372 # Unset ipb_enable_autoblock for IP blocks, makes no sense
373 if ( !$this->mUser
) {
374 $this->mEnableAutoblock
= 0;
377 # Don't collide with expired blocks
378 Block
::purgeExpired();
380 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
381 $dbw->insert( 'ipblocks',
384 'ipb_address' => $this->mAddress
,
385 'ipb_user' => $this->mUser
,
386 'ipb_by' => $this->mBy
,
387 'ipb_reason' => $this->mReason
,
388 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
389 'ipb_auto' => $this->mAuto
,
390 'ipb_anon_only' => $this->mAnonOnly
,
391 'ipb_create_account' => $this->mCreateAccount
,
392 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
393 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
394 'ipb_range_start' => $this->mRangeStart
,
395 'ipb_range_end' => $this->mRangeEnd
,
396 'ipb_deleted' => $this->mHideName
397 ), 'Block::insert', array( 'IGNORE' )
399 $affected = $dbw->affectedRows();
403 $this->doRetroactiveAutoblock();
409 * Retroactively autoblocks the last IP used by the user (if it is a user)
410 * blocked by this Block.
411 *@return Whether or not a retroactive autoblock was made.
413 function doRetroactiveAutoblock() {
414 $dbr = wfGetDB( DB_SLAVE
);
415 #If autoblock is enabled, autoblock the LAST IP used
416 # - stolen shamelessly from CheckUser_body.php
418 if ($this->mEnableAutoblock
&& $this->mUser
) {
419 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
421 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress
),
422 __METHOD__
, array( 'ORDER BY' => 'rc_timestamp DESC' ) );
424 if ( !$row ||
!$row->rc_ip
) {
425 #No results, don't autoblock anything
426 wfDebug("No IP found to retroactively autoblock\n");
428 #Limit is 1, so no loop needed.
429 $retroblockip = $row->rc_ip
;
430 return $this->doAutoblock($retroblockip);
436 * Autoblocks the given IP, referring to this Block.
437 * @param $autoblockip The IP to autoblock.
438 * @return bool Whether or not an autoblock was inserted.
440 function doAutoblock( $autoblockip ) {
441 # Check if this IP address is already blocked
442 $dbw = wfGetDB( DB_MASTER
);
445 # If autoblocks are disabled, go away.
446 if ( !$this->mEnableAutoblock
) {
450 # Check for presence on the autoblock whitelist
452 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
456 wfDebug("Checking the autoblock whitelist..\n");
458 foreach( $lines as $line ) {
460 if ( substr( $line, 0, 1 ) !== '*' ) {
464 $wlEntry = substr($line, 1);
465 $wlEntry = trim($wlEntry);
467 wfDebug("Checking $ip against $wlEntry...");
469 # Is the IP in this range?
470 if (IP
::isInRange( $ip, $wlEntry )) {
471 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
472 #$autoblockip = null; # Don't autoblock a whitelisted IP.
473 return; #This /SHOULD/ introduce a dummy block - but
474 # I don't know a safe way to do so. -werdna
476 wfDebug( " No match\n" );
480 # It's okay to autoblock. Go ahead and create/insert the block.
482 $ipblock = Block
::newFromDB( $autoblockip );
484 # If the user is already blocked. Then check if the autoblock would
485 # exceed the user block. If it would exceed, then do nothing, else
487 if ($this->mExpiry
&&
488 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
491 # Just update the timestamp
492 $ipblock->updateTimestamp();
495 $ipblock = new Block
;
498 # Make a new block object with the desired properties
499 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
500 $ipblock->mAddress
= $autoblockip;
502 $ipblock->mBy
= $this->mBy
;
503 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
504 $ipblock->mTimestamp
= wfTimestampNow();
506 $ipblock->mCreateAccount
= $this->mCreateAccount
;
507 # Continue suppressing the name if needed
508 $ipblock->mHideName
= $this->mHideName
;
510 # If the user is already blocked with an expiry date, we don't
511 # want to pile on top of that!
513 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
515 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
518 return $ipblock->insert();
521 function deleteIfExpired()
523 $fname = 'Block::deleteIfExpired';
524 wfProfileIn( $fname );
525 if ( $this->isExpired() ) {
526 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
530 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
533 wfProfileOut( $fname );
539 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
540 if ( !$this->mExpiry
) {
543 return wfTimestampNow() > $this->mExpiry
;
549 return $this->mAddress
!= '';
552 function updateTimestamp()
554 if ( $this->mAuto
) {
555 $this->mTimestamp
= wfTimestamp();
556 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
558 $dbw = wfGetDB( DB_MASTER
);
559 $dbw->update( 'ipblocks',
561 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
562 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
563 ), array( /* WHERE */
564 'ipb_address' => $this->mAddress
565 ), 'Block::updateTimestamp'
571 function getIntegerAddr()
573 return $this->mIntegerAddr;
576 function getNetworkBits()
578 return $this->mNetworkBits;
582 * @return The blocker user ID.
584 public function getBy() {
589 * @return The blocker user name.
593 if ( $this->mByName
=== false ) {
594 $this->mByName
= User
::whoIs( $this->mBy
);
596 return $this->mByName
;
599 function forUpdate( $x = NULL ) {
600 return wfSetVar( $this->mForUpdate
, $x );
603 function fromMaster( $x = NULL ) {
604 return wfSetVar( $this->mFromMaster
, $x );
607 function getRedactedName() {
608 if ( $this->mAuto
) {
609 return '#' . $this->mId
;
611 return $this->mAddress
;
616 * Encode expiry for DB
618 static function encodeExpiry( $expiry, $db ) {
619 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
620 return Block
::infinity();
622 return $db->timestamp( $expiry );
627 * Decode expiry which has come from the DB
629 static function decodeExpiry( $expiry ) {
630 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
631 return Block
::infinity();
633 return wfTimestamp( TS_MW
, $expiry );
637 static function getAutoblockExpiry( $timestamp )
639 global $wgAutoblockExpiry;
640 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
644 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
645 * For example, 127.111.113.151/24 -> 127.111.113.0/24
647 static function normaliseRange( $range ) {
648 $parts = explode( '/', $range );
649 if ( count( $parts ) == 2 ) {
651 if ( IP
::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
653 $ipint = IP
::toUnsigned6( $parts[0] );
654 # Native 32 bit functions WONT work here!!!
655 # Convert to a padded binary number
656 $network = wfBaseConvert( $ipint, 10, 2, 128 );
657 # Truncate the last (128-$bits) bits and replace them with zeros
658 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
659 # Convert back to an integer
660 $network = wfBaseConvert( $network, 2, 10 );
661 # Reform octet address
662 $newip = IP
::toOctet( $network );
663 $range = "$newip/{$parts[1]}";
665 else if ( IP
::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
666 $shift = 32 - $parts[1];
667 $ipint = IP
::toUnsigned( $parts[0] );
668 $ipint = $ipint >> $shift << $shift;
669 $newip = long2ip( $ipint );
670 $range = "$newip/{$parts[1]}";
677 * Purge expired blocks from the ipblocks table
679 static function purgeExpired() {
680 $dbw = wfGetDB( DB_MASTER
);
681 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
684 static function infinity() {
685 # This is a special keyword for timestamps in PostgreSQL, and
686 # works with CHAR(14) as well because "i" sorts after all numbers.
691 if ( !isset( $infinity ) ) {
692 $dbr = wfGetDB( DB_SLAVE );
693 $infinity = $dbr->bigTimestamp();