Okay brion, this patch actually /works/. Thanks to the miracles of testing, I can...
[mediawiki.git] / includes / Block.php
blob644fd9c161302cb32d94fc2390c9f0ea95abf576
1 <?php
2 /**
3 * Blocks and bans object
4 * @package MediaWiki
5 */
7 /**
8 * The block class
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.
15 * @package MediaWiki
17 class Block
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 )
30 $this->mId = 0;
31 $this->mAddress = $address;
32 $this->mUser = $user;
33 $this->mBy = $by;
34 $this->mReason = $reason;
35 $this->mTimestamp = wfTimestamp(TS_MW,$timestamp);
36 $this->mAuto = $auto;
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 )
50 $block = new Block();
51 $block->load( $address, $user, $killExpired );
52 if ( $block->isValid() ) {
53 return $block;
54 } else {
55 return null;
59 static function newFromID( $id )
61 $dbr =& wfGetDB( DB_SLAVE );
62 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
63 array( 'ipb_id' => $id ), __METHOD__ ) );
64 $block = new Block;
65 if ( $block->loadFromResult( $res ) ) {
66 return $block;
67 } else {
68 return null;
72 function clear()
74 $this->mAddress = $this->mReason = $this->mTimestamp = '';
75 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
76 $this->mEnableAutoblock = $this->mAuto = $this->mUser =
77 $this->mBy = 0;
78 $this->mByName = false;
81 /**
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) ) {
90 $options = array();
91 } else {
92 $options = array( 'FOR UPDATE' );
94 } else {
95 $db =& wfGetDB( DB_SLAVE );
96 $options = array();
98 return $db;
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" );
113 $options = array();
114 $db =& $this->getDBOptions( $options );
116 if ( 0 == $user && $address == '' ) {
117 # Invalid user specification, not blocked
118 $this->clear();
119 return false;
122 # Try user block
123 if ( $user ) {
124 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
125 __METHOD__, $options ) );
126 if ( $this->loadFromResult( $res, $killExpired ) ) {
127 return true;
130 $userObject = User::newFromId($user);
132 if ($userObject->isAllowed('ipblock-exempt') ) {
133 $address = '';
137 # Try IP block
138 # TODO: improve performance by merging this query with the autoblock one
139 # Slightly tricky while handling killExpired as well
140 if ( $address ) {
141 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
142 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
143 if ( $this->loadFromResult( $res, $killExpired ) ) {
144 if ( $user && $this->mAnonOnly ) {
145 # Block is marked anon-only
146 # Whitelist this IP address against autoblocks and range blocks
147 $this->clear();
148 return false;
149 } else {
150 return true;
155 # Try range block
156 if ( $this->loadRange( $address, $killExpired, $user == 0 ) ) {
157 if ( $user && $this->mAnonOnly ) {
158 $this->clear();
159 return false;
160 } else {
161 return true;
165 # Try autoblock
166 if ( $address ) {
167 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
168 if ( $user ) {
169 $conds['ipb_anon_only'] = 0;
171 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
172 if ( $this->loadFromResult( $res, $killExpired ) ) {
173 return true;
177 # Give up
178 $this->clear();
179 return false;
183 * Fill in member variables from a result wrapper
185 function loadFromResult( ResultWrapper $res, $killExpired = true ) {
186 $ret = false;
187 if ( 0 != $res->numRows() ) {
188 # Get first block
189 $row = $res->fetchObject();
190 $this->initFromRow( $row );
192 if ( $killExpired ) {
193 # If requested, delete expired rows
194 do {
195 $killed = $this->deleteIfExpired();
196 if ( $killed ) {
197 $row = $res->fetchObject();
198 if ( $row ) {
199 $this->initFromRow( $row );
202 } while ( $killed && $row );
204 # If there were any left after the killing finished, return true
205 if ( $row ) {
206 $ret = true;
208 } else {
209 $ret = true;
212 $res->free();
213 return $ret;
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 )
222 $iaddr = IP::toHex( $address );
223 if ( $iaddr === false ) {
224 # Invalid address
225 return 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 );
232 $options = array();
233 $db =& $this->getDBOptions( $options );
234 $conds = array(
235 "ipb_range_start LIKE '$range%'",
236 "ipb_range_start <= '$iaddr'",
237 "ipb_range_end >= '$iaddr'"
240 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
241 $success = $this->loadFromResult( $res, $killExpired );
242 return $success;
246 * Determine if a given integer IPv4 address is in a given CIDR network
247 * @deprecated Use IP::isInRange
249 function isAddressInRange( $addr, $range ) {
250 return IP::isInRange( $addr, $range );
253 function initFromRow( $row )
255 $this->mAddress = $row->ipb_address;
256 $this->mReason = $row->ipb_reason;
257 $this->mTimestamp = wfTimestamp(TS_MW,$row->ipb_timestamp);
258 $this->mUser = $row->ipb_user;
259 $this->mBy = $row->ipb_by;
260 $this->mAuto = $row->ipb_auto;
261 $this->mAnonOnly = $row->ipb_anon_only;
262 $this->mCreateAccount = $row->ipb_create_account;
263 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
264 $this->mId = $row->ipb_id;
265 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
266 if ( isset( $row->user_name ) ) {
267 $this->mByName = $row->user_name;
268 } else {
269 $this->mByName = false;
271 $this->mRangeStart = $row->ipb_range_start;
272 $this->mRangeEnd = $row->ipb_range_end;
275 function initialiseRange()
277 $this->mRangeStart = '';
278 $this->mRangeEnd = '';
280 if ( $this->mUser == 0 ) {
281 list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress );
286 * Callback with a Block object for every block
287 * @return integer number of blocks;
289 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
291 global $wgAntiLockFlags;
293 $block = new Block();
294 if ( $flags & Block::EB_FOR_UPDATE ) {
295 $db =& wfGetDB( DB_MASTER );
296 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK ) {
297 $options = '';
298 } else {
299 $options = 'FOR UPDATE';
301 $block->forUpdate( true );
302 } else {
303 $db =& wfGetDB( DB_SLAVE );
304 $options = '';
306 if ( $flags & Block::EB_RANGE_ONLY ) {
307 $cond = " AND ipb_range_start <> ''";
308 } else {
309 $cond = '';
312 $now = wfTimestampNow();
314 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
316 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
317 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
318 $res = $db->query( $sql, 'Block::enumBlocks' );
319 $num_rows = $db->numRows( $res );
321 while ( $row = $db->fetchObject( $res ) ) {
322 $block->initFromRow( $row );
323 if ( ( $flags & Block::EB_RANGE_ONLY ) && $block->mRangeStart == '' ) {
324 continue;
327 if ( !( $flags & Block::EB_KEEP_EXPIRED ) ) {
328 if ( $block->mExpiry && $now > $block->mExpiry ) {
329 $block->delete();
330 } else {
331 call_user_func( $callback, $block, $tag );
333 } else {
334 call_user_func( $callback, $block, $tag );
337 $db->freeResult( $res );
338 return $num_rows;
341 function delete()
343 if (wfReadOnly()) {
344 return false;
346 if ( !$this->mId ) {
347 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
350 $dbw =& wfGetDB( DB_MASTER );
351 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
352 return $dbw->affectedRows() > 0;
356 * Insert a block into the block table.
357 *@return Whether or not the insertion was successful.
359 function insert()
361 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
362 $dbw =& wfGetDB( DB_MASTER );
363 $dbw->begin();
365 # Unset ipb_anon_only for user blocks, makes no sense
366 if ( $this->mUser ) {
367 $this->mAnonOnly = 0;
370 # Unset ipb_enable_autoblock for IP blocks, makes no sense
371 if ( !$this->mUser ) {
372 $this->mEnableAutoblock = 0;
375 # Don't collide with expired blocks
376 Block::purgeExpired();
378 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
379 $dbw->insert( 'ipblocks',
380 array(
381 'ipb_id' => $ipb_id,
382 'ipb_address' => $this->mAddress,
383 'ipb_user' => $this->mUser,
384 'ipb_by' => $this->mBy,
385 'ipb_reason' => $this->mReason,
386 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
387 'ipb_auto' => $this->mAuto,
388 'ipb_anon_only' => $this->mAnonOnly,
389 'ipb_create_account' => $this->mCreateAccount,
390 'ipb_enable_autoblock' => $this->mEnableAutoblock,
391 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
392 'ipb_range_start' => $this->mRangeStart,
393 'ipb_range_end' => $this->mRangeEnd,
394 ), 'Block::insert', array( 'IGNORE' )
396 $affected = $dbw->affectedRows();
397 $dbw->commit();
399 if ($affected)
400 $this->doRetroactiveAutoblock();
402 return $affected;
406 * Retroactively autoblocks the last IP used by the user (if it is a user)
407 * blocked by this Block.
408 *@return Whether or not a retroactive autoblock was made.
410 function doRetroactiveAutoblock() {
411 $dbr = wfGetDB( DB_SLAVE );
412 #If autoblock is enabled, autoblock the LAST IP used
413 # - stolen shamelessly from CheckUser_body.php
415 if ($this->mEnableAutoblock && $this->mUser) {
416 wfDebug("Doing retroactive autoblocks for " . $this->mAddress . "\n");
418 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress ),
419 __METHOD__ , array( 'ORDER BY' => 'rc_timestamp DESC' ) );
421 if ( !$row || !$row->rc_ip ) {
422 #No results, don't autoblock anything
423 wfDebug("No IP found to retroactively autoblock\n");
424 } else {
425 #Limit is 1, so no loop needed.
426 $retroblockip = $row->rc_ip;
427 return $this->doAutoblock($retroblockip);
433 * Autoblocks the given IP, referring to this Block.
434 * @param $autoblockip The IP to autoblock.
435 * @return bool Whether or not an autoblock was inserted.
437 function doAutoblock( $autoblockip ) {
438 # Check if this IP address is already blocked
439 $dbw =& wfGetDB( DB_MASTER );
440 $dbw->begin();
442 # If autoblocks are disabled, go away.
443 if ( !$this->mEnableAutoblock ) {
444 return;
447 # Check for presence on the autoblock whitelist
448 # TODO cache this?
449 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
451 $ip = $autoblockip;
453 wfDebug("Checking the autoblock whitelist..\n");
455 foreach( $lines as $line ) {
456 # List items only
457 if ( substr( $line, 0, 1 ) !== '*' ) {
458 continue;
461 $wlEntry = substr($line, 1);
462 $wlEntry = trim($wlEntry);
464 wfDebug("Checking $ip against $wlEntry...");
466 # Is the IP in this range?
467 if (IP::isInRange( $ip, $wlEntry )) {
468 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
469 #$autoblockip = null; # Don't autoblock a whitelisted IP.
470 return; #This /SHOULD/ introduce a dummy block - but
471 # I don't know a safe way to do so. -werdna
472 } else {
473 wfDebug( " No match\n" );
477 # It's okay to autoblock. Go ahead and create/insert the block.
479 $ipblock = Block::newFromDB( $autoblockip );
480 if ( $ipblock ) {
481 # If the user is already blocked. Then check if the autoblock would
482 # exceed the user block. If it would exceed, then do nothing, else
483 # prolong block time
484 if ($this->mExpiry &&
485 ($this->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
486 return;
488 # Just update the timestamp
489 $ipblock->updateTimestamp();
490 return;
491 } else {
492 $ipblock = new Block;
495 # Make a new block object with the desired properties
496 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
497 $ipblock->mAddress = $autoblockip;
498 $ipblock->mUser = 0;
499 $ipblock->mBy = $this->mBy;
500 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
501 $ipblock->mTimestamp = wfTimestampNow();
502 $ipblock->mAuto = 1;
503 $ipblock->mCreateAccount = $this->mCreateAccount;
505 # If the user is already blocked with an expiry date, we don't
506 # want to pile on top of that!
507 if($this->mExpiry) {
508 $ipblock->mExpiry = min ( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ));
509 } else {
510 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
512 # Insert it
513 return $ipblock->insert();
516 function deleteIfExpired()
518 $fname = 'Block::deleteIfExpired';
519 wfProfileIn( $fname );
520 if ( $this->isExpired() ) {
521 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
522 $this->delete();
523 $retVal = true;
524 } else {
525 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
526 $retVal = false;
528 wfProfileOut( $fname );
529 return $retVal;
532 function isExpired()
534 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
535 if ( !$this->mExpiry ) {
536 return false;
537 } else {
538 return wfTimestampNow() > $this->mExpiry;
542 function isValid()
544 return $this->mAddress != '';
547 function updateTimestamp()
549 if ( $this->mAuto ) {
550 $this->mTimestamp = wfTimestamp();
551 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
553 $dbw =& wfGetDB( DB_MASTER );
554 $dbw->update( 'ipblocks',
555 array( /* SET */
556 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
557 'ipb_expiry' => $dbw->timestamp($this->mExpiry),
558 ), array( /* WHERE */
559 'ipb_address' => $this->mAddress
560 ), 'Block::updateTimestamp'
566 function getIntegerAddr()
568 return $this->mIntegerAddr;
571 function getNetworkBits()
573 return $this->mNetworkBits;
577 * @return The blocker user ID.
579 public function getBy() {
580 return $this->mBy;
584 * @return The blocker user name.
586 function getByName()
588 if ( $this->mByName === false ) {
589 $this->mByName = User::whoIs( $this->mBy );
591 return $this->mByName;
594 function forUpdate( $x = NULL ) {
595 return wfSetVar( $this->mForUpdate, $x );
598 function fromMaster( $x = NULL ) {
599 return wfSetVar( $this->mFromMaster, $x );
602 function getRedactedName() {
603 if ( $this->mAuto ) {
604 return '#' . $this->mId;
605 } else {
606 return $this->mAddress;
611 * Encode expiry for DB
613 static function encodeExpiry( $expiry, $db ) {
614 if ( $expiry == '' || $expiry == Block::infinity() ) {
615 return Block::infinity();
616 } else {
617 return $db->timestamp( $expiry );
621 /**
622 * Decode expiry which has come from the DB
624 static function decodeExpiry( $expiry ) {
625 if ( $expiry == '' || $expiry == Block::infinity() ) {
626 return Block::infinity();
627 } else {
628 return wfTimestamp( TS_MW, $expiry );
632 static function getAutoblockExpiry( $timestamp )
634 global $wgAutoblockExpiry;
635 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
638 static function normaliseRange( $range )
640 $parts = explode( '/', $range );
641 if ( count( $parts ) == 2 ) {
642 $shift = 32 - $parts[1];
643 $ipint = IP::toUnsigned( $parts[0] );
644 $ipint = $ipint >> $shift << $shift;
645 $newip = long2ip( $ipint );
646 $range = "$newip/{$parts[1]}";
648 return $range;
651 /**
652 * Purge expired blocks from the ipblocks table
654 static function purgeExpired() {
655 $dbw =& wfGetDB( DB_MASTER );
656 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
659 static function infinity() {
660 # This is a special keyword for timestamps in PostgreSQL, and
661 # works with CHAR(14) as well because "i" sorts after all numbers.
662 return 'infinity';
665 static $infinity;
666 if ( !isset( $infinity ) ) {
667 $dbr =& wfGetDB( DB_SLAVE );
668 $infinity = $dbr->bigTimestamp();
670 return $infinity;