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 $this->mAddress
= $address;
32 $this->mReason
= $reason;
33 $this->mTimestamp
= wfTimestamp(TS_MW
,$timestamp);
35 $this->mAnonOnly
= $anonOnly;
36 $this->mCreateAccount
= $createAccount;
37 $this->mExpiry
= self
::decodeExpiry( $expiry );
38 $this->mEnableAutoblock
= $enableAutoblock;
40 $this->mForUpdate
= false;
41 $this->mFromMaster
= false;
42 $this->mByName
= false;
43 $this->initialiseRange();
46 static function newFromDB( $address, $user = 0, $killExpired = true )
49 $block->load( $address, $user, $killExpired );
50 if ( $block->isValid() ) {
57 static function newFromID( $id )
59 $dbr = wfGetDB( DB_SLAVE
);
60 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
61 array( 'ipb_id' => $id ), __METHOD__
) );
63 if ( $block->loadFromResult( $res ) ) {
72 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
73 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
74 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
76 $this->mByName
= false;
80 * Get the DB object and set the reference parameter to the query options
82 function &getDBOptions( &$options )
84 global $wgAntiLockFlags;
85 if ( $this->mForUpdate ||
$this->mFromMaster
) {
86 $db = wfGetDB( DB_MASTER
);
87 if ( !$this->mForUpdate ||
($wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) ) {
90 $options = array( 'FOR UPDATE' );
93 $db = wfGetDB( DB_SLAVE
);
100 * Get a ban from the DB, with either the given address or the given username
102 * @param string $address The IP address of the user, or blank to skip IP blocks
103 * @param integer $user The user ID, or zero for anonymous users
104 * @param bool $killExpired Whether to delete expired rows while loading
107 function load( $address = '', $user = 0, $killExpired = true )
109 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
112 $db =& $this->getDBOptions( $options );
114 if ( 0 == $user && $address == '' ) {
115 # Invalid user specification, not blocked
122 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
123 __METHOD__
, $options ) );
124 if ( $this->loadFromResult( $res, $killExpired ) ) {
130 # TODO: improve performance by merging this query with the autoblock one
131 # Slightly tricky while handling killExpired as well
133 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
134 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
135 if ( $this->loadFromResult( $res, $killExpired ) ) {
136 if ( $user && $this->mAnonOnly
) {
137 # Block is marked anon-only
138 # Whitelist this IP address against autoblocks and range blocks
148 if ( $this->loadRange( $address, $killExpired, $user == 0 ) ) {
149 if ( $user && $this->mAnonOnly
) {
159 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
161 $conds['ipb_anon_only'] = 0;
163 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
164 if ( $this->loadFromResult( $res, $killExpired ) ) {
175 * Fill in member variables from a result wrapper
177 function loadFromResult( ResultWrapper
$res, $killExpired = true ) {
179 if ( 0 != $res->numRows() ) {
181 $row = $res->fetchObject();
182 $this->initFromRow( $row );
184 if ( $killExpired ) {
185 # If requested, delete expired rows
187 $killed = $this->deleteIfExpired();
189 $row = $res->fetchObject();
191 $this->initFromRow( $row );
194 } while ( $killed && $row );
196 # If there were any left after the killing finished, return true
209 * Search the database for any range blocks matching the given address, and
210 * load the row if one is found.
212 function loadRange( $address, $killExpired = true )
214 $iaddr = IP
::toHex( $address );
215 if ( $iaddr === false ) {
220 # Only scan ranges which start in this /16, this improves search speed
221 # Blocks should not cross a /16 boundary.
222 $range = substr( $iaddr, 0, 4 );
225 $db =& $this->getDBOptions( $options );
227 "ipb_range_start LIKE '$range%'",
228 "ipb_range_start <= '$iaddr'",
229 "ipb_range_end >= '$iaddr'"
232 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
233 $success = $this->loadFromResult( $res, $killExpired );
238 * Determine if a given integer IPv4 address is in a given CIDR network
239 * @deprecated Use IP::isInRange
241 function isAddressInRange( $addr, $range ) {
242 return IP
::isInRange( $addr, $range );
245 function initFromRow( $row )
247 $this->mAddress
= $row->ipb_address
;
248 $this->mReason
= $row->ipb_reason
;
249 $this->mTimestamp
= wfTimestamp(TS_MW
,$row->ipb_timestamp
);
250 $this->mUser
= $row->ipb_user
;
251 $this->mBy
= $row->ipb_by
;
252 $this->mAuto
= $row->ipb_auto
;
253 $this->mAnonOnly
= $row->ipb_anon_only
;
254 $this->mCreateAccount
= $row->ipb_create_account
;
255 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
256 $this->mId
= $row->ipb_id
;
257 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
258 if ( isset( $row->user_name
) ) {
259 $this->mByName
= $row->user_name
;
261 $this->mByName
= false;
263 $this->mRangeStart
= $row->ipb_range_start
;
264 $this->mRangeEnd
= $row->ipb_range_end
;
267 function initialiseRange()
269 $this->mRangeStart
= '';
270 $this->mRangeEnd
= '';
272 if ( $this->mUser
== 0 ) {
273 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
278 * Callback with a Block object for every block
279 * @return integer number of blocks;
281 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
283 global $wgAntiLockFlags;
285 $block = new Block();
286 if ( $flags & Block
::EB_FOR_UPDATE
) {
287 $db = wfGetDB( DB_MASTER
);
288 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
291 $options = 'FOR UPDATE';
293 $block->forUpdate( true );
295 $db = wfGetDB( DB_SLAVE
);
298 if ( $flags & Block
::EB_RANGE_ONLY
) {
299 $cond = " AND ipb_range_start <> ''";
304 $now = wfTimestampNow();
306 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
308 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
309 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
310 $res = $db->query( $sql, 'Block::enumBlocks' );
311 $num_rows = $db->numRows( $res );
313 while ( $row = $db->fetchObject( $res ) ) {
314 $block->initFromRow( $row );
315 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
319 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
320 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
323 call_user_func( $callback, $block, $tag );
326 call_user_func( $callback, $block, $tag );
329 $db->freeResult( $res );
339 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
342 $dbw = wfGetDB( DB_MASTER
);
343 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
344 return $dbw->affectedRows() > 0;
348 * Insert a block into the block table.
349 *@return Whether or not the insertion was successful.
353 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
354 $dbw = wfGetDB( DB_MASTER
);
357 # Unset ipb_anon_only for user blocks, makes no sense
358 if ( $this->mUser
) {
359 $this->mAnonOnly
= 0;
362 # Unset ipb_enable_autoblock for IP blocks, makes no sense
363 if ( !$this->mUser
) {
364 $this->mEnableAutoblock
= 0;
367 # Don't collide with expired blocks
368 Block
::purgeExpired();
370 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
371 $dbw->insert( 'ipblocks',
374 'ipb_address' => $this->mAddress
,
375 'ipb_user' => $this->mUser
,
376 'ipb_by' => $this->mBy
,
377 'ipb_reason' => $this->mReason
,
378 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
379 'ipb_auto' => $this->mAuto
,
380 'ipb_anon_only' => $this->mAnonOnly
,
381 'ipb_create_account' => $this->mCreateAccount
,
382 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
383 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
384 'ipb_range_start' => $this->mRangeStart
,
385 'ipb_range_end' => $this->mRangeEnd
,
386 ), 'Block::insert', array( 'IGNORE' )
388 $affected = $dbw->affectedRows();
392 $this->doRetroactiveAutoblock();
398 * Retroactively autoblocks the last IP used by the user (if it is a user)
399 * blocked by this Block.
400 *@return Whether or not a retroactive autoblock was made.
402 function doRetroactiveAutoblock() {
403 $dbr = wfGetDB( DB_SLAVE
);
404 #If autoblock is enabled, autoblock the LAST IP used
405 # - stolen shamelessly from CheckUser_body.php
407 if ($this->mEnableAutoblock
&& $this->mUser
) {
408 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
410 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress
),
411 __METHOD__
, array( 'ORDER BY' => 'rc_timestamp DESC' ) );
413 if ( !$row ||
!$row->rc_ip
) {
414 #No results, don't autoblock anything
415 wfDebug("No IP found to retroactively autoblock\n");
417 #Limit is 1, so no loop needed.
418 $retroblockip = $row->rc_ip
;
419 return $this->doAutoblock($retroblockip);
425 * Autoblocks the given IP, referring to this Block.
426 * @param $autoblockip The IP to autoblock.
427 * @return bool Whether or not an autoblock was inserted.
429 function doAutoblock( $autoblockip ) {
430 # Check if this IP address is already blocked
431 $dbw = wfGetDB( DB_MASTER
);
434 # If autoblocks are disabled, go away.
435 if ( !$this->mEnableAutoblock
) {
439 # Check for presence on the autoblock whitelist
441 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
445 wfDebug("Checking the autoblock whitelist..\n");
447 foreach( $lines as $line ) {
449 if ( substr( $line, 0, 1 ) !== '*' ) {
453 $wlEntry = substr($line, 1);
454 $wlEntry = trim($wlEntry);
456 wfDebug("Checking $ip against $wlEntry...");
458 # Is the IP in this range?
459 if (IP
::isInRange( $ip, $wlEntry )) {
460 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
461 #$autoblockip = null; # Don't autoblock a whitelisted IP.
462 return; #This /SHOULD/ introduce a dummy block - but
463 # I don't know a safe way to do so. -werdna
465 wfDebug( " No match\n" );
469 # It's okay to autoblock. Go ahead and create/insert the block.
471 $ipblock = Block
::newFromDB( $autoblockip );
473 # If the user is already blocked. Then check if the autoblock would
474 # exceed the user block. If it would exceed, then do nothing, else
476 if ($this->mExpiry
&&
477 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
480 # Just update the timestamp
481 $ipblock->updateTimestamp();
484 $ipblock = new Block
;
487 # Make a new block object with the desired properties
488 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
489 $ipblock->mAddress
= $autoblockip;
491 $ipblock->mBy
= $this->mBy
;
492 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
493 $ipblock->mTimestamp
= wfTimestampNow();
495 $ipblock->mCreateAccount
= $this->mCreateAccount
;
497 # If the user is already blocked with an expiry date, we don't
498 # want to pile on top of that!
500 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
502 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
505 return $ipblock->insert();
508 function deleteIfExpired()
510 $fname = 'Block::deleteIfExpired';
511 wfProfileIn( $fname );
512 if ( $this->isExpired() ) {
513 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
517 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
520 wfProfileOut( $fname );
526 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
527 if ( !$this->mExpiry
) {
530 return wfTimestampNow() > $this->mExpiry
;
536 return $this->mAddress
!= '';
539 function updateTimestamp()
541 if ( $this->mAuto
) {
542 $this->mTimestamp
= wfTimestamp();
543 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
545 $dbw = wfGetDB( DB_MASTER
);
546 $dbw->update( 'ipblocks',
548 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
549 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
550 ), array( /* WHERE */
551 'ipb_address' => $this->mAddress
552 ), 'Block::updateTimestamp'
558 function getIntegerAddr()
560 return $this->mIntegerAddr;
563 function getNetworkBits()
565 return $this->mNetworkBits;
569 * @return The blocker user ID.
571 public function getBy() {
576 * @return The blocker user name.
580 if ( $this->mByName
=== false ) {
581 $this->mByName
= User
::whoIs( $this->mBy
);
583 return $this->mByName
;
586 function forUpdate( $x = NULL ) {
587 return wfSetVar( $this->mForUpdate
, $x );
590 function fromMaster( $x = NULL ) {
591 return wfSetVar( $this->mFromMaster
, $x );
594 function getRedactedName() {
595 if ( $this->mAuto
) {
596 return '#' . $this->mId
;
598 return $this->mAddress
;
603 * Encode expiry for DB
605 static function encodeExpiry( $expiry, $db ) {
606 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
607 return Block
::infinity();
609 return $db->timestamp( $expiry );
614 * Decode expiry which has come from the DB
616 static function decodeExpiry( $expiry ) {
617 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
618 return Block
::infinity();
620 return wfTimestamp( TS_MW
, $expiry );
624 static function getAutoblockExpiry( $timestamp )
626 global $wgAutoblockExpiry;
627 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
630 static function normaliseRange( $range )
632 $parts = explode( '/', $range );
633 if ( count( $parts ) == 2 ) {
634 $shift = 32 - $parts[1];
635 $ipint = IP
::toUnsigned( $parts[0] );
636 $ipint = $ipint >> $shift << $shift;
637 $newip = long2ip( $ipint );
638 $range = "$newip/{$parts[1]}";
644 * Purge expired blocks from the ipblocks table
646 static function purgeExpired() {
647 $dbw = wfGetDB( DB_MASTER
);
648 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
651 static function infinity() {
652 # This is a special keyword for timestamps in PostgreSQL, and
653 # works with CHAR(14) as well because "i" sorts after all numbers.
658 if ( !isset( $infinity ) ) {
659 $dbr = wfGetDB( DB_SLAVE );
660 $infinity = $dbr->bigTimestamp();