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();
53 static function newFromDB( $address, $user = 0, $killExpired = true )
56 $block->load( $address, $user, $killExpired );
57 if ( $block->isValid() ) {
64 static function newFromID( $id )
66 $dbr = wfGetDB( DB_SLAVE
);
67 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
68 array( 'ipb_id' => $id ), __METHOD__
) );
70 if ( $block->loadFromResult( $res ) ) {
79 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
80 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
81 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
82 $this->mBy
= $this->mHideName
= $this->mBlockEmail
= 0;
83 $this->mByName
= false;
87 * Get the DB object and set the reference parameter to the query options
89 function &getDBOptions( &$options )
91 global $wgAntiLockFlags;
92 if ( $this->mForUpdate ||
$this->mFromMaster
) {
93 $db = wfGetDB( DB_MASTER
);
94 if ( !$this->mForUpdate ||
($wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) ) {
97 $options = array( 'FOR UPDATE' );
100 $db = wfGetDB( DB_SLAVE
);
107 * Get a ban from the DB, with either the given address or the given username
109 * @param string $address The IP address of the user, or blank to skip IP blocks
110 * @param integer $user The user ID, or zero for anonymous users
111 * @param bool $killExpired Whether to delete expired rows while loading
114 function load( $address = '', $user = 0, $killExpired = true )
116 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
119 $db =& $this->getDBOptions( $options );
121 if ( 0 == $user && $address == '' ) {
122 # Invalid user specification, not blocked
129 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
130 __METHOD__
, $options ) );
131 if ( $this->loadFromResult( $res, $killExpired ) ) {
137 # TODO: improve performance by merging this query with the autoblock one
138 # Slightly tricky while handling killExpired as well
140 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
141 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
142 if ( $this->loadFromResult( $res, $killExpired ) ) {
143 if ( $user && $this->mAnonOnly
) {
144 # Block is marked anon-only
145 # Whitelist this IP address against autoblocks and range blocks
155 if ( $this->loadRange( $address, $killExpired, $user ) ) {
156 if ( $user && $this->mAnonOnly
) {
166 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
168 $conds['ipb_anon_only'] = 0;
170 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
171 if ( $this->loadFromResult( $res, $killExpired ) ) {
182 * Fill in member variables from a result wrapper
184 function loadFromResult( ResultWrapper
$res, $killExpired = true )
187 if ( 0 != $res->numRows() ) {
189 $row = $res->fetchObject();
190 $this->initFromRow( $row );
192 if ( $killExpired ) {
193 # If requested, delete expired rows
195 $killed = $this->deleteIfExpired();
197 $row = $res->fetchObject();
199 $this->initFromRow( $row );
202 } while ( $killed && $row );
204 # If there were any left after the killing finished, return true
217 * Search the database for any range blocks matching the given address, and
218 * load the row if one is found.
220 function loadRange( $address, $killExpired = true, $user = 0 )
222 $iaddr = IP
::toHex( $address );
223 if ( $iaddr === false ) {
228 # Only scan ranges which start in this /16, this improves search speed
229 # Blocks should not cross a /16 boundary.
230 $range = substr( $iaddr, 0, 4 );
233 $db =& $this->getDBOptions( $options );
235 "ipb_range_start LIKE '$range%'",
236 "ipb_range_start <= '$iaddr'",
237 "ipb_range_end >= '$iaddr'"
241 $conds['ipb_anon_only'] = 0;
244 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
245 $success = $this->loadFromResult( $res, $killExpired );
250 * Determine if a given integer IPv4 address is in a given CIDR network
251 * @deprecated Use IP::isInRange
253 function isAddressInRange( $addr, $range ) {
254 return IP
::isInRange( $addr, $range );
257 function initFromRow( $row )
259 $this->mAddress
= $row->ipb_address
;
260 $this->mReason
= $row->ipb_reason
;
261 $this->mTimestamp
= wfTimestamp(TS_MW
,$row->ipb_timestamp
);
262 $this->mUser
= $row->ipb_user
;
263 $this->mBy
= $row->ipb_by
;
264 $this->mAuto
= $row->ipb_auto
;
265 $this->mAnonOnly
= $row->ipb_anon_only
;
266 $this->mCreateAccount
= $row->ipb_create_account
;
267 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
268 $this->mBlockEmail
= $row->ipb_block_email
;
269 $this->mHideName
= $row->ipb_deleted
;
270 $this->mId
= $row->ipb_id
;
271 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
272 if ( isset( $row->user_name
) ) {
273 $this->mByName
= $row->user_name
;
275 $this->mByName
= $row->ipb_by_text
;
277 $this->mRangeStart
= $row->ipb_range_start
;
278 $this->mRangeEnd
= $row->ipb_range_end
;
281 function initialiseRange()
283 $this->mRangeStart
= '';
284 $this->mRangeEnd
= '';
286 if ( $this->mUser
== 0 ) {
287 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
292 * Callback with a Block object for every block
293 * @return integer number of blocks;
295 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
297 global $wgAntiLockFlags;
299 $block = new Block();
300 if ( $flags & Block
::EB_FOR_UPDATE
) {
301 $db = wfGetDB( DB_MASTER
);
302 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
305 $options = 'FOR UPDATE';
307 $block->forUpdate( true );
309 $db = wfGetDB( DB_SLAVE
);
312 if ( $flags & Block
::EB_RANGE_ONLY
) {
313 $cond = " AND ipb_range_start <> ''";
318 $now = wfTimestampNow();
320 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
322 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
323 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
324 $res = $db->query( $sql, 'Block::enumBlocks' );
325 $num_rows = $db->numRows( $res );
327 while ( $row = $db->fetchObject( $res ) ) {
328 $block->initFromRow( $row );
329 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
333 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
334 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
337 call_user_func( $callback, $block, $tag );
340 call_user_func( $callback, $block, $tag );
343 $db->freeResult( $res );
353 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
356 $dbw = wfGetDB( DB_MASTER
);
357 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
358 return $dbw->affectedRows() > 0;
362 * Insert a block into the block table.
363 * @return Whether or not the insertion was successful.
367 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
368 $dbw = wfGetDB( DB_MASTER
);
370 # Unset ipb_anon_only for user blocks, makes no sense
371 if ( $this->mUser
) {
372 $this->mAnonOnly
= 0;
375 # Unset ipb_enable_autoblock for IP blocks, makes no sense
376 if ( !$this->mUser
) {
377 $this->mEnableAutoblock
= 0;
378 $this->mBlockEmail
= 0; //Same goes for email...
381 if( !$this->mByName
) {
383 $this->mByName
= User
::whoIs( $this->mBy
);
386 $this->mByName
= $wgUser->getName();
390 # Don't collide with expired blocks
391 Block
::purgeExpired();
393 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
394 $dbw->insert( 'ipblocks',
397 'ipb_address' => $this->mAddress
,
398 'ipb_user' => $this->mUser
,
399 'ipb_by' => $this->mBy
,
400 'ipb_by_text' => $this->mByName
,
401 'ipb_reason' => $this->mReason
,
402 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
403 'ipb_auto' => $this->mAuto
,
404 'ipb_anon_only' => $this->mAnonOnly
,
405 'ipb_create_account' => $this->mCreateAccount
,
406 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
407 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
408 'ipb_range_start' => $this->mRangeStart
,
409 'ipb_range_end' => $this->mRangeEnd
,
410 'ipb_deleted' => $this->mHideName
,
411 'ipb_block_email' => $this->mBlockEmail
412 ), 'Block::insert', array( 'IGNORE' )
414 $affected = $dbw->affectedRows();
417 $this->doRetroactiveAutoblock();
423 * Retroactively autoblocks the last IP used by the user (if it is a user)
424 * blocked by this Block.
425 *@return Whether or not a retroactive autoblock was made.
427 function doRetroactiveAutoblock() {
428 $dbr = wfGetDB( DB_SLAVE
);
429 #If autoblock is enabled, autoblock the LAST IP used
430 # - stolen shamelessly from CheckUser_body.php
432 if ($this->mEnableAutoblock
&& $this->mUser
) {
433 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
435 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
436 $conds = array( 'rc_user_text' => $this->mAddress
);
438 if ($this->mAngryAutoblock
) {
439 // Block any IP used in the last 7 days. Up to five IPs.
440 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - (7*86400) ) );
441 $options['LIMIT'] = 5;
443 // Just the last IP used.
444 $options['LIMIT'] = 1;
447 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
448 __METHOD__
, $options);
450 if ( !$dbr->numRows( $res ) ) {
451 #No results, don't autoblock anything
452 wfDebug("No IP found to retroactively autoblock\n");
454 while ( $row = $dbr->fetchObject( $res ) ) {
456 $this->doAutoblock( $row->rc_ip
);
463 * Checks whether a given IP is on the autoblock whitelist.
464 * @param string $autoblockip The IP to check
466 function isWhitelistedFromAutoblocks( $ip ) {
468 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
470 wfDebug("Checking the autoblock whitelist..\n");
472 foreach( $lines as $line ) {
474 if ( substr( $line, 0, 1 ) !== '*' ) {
478 $wlEntry = substr($line, 1);
479 $wlEntry = trim($wlEntry);
481 wfDebug("Checking $ip against $wlEntry...");
483 # Is the IP in this range?
484 if (IP
::isInRange( $ip, $wlEntry )) {
485 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
488 wfDebug( " No match\n" );
496 * Autoblocks the given IP, referring to this Block.
497 * @param string $autoblockip The IP to autoblock.
498 * @param bool $justInserted The main block was just inserted
499 * @return bool Whether or not an autoblock was inserted.
501 function doAutoblock( $autoblockip, $justInserted = false ) {
502 # If autoblocks are disabled, go away.
503 if ( !$this->mEnableAutoblock
) {
507 # Check for presence on the autoblock whitelist
508 if (Block
::isWhitelistedFromAutoblocks($autoblockip)) {
512 ## Allow hooks to cancel the autoblock.
513 if (!wfRunHooks( 'AbortAutoblock', array( $autoblockip, &$this ) )) {
514 wfDebug( "Autoblock aborted by hook." );
518 # It's okay to autoblock. Go ahead and create/insert the block.
520 $ipblock = Block
::newFromDB( $autoblockip );
522 # If the user is already blocked. Then check if the autoblock would
523 # exceed the user block. If it would exceed, then do nothing, else
525 if ($this->mExpiry
&&
526 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
529 # Just update the timestamp
530 if ( !$justInserted ) {
531 $ipblock->updateTimestamp();
535 $ipblock = new Block
;
538 # Make a new block object with the desired properties
539 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
540 $ipblock->mAddress
= $autoblockip;
542 $ipblock->mBy
= $this->mBy
;
543 $ipblock->mByName
= $this->mByName
;
544 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
545 $ipblock->mTimestamp
= wfTimestampNow();
547 $ipblock->mCreateAccount
= $this->mCreateAccount
;
548 # Continue suppressing the name if needed
549 $ipblock->mHideName
= $this->mHideName
;
551 # If the user is already blocked with an expiry date, we don't
552 # want to pile on top of that!
554 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
556 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
559 return $ipblock->insert();
562 function deleteIfExpired()
564 $fname = 'Block::deleteIfExpired';
565 wfProfileIn( $fname );
566 if ( $this->isExpired() ) {
567 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
571 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
574 wfProfileOut( $fname );
580 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
581 if ( !$this->mExpiry
) {
584 return wfTimestampNow() > $this->mExpiry
;
590 return $this->mAddress
!= '';
593 function updateTimestamp()
595 if ( $this->mAuto
) {
596 $this->mTimestamp
= wfTimestamp();
597 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
599 $dbw = wfGetDB( DB_MASTER
);
600 $dbw->update( 'ipblocks',
602 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
603 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
604 ), array( /* WHERE */
605 'ipb_address' => $this->mAddress
606 ), 'Block::updateTimestamp'
612 function getIntegerAddr()
614 return $this->mIntegerAddr;
617 function getNetworkBits()
619 return $this->mNetworkBits;
623 * @return The blocker user ID.
625 public function getBy() {
630 * @return The blocker user name.
634 return $this->mByName
;
637 function forUpdate( $x = NULL ) {
638 return wfSetVar( $this->mForUpdate
, $x );
641 function fromMaster( $x = NULL ) {
642 return wfSetVar( $this->mFromMaster
, $x );
645 function getRedactedName() {
646 if ( $this->mAuto
) {
647 return '#' . $this->mId
;
649 return $this->mAddress
;
654 * Encode expiry for DB
656 static function encodeExpiry( $expiry, $db ) {
657 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
658 return Block
::infinity();
660 return $db->timestamp( $expiry );
665 * Decode expiry which has come from the DB
667 static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
668 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
669 return Block
::infinity();
671 return wfTimestamp( $timestampType, $expiry );
675 static function getAutoblockExpiry( $timestamp )
677 global $wgAutoblockExpiry;
678 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
682 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
683 * For example, 127.111.113.151/24 -> 127.111.113.0/24
685 static function normaliseRange( $range ) {
686 $parts = explode( '/', $range );
687 if ( count( $parts ) == 2 ) {
689 if ( IP
::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
691 $ipint = IP
::toUnsigned6( $parts[0] );
692 # Native 32 bit functions WONT work here!!!
693 # Convert to a padded binary number
694 $network = wfBaseConvert( $ipint, 10, 2, 128 );
695 # Truncate the last (128-$bits) bits and replace them with zeros
696 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
697 # Convert back to an integer
698 $network = wfBaseConvert( $network, 2, 10 );
699 # Reform octet address
700 $newip = IP
::toOctet( $network );
701 $range = "$newip/{$parts[1]}";
703 else if ( IP
::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
704 $shift = 32 - $parts[1];
705 $ipint = IP
::toUnsigned( $parts[0] );
706 $ipint = $ipint >> $shift << $shift;
707 $newip = long2ip( $ipint );
708 $range = "$newip/{$parts[1]}";
715 * Purge expired blocks from the ipblocks table
717 static function purgeExpired() {
718 $dbw = wfGetDB( DB_MASTER
);
719 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
722 static function infinity() {
723 # This is a special keyword for timestamps in PostgreSQL, and
724 # works with CHAR(14) as well because "i" sorts after all numbers.
729 if ( !isset( $infinity ) ) {
730 $dbr = wfGetDB( DB_SLAVE );
731 $infinity = $dbr->bigTimestamp();
738 * Convert a DB-encoded expiry into a real string that humans can read.
740 static function formatExpiry( $encoded_expiry ) {
744 if( is_null( $msg ) ) {
746 $keys = array( 'infiniteblock', 'expiringblock' );
747 foreach( $keys as $key ) {
748 $msg[$key] = wfMsgHtml( $key );
752 $expiry = Block
::decodeExpiry( $encoded_expiry );
753 if ($expiry == 'infinity') {
754 $expirystr = $msg['infiniteblock'];
757 $expiretimestr = $wgLang->timeanddate( $expiry, true );
758 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array($expiretimestr) );
765 * Convert a typed-in expiry time into something we can put into the database.
767 static function parseExpiryInput( $expiry_input ) {
768 if ( $expiry_input == 'infinite' ||
$expiry_input == 'indefinite' ) {
769 $expiry = 'infinity';
771 $expiry = strtotime( $expiry_input );
772 if ($expiry < 0 ||
$expiry === false) {