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 $this->validateBlockParams();
410 # Don't collide with expired blocks
411 Block
::purgeExpired();
413 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
414 $dbw->insert( 'ipblocks',
417 'ipb_address' => $this->mAddress
,
418 'ipb_user' => $this->mUser
,
419 'ipb_by' => $this->mBy
,
420 'ipb_by_text' => $this->mByName
,
421 'ipb_reason' => $this->mReason
,
422 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
423 'ipb_auto' => $this->mAuto
,
424 'ipb_anon_only' => $this->mAnonOnly
,
425 'ipb_create_account' => $this->mCreateAccount
,
426 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
427 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
428 'ipb_range_start' => $this->mRangeStart
,
429 'ipb_range_end' => $this->mRangeEnd
,
430 'ipb_deleted' => $this->mHideName
,
431 'ipb_block_email' => $this->mBlockEmail
432 ), 'Block::insert', array( 'IGNORE' )
434 $affected = $dbw->affectedRows();
437 $this->doRetroactiveAutoblock();
443 * Update block with new parameters.
445 public function update() {
446 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
447 $dbw = wfGetDB( DB_MASTER
);
449 $this->validateBlockParams();
451 $dbw->update( 'ipblocks',
453 'ipb_user' => $this->mUser
,
454 'ipb_by' => $this->mBy
,
455 'ipb_by_text' => $this->mByName
,
456 'ipb_reason' => $this->mReason
,
457 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
458 'ipb_auto' => $this->mAuto
,
459 'ipb_anon_only' => $this->mAnonOnly
,
460 'ipb_create_account' => $this->mCreateAccount
,
461 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
462 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
463 'ipb_range_start' => $this->mRangeStart
,
464 'ipb_range_end' => $this->mRangeEnd
,
465 'ipb_deleted' => $this->mHideName
,
466 'ipb_block_email' => $this->mBlockEmail
),
467 array( 'ipb_id' => $this->mId
),
470 return $dbw->affectedRows();
474 * Make sure all the proper members are set to sane values
475 * before adding/updating a block
477 private function validateBlockParams() {
478 # Unset ipb_anon_only for user blocks, makes no sense
479 if ( $this->mUser
) {
480 $this->mAnonOnly
= 0;
483 # Unset ipb_enable_autoblock for IP blocks, makes no sense
484 if ( !$this->mUser
) {
485 $this->mEnableAutoblock
= 0;
486 $this->mBlockEmail
= 0; //Same goes for email...
489 if( !$this->mByName
) {
491 $this->mByName
= User
::whoIs( $this->mBy
);
494 $this->mByName
= $wgUser->getName();
501 * Retroactively autoblocks the last IP used by the user (if it is a user)
502 * blocked by this Block.
503 * @return bool Whether or not a retroactive autoblock was made.
505 function doRetroactiveAutoblock() {
506 $dbr = wfGetDB( DB_SLAVE
);
507 #If autoblock is enabled, autoblock the LAST IP used
508 # - stolen shamelessly from CheckUser_body.php
510 if ($this->mEnableAutoblock
&& $this->mUser
) {
511 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
513 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
514 $conds = array( 'rc_user_text' => $this->mAddress
);
516 if ($this->mAngryAutoblock
) {
517 // Block any IP used in the last 7 days. Up to five IPs.
518 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - (7*86400) ) );
519 $options['LIMIT'] = 5;
521 // Just the last IP used.
522 $options['LIMIT'] = 1;
525 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
526 __METHOD__
, $options);
528 if ( !$dbr->numRows( $res ) ) {
529 #No results, don't autoblock anything
530 wfDebug("No IP found to retroactively autoblock\n");
532 while ( $row = $dbr->fetchObject( $res ) ) {
534 $this->doAutoblock( $row->rc_ip
);
541 * Checks whether a given IP is on the autoblock whitelist.
543 * @param string $autoblockip The IP to check
545 function isWhitelistedFromAutoblocks( $ip ) {
548 // Try to get the autoblock_whitelist from the cache, as it's faster
549 // than getting the msg raw and explode()'ing it.
550 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
551 $lines = $wgMemc->get( $key );
553 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
554 $wgMemc->set( $key, $lines, 3600 * 24 );
557 wfDebug("Checking the autoblock whitelist..\n");
559 foreach( $lines as $line ) {
561 if ( substr( $line, 0, 1 ) !== '*' ) {
565 $wlEntry = substr($line, 1);
566 $wlEntry = trim($wlEntry);
568 wfDebug("Checking $ip against $wlEntry...");
570 # Is the IP in this range?
571 if (IP
::isInRange( $ip, $wlEntry )) {
572 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
575 wfDebug( " No match\n" );
583 * Autoblocks the given IP, referring to this Block.
584 * @param string $autoblockip The IP to autoblock.
585 * @param bool $justInserted The main block was just inserted
586 * @return bool Whether or not an autoblock was inserted.
588 function doAutoblock( $autoblockip, $justInserted = false ) {
589 # If autoblocks are disabled, go away.
590 if ( !$this->mEnableAutoblock
) {
594 # Check for presence on the autoblock whitelist
595 if (Block
::isWhitelistedFromAutoblocks($autoblockip)) {
599 ## Allow hooks to cancel the autoblock.
600 if (!wfRunHooks( 'AbortAutoblock', array( $autoblockip, &$this ) )) {
601 wfDebug( "Autoblock aborted by hook." );
605 # It's okay to autoblock. Go ahead and create/insert the block.
607 $ipblock = Block
::newFromDB( $autoblockip );
609 # If the user is already blocked. Then check if the autoblock would
610 # exceed the user block. If it would exceed, then do nothing, else
612 if ($this->mExpiry
&&
613 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
616 # Just update the timestamp
617 if ( !$justInserted ) {
618 $ipblock->updateTimestamp();
622 $ipblock = new Block
;
625 # Make a new block object with the desired properties
626 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
627 $ipblock->mAddress
= $autoblockip;
629 $ipblock->mBy
= $this->mBy
;
630 $ipblock->mByName
= $this->mByName
;
631 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
632 $ipblock->mTimestamp
= wfTimestampNow();
634 $ipblock->mCreateAccount
= $this->mCreateAccount
;
635 # Continue suppressing the name if needed
636 $ipblock->mHideName
= $this->mHideName
;
638 # If the user is already blocked with an expiry date, we don't
639 # want to pile on top of that!
641 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
643 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
646 return $ipblock->insert();
650 * Check if a block has expired. Delete it if it is.
653 function deleteIfExpired()
655 $fname = 'Block::deleteIfExpired';
656 wfProfileIn( $fname );
657 if ( $this->isExpired() ) {
658 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
662 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
665 wfProfileOut( $fname );
670 * Has the block expired?
675 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
676 if ( !$this->mExpiry
) {
679 return wfTimestampNow() > $this->mExpiry
;
684 * Is the block address valid (i.e. not a null string?)
689 return $this->mAddress
!= '';
693 * Update the timestamp on autoblocks.
695 function updateTimestamp()
697 if ( $this->mAuto
) {
698 $this->mTimestamp
= wfTimestamp();
699 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
701 $dbw = wfGetDB( DB_MASTER
);
702 $dbw->update( 'ipblocks',
704 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
705 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
706 ), array( /* WHERE */
707 'ipb_address' => $this->mAddress
708 ), 'Block::updateTimestamp'
714 function getIntegerAddr()
716 return $this->mIntegerAddr;
719 function getNetworkBits()
721 return $this->mNetworkBits;
725 * Get the user id of the blocking sysop
728 public function getBy() {
733 * Get the username of the blocking sysop
738 return $this->mByName
;
741 function forUpdate( $x = NULL ) {
742 return wfSetVar( $this->mForUpdate
, $x );
745 function fromMaster( $x = NULL ) {
746 return wfSetVar( $this->mFromMaster
, $x );
749 function getRedactedName() {
750 if ( $this->mAuto
) {
751 return '#' . $this->mId
;
753 return $this->mAddress
;
758 * Encode expiry for DB
760 * @param $expiry string Timestamp for expiry, or
761 * @param $db Database object
763 static function encodeExpiry( $expiry, $db ) {
764 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
765 return Block
::infinity();
767 return $db->timestamp( $expiry );
772 * Decode expiry which has come from the DB
774 * @param $expiry string Database expiry format
775 * @param $timestampType Requested timestamp format
777 static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
778 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
779 return Block
::infinity();
781 return wfTimestamp( $timestampType, $expiry );
786 * Get a timestamp of the expiry for autoblocks
789 static function getAutoblockExpiry( $timestamp )
791 global $wgAutoblockExpiry;
792 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
796 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
797 * For example, 127.111.113.151/24 -> 127.111.113.0/24
798 * @param $range string IP address to normalize
801 static function normaliseRange( $range ) {
802 $parts = explode( '/', $range );
803 if ( count( $parts ) == 2 ) {
805 if ( IP
::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
807 $ipint = IP
::toUnsigned6( $parts[0] );
808 # Native 32 bit functions WONT work here!!!
809 # Convert to a padded binary number
810 $network = wfBaseConvert( $ipint, 10, 2, 128 );
811 # Truncate the last (128-$bits) bits and replace them with zeros
812 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
813 # Convert back to an integer
814 $network = wfBaseConvert( $network, 2, 10 );
815 # Reform octet address
816 $newip = IP
::toOctet( $network );
817 $range = "$newip/{$parts[1]}";
819 else if ( IP
::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
820 $shift = 32 - $parts[1];
821 $ipint = IP
::toUnsigned( $parts[0] );
822 $ipint = $ipint >> $shift << $shift;
823 $newip = long2ip( $ipint );
824 $range = "$newip/{$parts[1]}";
831 * Purge expired blocks from the ipblocks table
833 static function purgeExpired() {
834 $dbw = wfGetDB( DB_MASTER
);
835 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
839 * This is a special keyword for timestamps in PostgreSQL, and
840 * works with CHAR(14) as well because "i" sorts after all numbers.
843 static function infinity() {
848 * Convert a DB-encoded expiry into a real string that humans can read.
849 * @param $encoded_expiry string Database encoded expiry time
852 static function formatExpiry( $encoded_expiry ) {
856 if( is_null( $msg ) ) {
858 $keys = array( 'infiniteblock', 'expiringblock' );
859 foreach( $keys as $key ) {
860 $msg[$key] = wfMsgHtml( $key );
864 $expiry = Block
::decodeExpiry( $encoded_expiry );
865 if ($expiry == 'infinity') {
866 $expirystr = $msg['infiniteblock'];
869 $expiretimestr = $wgLang->timeanddate( $expiry, true );
870 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array($expiretimestr) );
877 * Convert a typed-in expiry time into something we can put into the database.
878 * @param $expiry_input string Whatever was typed into the form
879 * @return string More database friendly
881 static function parseExpiryInput( $expiry_input ) {
882 if ( $expiry_input == 'infinite' ||
$expiry_input == 'indefinite' ) {
883 $expiry = 'infinity';
885 $expiry = strtotime( $expiry_input );
886 if ($expiry < 0 ||
$expiry === false) {