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, $hideName = 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;
41 $this->mHideName
= $hideName;
43 $this->mForUpdate
= false;
44 $this->mFromMaster
= false;
45 $this->mByName
= false;
46 $this->initialiseRange();
49 static function newFromDB( $address, $user = 0, $killExpired = true )
52 $block->load( $address, $user, $killExpired );
53 if ( $block->isValid() ) {
60 static function newFromID( $id )
62 $dbr = wfGetDB( DB_SLAVE
);
63 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
64 array( 'ipb_id' => $id ), __METHOD__
) );
66 if ( $block->loadFromResult( $res ) ) {
75 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
76 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
77 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
78 $this->mBy
= $this->mHideName
= 0;
79 $this->mByName
= false;
83 * Get the DB object and set the reference parameter to the query options
85 function &getDBOptions( &$options )
87 global $wgAntiLockFlags;
88 if ( $this->mForUpdate ||
$this->mFromMaster
) {
89 $db = wfGetDB( DB_MASTER
);
90 if ( !$this->mForUpdate ||
($wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) ) {
93 $options = array( 'FOR UPDATE' );
96 $db = wfGetDB( DB_SLAVE
);
103 * Get a ban from the DB, with either the given address or the given username
105 * @param string $address The IP address of the user, or blank to skip IP blocks
106 * @param integer $user The user ID, or zero for anonymous users
107 * @param bool $killExpired Whether to delete expired rows while loading
110 function load( $address = '', $user = 0, $killExpired = true )
112 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
115 $db =& $this->getDBOptions( $options );
117 if ( 0 == $user && $address == '' ) {
118 # Invalid user specification, not blocked
125 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
126 __METHOD__
, $options ) );
127 if ( $this->loadFromResult( $res, $killExpired ) ) {
133 # TODO: improve performance by merging this query with the autoblock one
134 # Slightly tricky while handling killExpired as well
136 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
137 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
138 if ( $this->loadFromResult( $res, $killExpired ) ) {
139 if ( $user && $this->mAnonOnly
) {
140 # Block is marked anon-only
141 # Whitelist this IP address against autoblocks and range blocks
151 if ( $this->loadRange( $address, $killExpired, $user == 0 ) ) {
152 if ( $user && $this->mAnonOnly
) {
162 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
164 $conds['ipb_anon_only'] = 0;
166 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
167 if ( $this->loadFromResult( $res, $killExpired ) ) {
178 * Fill in member variables from a result wrapper
180 function loadFromResult( ResultWrapper
$res, $killExpired = true )
183 if ( 0 != $res->numRows() ) {
185 $row = $res->fetchObject();
186 $this->initFromRow( $row );
188 if ( $killExpired ) {
189 # If requested, delete expired rows
191 $killed = $this->deleteIfExpired();
193 $row = $res->fetchObject();
195 $this->initFromRow( $row );
198 } while ( $killed && $row );
200 # If there were any left after the killing finished, return true
213 * Search the database for any range blocks matching the given address, and
214 * load the row if one is found.
216 function loadRange( $address, $killExpired = true, $user = 0 )
218 $iaddr = IP
::toHex( $address );
219 if ( $iaddr === false ) {
224 # Only scan ranges which start in this /16, this improves search speed
225 # Blocks should not cross a /16 boundary.
226 $range = substr( $iaddr, 0, 4 );
229 $db =& $this->getDBOptions( $options );
231 "ipb_range_start LIKE '$range%'",
232 "ipb_range_start <= '$iaddr'",
233 "ipb_range_end >= '$iaddr'"
237 $conds['ipb_anon_only'] = 0;
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->mHideName
= $row->ipb_deleted
;
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
= '';
281 if ( $this->mUser
== 0 ) {
282 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
287 * Callback with a Block object for every block
288 * @return integer number of blocks;
290 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
292 global $wgAntiLockFlags;
294 $block = new Block();
295 if ( $flags & Block
::EB_FOR_UPDATE
) {
296 $db = wfGetDB( DB_MASTER
);
297 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
300 $options = 'FOR UPDATE';
302 $block->forUpdate( true );
304 $db = wfGetDB( DB_SLAVE
);
307 if ( $flags & Block
::EB_RANGE_ONLY
) {
308 $cond = " AND ipb_range_start <> ''";
313 $now = wfTimestampNow();
315 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
317 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
318 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
319 $res = $db->query( $sql, 'Block::enumBlocks' );
320 $num_rows = $db->numRows( $res );
322 while ( $row = $db->fetchObject( $res ) ) {
323 $block->initFromRow( $row );
324 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
328 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
329 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
332 call_user_func( $callback, $block, $tag );
335 call_user_func( $callback, $block, $tag );
338 $db->freeResult( $res );
348 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
351 $dbw = wfGetDB( DB_MASTER
);
352 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
353 return $dbw->affectedRows() > 0;
357 * Insert a block into the block table.
358 *@return Whether or not the insertion was successful.
362 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
363 $dbw = wfGetDB( DB_MASTER
);
366 # Unset ipb_anon_only for user blocks, makes no sense
367 if ( $this->mUser
) {
368 $this->mAnonOnly
= 0;
371 # Unset ipb_enable_autoblock for IP blocks, makes no sense
372 if ( !$this->mUser
) {
373 $this->mEnableAutoblock
= 0;
376 # Don't collide with expired blocks
377 Block
::purgeExpired();
379 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
380 $dbw->insert( 'ipblocks',
383 'ipb_address' => $this->mAddress
,
384 'ipb_user' => $this->mUser
,
385 'ipb_by' => $this->mBy
,
386 'ipb_reason' => $this->mReason
,
387 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
388 'ipb_auto' => $this->mAuto
,
389 'ipb_anon_only' => $this->mAnonOnly
,
390 'ipb_create_account' => $this->mCreateAccount
,
391 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
392 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
393 'ipb_range_start' => $this->mRangeStart
,
394 'ipb_range_end' => $this->mRangeEnd
,
395 'ipb_deleted' => $this->mHideName
396 ), 'Block::insert', array( 'IGNORE' )
398 $affected = $dbw->affectedRows();
402 $this->doRetroactiveAutoblock();
408 * Retroactively autoblocks the last IP used by the user (if it is a user)
409 * blocked by this Block.
410 *@return Whether or not a retroactive autoblock was made.
412 function doRetroactiveAutoblock() {
413 $dbr = wfGetDB( DB_SLAVE
);
414 #If autoblock is enabled, autoblock the LAST IP used
415 # - stolen shamelessly from CheckUser_body.php
417 if ($this->mEnableAutoblock
&& $this->mUser
) {
418 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
420 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress
),
421 __METHOD__
, array( 'ORDER BY' => 'rc_timestamp DESC' ) );
423 if ( !$row ||
!$row->rc_ip
) {
424 #No results, don't autoblock anything
425 wfDebug("No IP found to retroactively autoblock\n");
427 #Limit is 1, so no loop needed.
428 $retroblockip = $row->rc_ip
;
429 return $this->doAutoblock($retroblockip);
435 * Autoblocks the given IP, referring to this Block.
436 * @param $autoblockip The IP to autoblock.
437 * @return bool Whether or not an autoblock was inserted.
439 function doAutoblock( $autoblockip ) {
440 # Check if this IP address is already blocked
441 $dbw = wfGetDB( DB_MASTER
);
444 # If autoblocks are disabled, go away.
445 if ( !$this->mEnableAutoblock
) {
449 # Check for presence on the autoblock whitelist
451 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
455 wfDebug("Checking the autoblock whitelist..\n");
457 foreach( $lines as $line ) {
459 if ( substr( $line, 0, 1 ) !== '*' ) {
463 $wlEntry = substr($line, 1);
464 $wlEntry = trim($wlEntry);
466 wfDebug("Checking $ip against $wlEntry...");
468 # Is the IP in this range?
469 if (IP
::isInRange( $ip, $wlEntry )) {
470 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
471 #$autoblockip = null; # Don't autoblock a whitelisted IP.
472 return; #This /SHOULD/ introduce a dummy block - but
473 # I don't know a safe way to do so. -werdna
475 wfDebug( " No match\n" );
479 # It's okay to autoblock. Go ahead and create/insert the block.
481 $ipblock = Block
::newFromDB( $autoblockip );
483 # If the user is already blocked. Then check if the autoblock would
484 # exceed the user block. If it would exceed, then do nothing, else
486 if ($this->mExpiry
&&
487 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
490 # Just update the timestamp
491 $ipblock->updateTimestamp();
494 $ipblock = new Block
;
497 # Make a new block object with the desired properties
498 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
499 $ipblock->mAddress
= $autoblockip;
501 $ipblock->mBy
= $this->mBy
;
502 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
503 $ipblock->mTimestamp
= wfTimestampNow();
505 $ipblock->mCreateAccount
= $this->mCreateAccount
;
506 # Continue suppressing the name if needed
507 $ipblock->mHideName
= $this->mHideName
;
509 # If the user is already blocked with an expiry date, we don't
510 # want to pile on top of that!
512 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
514 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
517 return $ipblock->insert();
520 function deleteIfExpired()
522 $fname = 'Block::deleteIfExpired';
523 wfProfileIn( $fname );
524 if ( $this->isExpired() ) {
525 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
529 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
532 wfProfileOut( $fname );
538 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
539 if ( !$this->mExpiry
) {
542 return wfTimestampNow() > $this->mExpiry
;
548 return $this->mAddress
!= '';
551 function updateTimestamp()
553 if ( $this->mAuto
) {
554 $this->mTimestamp
= wfTimestamp();
555 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
557 $dbw = wfGetDB( DB_MASTER
);
558 $dbw->update( 'ipblocks',
560 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
561 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
562 ), array( /* WHERE */
563 'ipb_address' => $this->mAddress
564 ), 'Block::updateTimestamp'
570 function getIntegerAddr()
572 return $this->mIntegerAddr;
575 function getNetworkBits()
577 return $this->mNetworkBits;
581 * @return The blocker user ID.
583 public function getBy() {
588 * @return The blocker user name.
592 if ( $this->mByName
=== false ) {
593 $this->mByName
= User
::whoIs( $this->mBy
);
595 return $this->mByName
;
598 function forUpdate( $x = NULL ) {
599 return wfSetVar( $this->mForUpdate
, $x );
602 function fromMaster( $x = NULL ) {
603 return wfSetVar( $this->mFromMaster
, $x );
606 function getRedactedName() {
607 if ( $this->mAuto
) {
608 return '#' . $this->mId
;
610 return $this->mAddress
;
615 * Encode expiry for DB
617 static function encodeExpiry( $expiry, $db ) {
618 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
619 return Block
::infinity();
621 return $db->timestamp( $expiry );
626 * Decode expiry which has come from the DB
628 static function decodeExpiry( $expiry ) {
629 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
630 return Block
::infinity();
632 return wfTimestamp( TS_MW
, $expiry );
636 static function getAutoblockExpiry( $timestamp )
638 global $wgAutoblockExpiry;
639 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
643 * Gets rid of uneeded numbers in quad-dotted IP strings
644 * For example, 127.111.113.151/24 -> 127.111.113.0/24
646 static function normaliseRange( $range ) {
647 // Use IPv6 functions if needed
648 if ( IP
::isIPv6($range) ) return self
::normaliseRange6( $range );
649 $parts = explode( '/', $range );
650 if ( count( $parts ) == 2 ) {
651 $shift = 32 - $parts[1];
652 $ipint = IP
::toUnsigned( $parts[0] );
653 $ipint = $ipint >> $shift << $shift;
654 $newip = long2ip( $ipint );
655 $range = "$newip/{$parts[1]}";
661 static function normaliseRange6( $range ) {
662 $parts = explode( '/', $range );
663 if ( count( $parts ) == 2 ) {
665 $ipint = IP
::toUnsigned6( $parts[0] );
666 # Native 32 bit functions WONT work here!!!
667 # Convert to a padded binary number
668 $network = wfBaseConvert( $ipint, 10, 2, 128 );
669 # Truncate the last (128-$bits) bits and replace them with zeros
670 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
671 # Convert back to an integer
672 $network = wfBaseConvert( $network, 2, 10 );
673 # Reform octet address
674 $newip = IP
::toOctet( $network );
675 $range = "$newip/{$parts[1]}";
681 * Purge expired blocks from the ipblocks table
683 static function purgeExpired() {
684 $dbw = wfGetDB( DB_MASTER
);
685 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
688 static function infinity() {
689 # This is a special keyword for timestamps in PostgreSQL, and
690 # works with CHAR(14) as well because "i" sorts after all numbers.
695 if ( !isset( $infinity ) ) {
696 $dbr = wfGetDB( DB_SLAVE );
697 $infinity = $dbr->bigTimestamp();