4 * 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.
18 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
19 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock, $mHideName,
20 $mBlockEmail, $mByName, $mAngryAutoblock;
21 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster;
23 const EB_KEEP_EXPIRED
= 1;
24 const EB_FOR_UPDATE
= 2;
25 const EB_RANGE_ONLY
= 4;
27 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
28 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
29 $hideName = 0, $blockEmail = 0 )
32 # Expand valid IPv6 addresses
33 $address = IP
::sanitizeIP( $address );
34 $this->mAddress
= $address;
37 $this->mReason
= $reason;
38 $this->mTimestamp
= wfTimestamp(TS_MW
,$timestamp);
40 $this->mAnonOnly
= $anonOnly;
41 $this->mCreateAccount
= $createAccount;
42 $this->mExpiry
= self
::decodeExpiry( $expiry );
43 $this->mEnableAutoblock
= $enableAutoblock;
44 $this->mHideName
= $hideName;
45 $this->mBlockEmail
= $blockEmail;
46 $this->mForUpdate
= false;
47 $this->mFromMaster
= false;
48 $this->mByName
= false;
49 $this->mAngryAutoblock
= false;
50 $this->initialiseRange();
54 * Load a block from the database, using either the IP address or
57 * @return Block Object
58 * @param $address string IP address of user/anon
59 * @param $user int User id of user
60 * @param $killExpired bool Delete expired blocks on load
62 static function newFromDB( $address, $user = 0, $killExpired = true )
65 $block->load( $address, $user, $killExpired );
66 if ( $block->isValid() ) {
74 * Load a blocked user from their block id.
75 * @return Block object
76 * @param $id int Block id to search for
78 static function newFromID( $id )
80 $dbr = wfGetDB( DB_SLAVE
);
81 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
82 array( 'ipb_id' => $id ), __METHOD__
) );
84 if ( $block->loadFromResult( $res ) ) {
92 * Clear all member variables in the current object. Does not clear
93 * the block from the DB.
97 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
98 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
99 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
100 $this->mBy
= $this->mHideName
= $this->mBlockEmail
= 0;
101 $this->mByName
= false;
105 * Get the DB object and set the reference parameter to the query options
108 function &getDBOptions( &$options ) {
109 global $wgAntiLockFlags;
110 if ( $this->mForUpdate ||
$this->mFromMaster
) {
111 $db = wfGetDB( DB_MASTER
);
112 if ( !$this->mForUpdate ||
($wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) ) {
115 $options = array( 'FOR UPDATE' );
118 $db = wfGetDB( DB_SLAVE
);
125 * Get a ban from the DB, with either the given address or the given username
127 * @param $address string The IP address of the user, or blank to skip IP blocks
128 * @param $user int The user ID, or zero for anonymous users
129 * @param $killExpired bool Whether to delete expired rows while loading
132 function load( $address = '', $user = 0, $killExpired = true )
134 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
137 $db =& $this->getDBOptions( $options );
139 if ( 0 == $user && $address == '' ) {
140 # Invalid user specification, not blocked
147 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
148 __METHOD__
, $options ) );
149 if ( $this->loadFromResult( $res, $killExpired ) ) {
155 # TODO: improve performance by merging this query with the autoblock one
156 # Slightly tricky while handling killExpired as well
158 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
159 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
160 if ( $this->loadFromResult( $res, $killExpired ) ) {
161 if ( $user && $this->mAnonOnly
) {
162 # Block is marked anon-only
163 # Whitelist this IP address against autoblocks and range blocks
173 if ( $this->loadRange( $address, $killExpired, $user ) ) {
174 if ( $user && $this->mAnonOnly
) {
184 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
186 $conds['ipb_anon_only'] = 0;
188 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
189 if ( $this->loadFromResult( $res, $killExpired ) ) {
200 * Fill in member variables from a result wrapper
202 * @param $res ResultWrapper Row from the ipblocks table
203 * @param $killExpired bool Whether to delete expired rows while loading
205 function loadFromResult( ResultWrapper
$res, $killExpired = true )
208 if ( 0 != $res->numRows() ) {
210 $row = $res->fetchObject();
211 $this->initFromRow( $row );
213 if ( $killExpired ) {
214 # If requested, delete expired rows
216 $killed = $this->deleteIfExpired();
218 $row = $res->fetchObject();
220 $this->initFromRow( $row );
223 } while ( $killed && $row );
225 # If there were any left after the killing finished, return true
238 * Search the database for any range blocks matching the given address, and
239 * load the row if one is found.
241 * @param $address string IP address range
242 * @param $killExpired bool Whether to delete expired rows while loading
243 * @param $userid int If not 0, then sets ipb_anon_only
245 function loadRange( $address, $killExpired = true, $user = 0 )
247 $iaddr = IP
::toHex( $address );
248 if ( $iaddr === false ) {
253 # Only scan ranges which start in this /16, this improves search speed
254 # Blocks should not cross a /16 boundary.
255 $range = substr( $iaddr, 0, 4 );
258 $db =& $this->getDBOptions( $options );
260 "ipb_range_start LIKE '$range%'",
261 "ipb_range_start <= '$iaddr'",
262 "ipb_range_end >= '$iaddr'"
266 $conds['ipb_anon_only'] = 0;
269 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
270 $success = $this->loadFromResult( $res, $killExpired );
275 * Determine if a given integer IPv4 address is in a given CIDR network
276 * @deprecated Use IP::isInRange
278 function isAddressInRange( $addr, $range ) {
279 return IP
::isInRange( $addr, $range );
283 * Given a database row from the ipblocks table, initialize
285 * @param $row ResultWrapper A row from the ipblocks table
287 function initFromRow( $row )
289 $this->mAddress
= $row->ipb_address
;
290 $this->mReason
= $row->ipb_reason
;
291 $this->mTimestamp
= wfTimestamp(TS_MW
,$row->ipb_timestamp
);
292 $this->mUser
= $row->ipb_user
;
293 $this->mBy
= $row->ipb_by
;
294 $this->mAuto
= $row->ipb_auto
;
295 $this->mAnonOnly
= $row->ipb_anon_only
;
296 $this->mCreateAccount
= $row->ipb_create_account
;
297 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
298 $this->mBlockEmail
= $row->ipb_block_email
;
299 $this->mHideName
= $row->ipb_deleted
;
300 $this->mId
= $row->ipb_id
;
301 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
302 if ( isset( $row->user_name
) ) {
303 $this->mByName
= $row->user_name
;
305 $this->mByName
= $row->ipb_by_text
;
307 $this->mRangeStart
= $row->ipb_range_start
;
308 $this->mRangeEnd
= $row->ipb_range_end
;
312 * Once $mAddress has been set, get the range they came from.
313 * Wrapper for IP::parseRange
315 function initialiseRange()
317 $this->mRangeStart
= '';
318 $this->mRangeEnd
= '';
320 if ( $this->mUser
== 0 ) {
321 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
326 * Callback with a Block object for every block
327 * @return integer number of blocks;
329 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
331 global $wgAntiLockFlags;
333 $block = new Block();
334 if ( $flags & Block
::EB_FOR_UPDATE
) {
335 $db = wfGetDB( DB_MASTER
);
336 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
339 $options = 'FOR UPDATE';
341 $block->forUpdate( true );
343 $db = wfGetDB( DB_SLAVE
);
346 if ( $flags & Block
::EB_RANGE_ONLY
) {
347 $cond = " AND ipb_range_start <> ''";
352 $now = wfTimestampNow();
354 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
356 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
357 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
358 $res = $db->query( $sql, 'Block::enumBlocks' );
359 $num_rows = $db->numRows( $res );
361 while ( $row = $db->fetchObject( $res ) ) {
362 $block->initFromRow( $row );
363 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
367 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
368 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
371 call_user_func( $callback, $block, $tag );
374 call_user_func( $callback, $block, $tag );
377 $db->freeResult( $res );
382 * Delete the row from the IP blocks table.
391 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
394 $dbw = wfGetDB( DB_MASTER
);
395 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
396 return $dbw->affectedRows() > 0;
400 * Insert a block into the block table.
401 * @return bool Whether or not the insertion was successful.
405 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
406 $dbw = wfGetDB( DB_MASTER
);
408 # Unset ipb_anon_only for user blocks, makes no sense
409 if ( $this->mUser
) {
410 $this->mAnonOnly
= 0;
413 # Unset ipb_enable_autoblock for IP blocks, makes no sense
414 if ( !$this->mUser
) {
415 $this->mEnableAutoblock
= 0;
416 $this->mBlockEmail
= 0; //Same goes for email...
419 if( !$this->mByName
) {
421 $this->mByName
= User
::whoIs( $this->mBy
);
424 $this->mByName
= $wgUser->getName();
428 # Don't collide with expired blocks
429 Block
::purgeExpired();
431 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
432 $dbw->insert( 'ipblocks',
435 'ipb_address' => $this->mAddress
,
436 'ipb_user' => $this->mUser
,
437 'ipb_by' => $this->mBy
,
438 'ipb_by_text' => $this->mByName
,
439 'ipb_reason' => $this->mReason
,
440 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
441 'ipb_auto' => $this->mAuto
,
442 'ipb_anon_only' => $this->mAnonOnly
,
443 'ipb_create_account' => $this->mCreateAccount
,
444 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
445 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
446 'ipb_range_start' => $this->mRangeStart
,
447 'ipb_range_end' => $this->mRangeEnd
,
448 'ipb_deleted' => $this->mHideName
,
449 'ipb_block_email' => $this->mBlockEmail
450 ), 'Block::insert', array( 'IGNORE' )
452 $affected = $dbw->affectedRows();
455 $this->doRetroactiveAutoblock();
461 * Retroactively autoblocks the last IP used by the user (if it is a user)
462 * blocked by this Block.
463 * @return bool Whether or not a retroactive autoblock was made.
465 function doRetroactiveAutoblock() {
466 $dbr = wfGetDB( DB_SLAVE
);
467 #If autoblock is enabled, autoblock the LAST IP used
468 # - stolen shamelessly from CheckUser_body.php
470 if ($this->mEnableAutoblock
&& $this->mUser
) {
471 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
473 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
474 $conds = array( 'rc_user_text' => $this->mAddress
);
476 if ($this->mAngryAutoblock
) {
477 // Block any IP used in the last 7 days. Up to five IPs.
478 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - (7*86400) ) );
479 $options['LIMIT'] = 5;
481 // Just the last IP used.
482 $options['LIMIT'] = 1;
485 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
486 __METHOD__
, $options);
488 if ( !$dbr->numRows( $res ) ) {
489 #No results, don't autoblock anything
490 wfDebug("No IP found to retroactively autoblock\n");
492 while ( $row = $dbr->fetchObject( $res ) ) {
494 $this->doAutoblock( $row->rc_ip
);
501 * Checks whether a given IP is on the autoblock whitelist.
503 * @param string $autoblockip The IP to check
505 function isWhitelistedFromAutoblocks( $ip ) {
508 // Try to get the autoblock_whitelist from the cache, as it's faster
509 // than getting the msg raw and explode()'ing it.
510 $key = wfMemc( 'ipb', 'autoblock', 'whitelist' );
511 $lines = $wgMemc->get( $key );
513 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
514 $wgMemc->set( $key, $lines, 3600 * 24 );
517 wfDebug("Checking the autoblock whitelist..\n");
519 foreach( $lines as $line ) {
521 if ( substr( $line, 0, 1 ) !== '*' ) {
525 $wlEntry = substr($line, 1);
526 $wlEntry = trim($wlEntry);
528 wfDebug("Checking $ip against $wlEntry...");
530 # Is the IP in this range?
531 if (IP
::isInRange( $ip, $wlEntry )) {
532 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
535 wfDebug( " No match\n" );
543 * Autoblocks the given IP, referring to this Block.
544 * @param string $autoblockip The IP to autoblock.
545 * @param bool $justInserted The main block was just inserted
546 * @return bool Whether or not an autoblock was inserted.
548 function doAutoblock( $autoblockip, $justInserted = false ) {
549 # If autoblocks are disabled, go away.
550 if ( !$this->mEnableAutoblock
) {
554 # Check for presence on the autoblock whitelist
555 if (Block
::isWhitelistedFromAutoblocks($autoblockip)) {
559 ## Allow hooks to cancel the autoblock.
560 if (!wfRunHooks( 'AbortAutoblock', array( $autoblockip, &$this ) )) {
561 wfDebug( "Autoblock aborted by hook." );
565 # It's okay to autoblock. Go ahead and create/insert the block.
567 $ipblock = Block
::newFromDB( $autoblockip );
569 # If the user is already blocked. Then check if the autoblock would
570 # exceed the user block. If it would exceed, then do nothing, else
572 if ($this->mExpiry
&&
573 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
576 # Just update the timestamp
577 if ( !$justInserted ) {
578 $ipblock->updateTimestamp();
582 $ipblock = new Block
;
585 # Make a new block object with the desired properties
586 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
587 $ipblock->mAddress
= $autoblockip;
589 $ipblock->mBy
= $this->mBy
;
590 $ipblock->mByName
= $this->mByName
;
591 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
592 $ipblock->mTimestamp
= wfTimestampNow();
594 $ipblock->mCreateAccount
= $this->mCreateAccount
;
595 # Continue suppressing the name if needed
596 $ipblock->mHideName
= $this->mHideName
;
598 # If the user is already blocked with an expiry date, we don't
599 # want to pile on top of that!
601 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
603 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
606 return $ipblock->insert();
610 * Check if a block has expired. Delete it if it is.
613 function deleteIfExpired()
615 $fname = 'Block::deleteIfExpired';
616 wfProfileIn( $fname );
617 if ( $this->isExpired() ) {
618 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
622 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
625 wfProfileOut( $fname );
630 * Has the block expired?
635 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
636 if ( !$this->mExpiry
) {
639 return wfTimestampNow() > $this->mExpiry
;
644 * Is the block address valid (i.e. not a null string?)
649 return $this->mAddress
!= '';
653 * Update the timestamp on autoblocks.
655 function updateTimestamp()
657 if ( $this->mAuto
) {
658 $this->mTimestamp
= wfTimestamp();
659 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
661 $dbw = wfGetDB( DB_MASTER
);
662 $dbw->update( 'ipblocks',
664 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
665 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
666 ), array( /* WHERE */
667 'ipb_address' => $this->mAddress
668 ), 'Block::updateTimestamp'
674 function getIntegerAddr()
676 return $this->mIntegerAddr;
679 function getNetworkBits()
681 return $this->mNetworkBits;
685 * Get the user id of the blocking sysop
688 public function getBy() {
693 * Get the username of the blocking sysop
698 return $this->mByName
;
701 function forUpdate( $x = NULL ) {
702 return wfSetVar( $this->mForUpdate
, $x );
705 function fromMaster( $x = NULL ) {
706 return wfSetVar( $this->mFromMaster
, $x );
709 function getRedactedName() {
710 if ( $this->mAuto
) {
711 return '#' . $this->mId
;
713 return $this->mAddress
;
718 * Encode expiry for DB
720 * @param $expiry string Timestamp for expiry, or
721 * @param $db Database object
723 static function encodeExpiry( $expiry, $db ) {
724 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
725 return Block
::infinity();
727 return $db->timestamp( $expiry );
732 * Decode expiry which has come from the DB
734 * @param $expiry string Database expiry format
735 * @param $timestampType Requested timestamp format
737 static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
738 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
739 return Block
::infinity();
741 return wfTimestamp( $timestampType, $expiry );
746 * Get a timestamp of the expiry for autoblocks
749 static function getAutoblockExpiry( $timestamp )
751 global $wgAutoblockExpiry;
752 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
756 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
757 * For example, 127.111.113.151/24 -> 127.111.113.0/24
758 * @param $range string IP address to normalize
761 static function normaliseRange( $range ) {
762 $parts = explode( '/', $range );
763 if ( count( $parts ) == 2 ) {
765 if ( IP
::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
767 $ipint = IP
::toUnsigned6( $parts[0] );
768 # Native 32 bit functions WONT work here!!!
769 # Convert to a padded binary number
770 $network = wfBaseConvert( $ipint, 10, 2, 128 );
771 # Truncate the last (128-$bits) bits and replace them with zeros
772 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
773 # Convert back to an integer
774 $network = wfBaseConvert( $network, 2, 10 );
775 # Reform octet address
776 $newip = IP
::toOctet( $network );
777 $range = "$newip/{$parts[1]}";
779 else if ( IP
::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
780 $shift = 32 - $parts[1];
781 $ipint = IP
::toUnsigned( $parts[0] );
782 $ipint = $ipint >> $shift << $shift;
783 $newip = long2ip( $ipint );
784 $range = "$newip/{$parts[1]}";
791 * Purge expired blocks from the ipblocks table
793 static function purgeExpired() {
794 $dbw = wfGetDB( DB_MASTER
);
795 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
799 * This is a special keyword for timestamps in PostgreSQL, and
800 * works with CHAR(14) as well because "i" sorts after all numbers.
803 static function infinity() {
808 * Convert a DB-encoded expiry into a real string that humans can read.
811 * @todo @fixme This is nasty. Forces a msg on the expiry, which isn't what
812 * we want. Probably want to abstract out the number formatting so it can
813 * be used elsewhere (some bug I forgot and can't find at the moment)
815 static function formatExpiry( $encoded_expiry ) {
819 if( is_null( $msg ) ) {
821 $keys = array( 'infiniteblock', 'expiringblock' );
822 foreach( $keys as $key ) {
823 $msg[$key] = wfMsgHtml( $key );
827 $expiry = Block
::decodeExpiry( $encoded_expiry );
828 if ($expiry == 'infinity') {
829 $expirystr = $msg['infiniteblock'];
832 $expiretimestr = $wgLang->timeanddate( $expiry, true );
833 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array($expiretimestr) );
840 * Convert a typed-in expiry time into something we can put into the database.
841 * @param $expiry_input string Whatever was typed into the form
842 * @return string More database friendly
844 static function parseExpiryInput( $expiry_input ) {
845 if ( $expiry_input == 'infinite' ||
$expiry_input == 'indefinite' ) {
846 $expiry = 'infinity';
848 $expiry = strtotime( $expiry_input );
849 if ($expiry < 0 ||
$expiry === false) {