3 * Blocks and bans object
9 * All the functions in this class assume the object is either explicitly
10 * loaded or filled. It is not load-on-demand. There are no accessors.
12 * Globals used: $wgAutoblockExpiry, $wgAntiLockFlags
14 * @todo This could be used everywhere, but it isn't.
19 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
20 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock;
21 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster, $mByName;
23 const EB_KEEP_EXPIRED
= 1;
24 const EB_FOR_UPDATE
= 2;
25 const EB_RANGE_ONLY
= 4;
27 function Block( $address = '', $user = 0, $by = 0, $reason = '',
28 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0 )
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 );
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 == 0 ) ) {
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 ) {
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 )
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'"
237 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
238 $success = $this->loadFromResult( $res, $killExpired );
243 * Determine if a given integer IPv4 address is in a given CIDR network
244 * @deprecated Use IP::isAddressInRange
246 function isAddressInRange( $addr, $range ) {
247 return IP
::isAddressInRange( $addr, $range );
250 function initFromRow( $row )
252 $this->mAddress
= $row->ipb_address
;
253 $this->mReason
= $row->ipb_reason
;
254 $this->mTimestamp
= wfTimestamp(TS_MW
,$row->ipb_timestamp
);
255 $this->mUser
= $row->ipb_user
;
256 $this->mBy
= $row->ipb_by
;
257 $this->mAuto
= $row->ipb_auto
;
258 $this->mAnonOnly
= $row->ipb_anon_only
;
259 $this->mCreateAccount
= $row->ipb_create_account
;
260 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
261 $this->mId
= $row->ipb_id
;
262 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
263 if ( isset( $row->user_name
) ) {
264 $this->mByName
= $row->user_name
;
266 $this->mByName
= false;
268 $this->mRangeStart
= $row->ipb_range_start
;
269 $this->mRangeEnd
= $row->ipb_range_end
;
272 function initialiseRange()
274 $this->mRangeStart
= '';
275 $this->mRangeEnd
= '';
277 if ( $this->mUser
== 0 ) {
278 list($this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange
$this->mAddress
);
283 * Callback with a Block object for every block
284 * @return integer number of blocks;
286 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
288 global $wgAntiLockFlags;
290 $block = new Block();
291 if ( $flags & Block
::EB_FOR_UPDATE
) {
292 $db =& wfGetDB( DB_MASTER
);
293 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
296 $options = 'FOR UPDATE';
298 $block->forUpdate( true );
300 $db =& wfGetDB( DB_SLAVE
);
303 if ( $flags & Block
::EB_RANGE_ONLY
) {
304 $cond = " AND ipb_range_start <> ''";
309 $now = wfTimestampNow();
311 extract( $db->tableNames( 'ipblocks', 'user' ) );
313 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
314 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
315 $res = $db->query( $sql, 'Block::enumBlocks' );
316 $num_rows = $db->numRows( $res );
318 while ( $row = $db->fetchObject( $res ) ) {
319 $block->initFromRow( $row );
320 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
324 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
325 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
328 call_user_func( $callback, $block, $tag );
331 call_user_func( $callback, $block, $tag );
334 $db->freeResult( $res );
344 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
347 $dbw =& wfGetDB( DB_MASTER
);
348 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
349 return $dbw->affectedRows() > 0;
353 * Insert a block into the block table.
354 *@return Whether or not the insertion was successful.
358 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
359 $dbw =& wfGetDB( DB_MASTER
);
362 # Unset ipb_anon_only for user blocks, makes no sense
363 if ( $this->mUser
) {
364 $this->mAnonOnly
= 0;
367 # Unset ipb_enable_autoblock for IP blocks, makes no sense
368 if ( !$this->mUser
) {
369 $this->mEnableAutoblock
= 0;
372 # Don't collide with expired blocks
373 Block
::purgeExpired();
375 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
376 $dbw->insert( 'ipblocks',
379 'ipb_address' => $this->mAddress
,
380 'ipb_user' => $this->mUser
,
381 'ipb_by' => $this->mBy
,
382 'ipb_reason' => $this->mReason
,
383 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
384 'ipb_auto' => $this->mAuto
,
385 'ipb_anon_only' => $this->mAnonOnly
,
386 'ipb_create_account' => $this->mCreateAccount
,
387 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
388 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
389 'ipb_range_start' => $this->mRangeStart
,
390 'ipb_range_end' => $this->mRangeEnd
,
391 ), 'Block::insert', array( 'IGNORE' )
393 $affected = $dbw->affectedRows();
397 $this->doRetroactiveAutoblock();
403 * Retroactively autoblocks the last IP used by the user (if it is a user)
404 * blocked by this Block.
405 *@return Whether or not a retroactive autoblock was made.
407 function doRetroactiveAutoblock() {
408 $dbr = wfGetDb( DB_SLAVE
);
409 #If autoblock is enabled, autoblock the LAST IP used
410 # - stolen shamelessly from CheckUser_body.php
412 if ($this->mEnableAutoblock
&& $this->mUser
) {
413 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
415 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress
),
416 $fname, array( 'ORDER BY' => 'rc_timestamp DESC' ) );
418 if ( !$row ||
!$row->rc_ip
) {
419 #No results, don't autoblock anything
420 wfDebug("No IP found to retroactively autoblock\n");
422 #Limit is 1, so no loop needed.
423 $retroblockip = $row->rc_ip
;
424 return $this->doAutoblock($retroblockip);
430 * Autoblocks the given IP, referring to this Block.
431 * @param string $autoblockip The IP to autoblock, dotted-quad.
432 * @return bool True if an autoblock was inserted OR redundant to preexisting block.
434 public function doAutoblock( $autoblockip ) {
435 # Check if this IP address is already blocked
436 $dbw =& wfGetDb( DB_MASTER
);
439 # If autoblocks are disabled, or if this IP is whitelisted, go away.
440 if ( !$this->mEnableAutoblock || self
::isWhitelistedIp( $autoblockip ) ) {
444 # It's okay to autoblock. Go ahead and create/insert the block.
446 $ipblock = Block
::newFromDB( $autoblockip );
448 # If the user is already blocked. Then check if the autoblock would
449 # exceed the user block. If it would exceed, then do nothing, else
451 if ($this->mExpiry
&&
452 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
455 # Just update the timestamp
456 $ipblock->updateTimestamp();
459 $ipblock = new Block
;
462 # Make a new block object with the desired properties
463 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
464 $ipblock->mAddress
= $autoblockip;
466 $ipblock->mBy
= $this->mBy
;
467 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
468 $ipblock->mTimestamp
= wfTimestampNow();
470 $ipblock->mCreateAccount
= $this->mCreateAccount
;
472 # If the user is already blocked with an expiry date, we don't
473 # want to pile on top of that!
475 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
477 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
480 return $ipblock->insert();
484 * Checks whether an IP is whitelisted in the autoblock_whitelist message.
487 * @param string $ip Dotted quad
490 private static function isWhitelistedIp( $ip ) {
491 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
493 wfDebug("Checking the autoblock whitelist..\n");
495 foreach( $lines as $line ) {
496 # Parse list items only
497 if ( substr( $line, 0, 1 ) !== '*' ) {
501 $wlEntry = substr($line, 1);
502 $wlEntry = trim($wlEntry);
504 wfDebug("Checking $wlEntry\n");
506 # Is the IP in this range?
507 if (IP
::isAddressInRange( $autoblockip, $wlEntry )) {
508 wfDebug("IP $autoblockip matches $wlEntry, not autoblocking\n");
509 return true; #This /SHOULD/ introduce a dummy block - but
510 # I don't know a safe way to do so. -werdna
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 * Purge expired blocks from the ipblocks table
653 static function purgeExpired() {
654 $dbw =& wfGetDB( DB_MASTER
);
655 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
658 static function infinity() {
659 # This is a special keyword for timestamps in PostgreSQL, and
660 # works with CHAR(14) as well because "i" sorts after all numbers.
665 if ( !isset( $infinity ) ) {
666 $dbr =& wfGetDB( DB_SLAVE );
667 $infinity = $dbr->bigTimestamp();