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 $mBlockEmail, $mByName;
20 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster;
22 const EB_KEEP_EXPIRED
= 1;
23 const EB_FOR_UPDATE
= 2;
24 const EB_RANGE_ONLY
= 4;
26 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
27 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
28 $hideName = 0, $blockEmail = 0 )
31 # Expand valid IPv6 addresses
32 $address = IP
::sanitizeIP( $address );
33 $this->mAddress
= $address;
36 $this->mReason
= $reason;
37 $this->mTimestamp
= wfTimestamp(TS_MW
,$timestamp);
39 $this->mAnonOnly
= $anonOnly;
40 $this->mCreateAccount
= $createAccount;
41 $this->mExpiry
= self
::decodeExpiry( $expiry );
42 $this->mEnableAutoblock
= $enableAutoblock;
43 $this->mHideName
= $hideName;
44 $this->mBlockEmail
= $blockEmail;
45 $this->mForUpdate
= false;
46 $this->mFromMaster
= false;
47 $this->mByName
= false;
48 $this->initialiseRange();
51 static function newFromDB( $address, $user = 0, $killExpired = true )
54 $block->load( $address, $user, $killExpired );
55 if ( $block->isValid() ) {
62 static function newFromID( $id )
64 $dbr = wfGetDB( DB_SLAVE
);
65 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
66 array( 'ipb_id' => $id ), __METHOD__
) );
68 if ( $block->loadFromResult( $res ) ) {
77 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
78 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
79 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
80 $this->mBy
= $this->mHideName
= $this->mBlockEmail
= 0;
81 $this->mByName
= false;
85 * Get the DB object and set the reference parameter to the query options
87 function &getDBOptions( &$options )
89 global $wgAntiLockFlags;
90 if ( $this->mForUpdate ||
$this->mFromMaster
) {
91 $db = wfGetDB( DB_MASTER
);
92 if ( !$this->mForUpdate ||
($wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) ) {
95 $options = array( 'FOR UPDATE' );
98 $db = wfGetDB( DB_SLAVE
);
105 * Get a ban from the DB, with either the given address or the given username
107 * @param string $address The IP address of the user, or blank to skip IP blocks
108 * @param integer $user The user ID, or zero for anonymous users
109 * @param bool $killExpired Whether to delete expired rows while loading
112 function load( $address = '', $user = 0, $killExpired = true )
114 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
117 $db =& $this->getDBOptions( $options );
119 if ( 0 == $user && $address == '' ) {
120 # Invalid user specification, not blocked
127 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
128 __METHOD__
, $options ) );
129 if ( $this->loadFromResult( $res, $killExpired ) ) {
135 # TODO: improve performance by merging this query with the autoblock one
136 # Slightly tricky while handling killExpired as well
138 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
139 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
140 if ( $this->loadFromResult( $res, $killExpired ) ) {
141 if ( $user && $this->mAnonOnly
) {
142 # Block is marked anon-only
143 # Whitelist this IP address against autoblocks and range blocks
153 if ( $this->loadRange( $address, $killExpired, $user ) ) {
154 if ( $user && $this->mAnonOnly
) {
164 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
166 $conds['ipb_anon_only'] = 0;
168 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
169 if ( $this->loadFromResult( $res, $killExpired ) ) {
180 * Fill in member variables from a result wrapper
182 function loadFromResult( ResultWrapper
$res, $killExpired = true )
185 if ( 0 != $res->numRows() ) {
187 $row = $res->fetchObject();
188 $this->initFromRow( $row );
190 if ( $killExpired ) {
191 # If requested, delete expired rows
193 $killed = $this->deleteIfExpired();
195 $row = $res->fetchObject();
197 $this->initFromRow( $row );
200 } while ( $killed && $row );
202 # If there were any left after the killing finished, return true
215 * Search the database for any range blocks matching the given address, and
216 * load the row if one is found.
218 function loadRange( $address, $killExpired = true, $user = 0 )
220 $iaddr = IP
::toHex( $address );
221 if ( $iaddr === false ) {
226 # Only scan ranges which start in this /16, this improves search speed
227 # Blocks should not cross a /16 boundary.
228 $range = substr( $iaddr, 0, 4 );
231 $db =& $this->getDBOptions( $options );
233 "ipb_range_start LIKE '$range%'",
234 "ipb_range_start <= '$iaddr'",
235 "ipb_range_end >= '$iaddr'"
239 $conds['ipb_anon_only'] = 0;
242 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
243 $success = $this->loadFromResult( $res, $killExpired );
248 * Determine if a given integer IPv4 address is in a given CIDR network
249 * @deprecated Use IP::isInRange
251 function isAddressInRange( $addr, $range ) {
252 return IP
::isInRange( $addr, $range );
255 function initFromRow( $row )
257 $this->mAddress
= $row->ipb_address
;
258 $this->mReason
= $row->ipb_reason
;
259 $this->mTimestamp
= wfTimestamp(TS_MW
,$row->ipb_timestamp
);
260 $this->mUser
= $row->ipb_user
;
261 $this->mBy
= $row->ipb_by
;
262 $this->mAuto
= $row->ipb_auto
;
263 $this->mAnonOnly
= $row->ipb_anon_only
;
264 $this->mCreateAccount
= $row->ipb_create_account
;
265 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
266 $this->mBlockEmail
= $row->ipb_block_email
;
267 $this->mHideName
= $row->ipb_deleted
;
268 $this->mId
= $row->ipb_id
;
269 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
270 if ( isset( $row->user_name
) ) {
271 $this->mByName
= $row->user_name
;
273 $this->mByName
= $row->ipb_by_text
;
275 $this->mRangeStart
= $row->ipb_range_start
;
276 $this->mRangeEnd
= $row->ipb_range_end
;
279 function initialiseRange()
281 $this->mRangeStart
= '';
282 $this->mRangeEnd
= '';
284 if ( $this->mUser
== 0 ) {
285 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
290 * Callback with a Block object for every block
291 * @return integer number of blocks;
293 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
295 global $wgAntiLockFlags;
297 $block = new Block();
298 if ( $flags & Block
::EB_FOR_UPDATE
) {
299 $db = wfGetDB( DB_MASTER
);
300 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
303 $options = 'FOR UPDATE';
305 $block->forUpdate( true );
307 $db = wfGetDB( DB_SLAVE
);
310 if ( $flags & Block
::EB_RANGE_ONLY
) {
311 $cond = " AND ipb_range_start <> ''";
316 $now = wfTimestampNow();
318 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
320 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
321 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
322 $res = $db->query( $sql, 'Block::enumBlocks' );
323 $num_rows = $db->numRows( $res );
325 while ( $row = $db->fetchObject( $res ) ) {
326 $block->initFromRow( $row );
327 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
331 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
332 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
335 call_user_func( $callback, $block, $tag );
338 call_user_func( $callback, $block, $tag );
341 $db->freeResult( $res );
351 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
354 $dbw = wfGetDB( DB_MASTER
);
355 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
356 return $dbw->affectedRows() > 0;
360 * Insert a block into the block table.
361 * @return Whether or not the insertion was successful.
365 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
366 $dbw = wfGetDB( DB_MASTER
);
368 # Unset ipb_anon_only for user blocks, makes no sense
369 if ( $this->mUser
) {
370 $this->mAnonOnly
= 0;
373 # Unset ipb_enable_autoblock for IP blocks, makes no sense
374 if ( !$this->mUser
) {
375 $this->mEnableAutoblock
= 0;
376 $this->mBlockEmail
= 0; //Same goes for email...
379 if( !$this->mByName
) {
381 $this->mByName
= User
::whoIs( $this->mBy
);
384 $this->mByName
= $wgUser->getName();
388 # Don't collide with expired blocks
389 Block
::purgeExpired();
391 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
392 $dbw->insert( 'ipblocks',
395 'ipb_address' => $this->mAddress
,
396 'ipb_user' => $this->mUser
,
397 'ipb_by' => $this->mBy
,
398 'ipb_by_text' => $this->mByName
,
399 'ipb_reason' => $this->mReason
,
400 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
401 'ipb_auto' => $this->mAuto
,
402 'ipb_anon_only' => $this->mAnonOnly
,
403 'ipb_create_account' => $this->mCreateAccount
,
404 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
405 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
406 'ipb_range_start' => $this->mRangeStart
,
407 'ipb_range_end' => $this->mRangeEnd
,
408 'ipb_deleted' => $this->mHideName
,
409 'ipb_block_email' => $this->mBlockEmail
410 ), 'Block::insert', array( 'IGNORE' )
412 $affected = $dbw->affectedRows();
415 $this->doRetroactiveAutoblock();
421 * Retroactively autoblocks the last IP used by the user (if it is a user)
422 * blocked by this Block.
423 *@return Whether or not a retroactive autoblock was made.
425 function doRetroactiveAutoblock() {
426 $dbr = wfGetDB( DB_SLAVE
);
427 #If autoblock is enabled, autoblock the LAST IP used
428 # - stolen shamelessly from CheckUser_body.php
430 if ($this->mEnableAutoblock
&& $this->mUser
) {
431 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
433 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress
),
434 __METHOD__
, array( 'ORDER BY' => 'rc_timestamp DESC' ) );
436 if ( !$row ||
!$row->rc_ip
) {
437 #No results, don't autoblock anything
438 wfDebug("No IP found to retroactively autoblock\n");
440 #Limit is 1, so no loop needed.
441 $retroblockip = $row->rc_ip
;
442 return $this->doAutoblock( $retroblockip, true );
448 * Autoblocks the given IP, referring to this Block.
449 * @param string $autoblockip The IP to autoblock.
450 * @param bool $justInserted The main block was just inserted
451 * @return bool Whether or not an autoblock was inserted.
453 function doAutoblock( $autoblockip, $justInserted = false ) {
454 # If autoblocks are disabled, go away.
455 if ( !$this->mEnableAutoblock
) {
459 # Check for presence on the autoblock whitelist
461 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
465 wfDebug("Checking the autoblock whitelist..\n");
467 foreach( $lines as $line ) {
469 if ( substr( $line, 0, 1 ) !== '*' ) {
473 $wlEntry = substr($line, 1);
474 $wlEntry = trim($wlEntry);
476 wfDebug("Checking $ip against $wlEntry...");
478 # Is the IP in this range?
479 if (IP
::isInRange( $ip, $wlEntry )) {
480 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
481 #$autoblockip = null; # Don't autoblock a whitelisted IP.
482 return; #This /SHOULD/ introduce a dummy block - but
483 # I don't know a safe way to do so. -werdna
485 wfDebug( " No match\n" );
489 # It's okay to autoblock. Go ahead and create/insert the block.
491 $ipblock = Block
::newFromDB( $autoblockip );
493 # If the user is already blocked. Then check if the autoblock would
494 # exceed the user block. If it would exceed, then do nothing, else
496 if ($this->mExpiry
&&
497 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
500 # Just update the timestamp
501 if ( !$justInserted ) {
502 $ipblock->updateTimestamp();
506 $ipblock = new Block
;
509 # Make a new block object with the desired properties
510 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
511 $ipblock->mAddress
= $autoblockip;
513 $ipblock->mBy
= $this->mBy
;
514 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
515 $ipblock->mTimestamp
= wfTimestampNow();
517 $ipblock->mCreateAccount
= $this->mCreateAccount
;
518 # Continue suppressing the name if needed
519 $ipblock->mHideName
= $this->mHideName
;
521 # If the user is already blocked with an expiry date, we don't
522 # want to pile on top of that!
524 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
526 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
529 return $ipblock->insert();
532 function deleteIfExpired()
534 $fname = 'Block::deleteIfExpired';
535 wfProfileIn( $fname );
536 if ( $this->isExpired() ) {
537 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
541 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
544 wfProfileOut( $fname );
550 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
551 if ( !$this->mExpiry
) {
554 return wfTimestampNow() > $this->mExpiry
;
560 return $this->mAddress
!= '';
563 function updateTimestamp()
565 if ( $this->mAuto
) {
566 $this->mTimestamp
= wfTimestamp();
567 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
569 $dbw = wfGetDB( DB_MASTER
);
570 $dbw->update( 'ipblocks',
572 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
573 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
574 ), array( /* WHERE */
575 'ipb_address' => $this->mAddress
576 ), 'Block::updateTimestamp'
582 function getIntegerAddr()
584 return $this->mIntegerAddr;
587 function getNetworkBits()
589 return $this->mNetworkBits;
593 * @return The blocker user ID.
595 public function getBy() {
600 * @return The blocker user name.
604 return $this->mByName
;
607 function forUpdate( $x = NULL ) {
608 return wfSetVar( $this->mForUpdate
, $x );
611 function fromMaster( $x = NULL ) {
612 return wfSetVar( $this->mFromMaster
, $x );
615 function getRedactedName() {
616 if ( $this->mAuto
) {
617 return '#' . $this->mId
;
619 return $this->mAddress
;
624 * Encode expiry for DB
626 static function encodeExpiry( $expiry, $db ) {
627 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
628 return Block
::infinity();
630 return $db->timestamp( $expiry );
635 * Decode expiry which has come from the DB
637 static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
638 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
639 return Block
::infinity();
641 return wfTimestamp( $timestampType, $expiry );
645 static function getAutoblockExpiry( $timestamp )
647 global $wgAutoblockExpiry;
648 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
652 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
653 * For example, 127.111.113.151/24 -> 127.111.113.0/24
655 static function normaliseRange( $range ) {
656 $parts = explode( '/', $range );
657 if ( count( $parts ) == 2 ) {
659 if ( IP
::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
661 $ipint = IP
::toUnsigned6( $parts[0] );
662 # Native 32 bit functions WONT work here!!!
663 # Convert to a padded binary number
664 $network = wfBaseConvert( $ipint, 10, 2, 128 );
665 # Truncate the last (128-$bits) bits and replace them with zeros
666 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
667 # Convert back to an integer
668 $network = wfBaseConvert( $network, 2, 10 );
669 # Reform octet address
670 $newip = IP
::toOctet( $network );
671 $range = "$newip/{$parts[1]}";
673 else if ( IP
::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
674 $shift = 32 - $parts[1];
675 $ipint = IP
::toUnsigned( $parts[0] );
676 $ipint = $ipint >> $shift << $shift;
677 $newip = long2ip( $ipint );
678 $range = "$newip/{$parts[1]}";
685 * Purge expired blocks from the ipblocks table
687 static function purgeExpired() {
688 $dbw = wfGetDB( DB_MASTER
);
689 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
692 static function infinity() {
693 # This is a special keyword for timestamps in PostgreSQL, and
694 # works with CHAR(14) as well because "i" sorts after all numbers.
699 if ( !isset( $infinity ) ) {
700 $dbr = wfGetDB( DB_SLAVE );
701 $infinity = $dbr->bigTimestamp();