Ajax show editors message moved to the extension repository (r19556)
[mediawiki.git] / includes / Block.php
blob5645ed3c1d129281942ea3a8599491de08923a61
1 <?php
2 /**
3 * Blocks and bans object
4 */
6 /**
7 * The block class
8 * All the functions in this class assume the object is either explicitly
9 * loaded or filled. It is not load-on-demand. There are no accessors.
11 * Globals used: $wgAutoblockExpiry, $wgAntiLockFlags
13 * @todo This could be used everywhere, but it isn't.
15 class Block
17 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
18 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock;
19 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster, $mByName;
21 const EB_KEEP_EXPIRED = 1;
22 const EB_FOR_UPDATE = 2;
23 const EB_RANGE_ONLY = 4;
25 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
26 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0 )
28 $this->mId = 0;
29 $this->mAddress = $address;
30 $this->mUser = $user;
31 $this->mBy = $by;
32 $this->mReason = $reason;
33 $this->mTimestamp = wfTimestamp(TS_MW,$timestamp);
34 $this->mAuto = $auto;
35 $this->mAnonOnly = $anonOnly;
36 $this->mCreateAccount = $createAccount;
37 $this->mExpiry = self::decodeExpiry( $expiry );
38 $this->mEnableAutoblock = $enableAutoblock;
40 $this->mForUpdate = false;
41 $this->mFromMaster = false;
42 $this->mByName = false;
43 $this->initialiseRange();
46 static function newFromDB( $address, $user = 0, $killExpired = true )
48 $block = new Block();
49 $block->load( $address, $user, $killExpired );
50 if ( $block->isValid() ) {
51 return $block;
52 } else {
53 return null;
57 static function newFromID( $id )
59 $dbr =& wfGetDB( DB_SLAVE );
60 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
61 array( 'ipb_id' => $id ), __METHOD__ ) );
62 $block = new Block;
63 if ( $block->loadFromResult( $res ) ) {
64 return $block;
65 } else {
66 return null;
70 function clear()
72 $this->mAddress = $this->mReason = $this->mTimestamp = '';
73 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
74 $this->mEnableAutoblock = $this->mAuto = $this->mUser =
75 $this->mBy = 0;
76 $this->mByName = false;
79 /**
80 * Get the DB object and set the reference parameter to the query options
82 function &getDBOptions( &$options )
84 global $wgAntiLockFlags;
85 if ( $this->mForUpdate || $this->mFromMaster ) {
86 $db =& wfGetDB( DB_MASTER );
87 if ( !$this->mForUpdate || ($wgAntiLockFlags & ALF_NO_BLOCK_LOCK) ) {
88 $options = array();
89 } else {
90 $options = array( 'FOR UPDATE' );
92 } else {
93 $db =& wfGetDB( DB_SLAVE );
94 $options = array();
96 return $db;
99 /**
100 * Get a ban from the DB, with either the given address or the given username
102 * @param string $address The IP address of the user, or blank to skip IP blocks
103 * @param integer $user The user ID, or zero for anonymous users
104 * @param bool $killExpired Whether to delete expired rows while loading
107 function load( $address = '', $user = 0, $killExpired = true )
109 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
111 $options = array();
112 $db =& $this->getDBOptions( $options );
114 if ( 0 == $user && $address == '' ) {
115 # Invalid user specification, not blocked
116 $this->clear();
117 return false;
120 # Try user block
121 if ( $user ) {
122 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
123 __METHOD__, $options ) );
124 if ( $this->loadFromResult( $res, $killExpired ) ) {
125 return true;
129 # Try IP block
130 # TODO: improve performance by merging this query with the autoblock one
131 # Slightly tricky while handling killExpired as well
132 if ( $address ) {
133 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
134 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
135 if ( $this->loadFromResult( $res, $killExpired ) ) {
136 if ( $user && $this->mAnonOnly ) {
137 # Block is marked anon-only
138 # Whitelist this IP address against autoblocks and range blocks
139 $this->clear();
140 return false;
141 } else {
142 return true;
147 # Try range block
148 if ( $this->loadRange( $address, $killExpired, $user == 0 ) ) {
149 if ( $user && $this->mAnonOnly ) {
150 $this->clear();
151 return false;
152 } else {
153 return true;
157 # Try autoblock
158 if ( $address ) {
159 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
160 if ( $user ) {
161 $conds['ipb_anon_only'] = 0;
163 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
164 if ( $this->loadFromResult( $res, $killExpired ) ) {
165 return true;
169 # Give up
170 $this->clear();
171 return false;
175 * Fill in member variables from a result wrapper
177 function loadFromResult( ResultWrapper $res, $killExpired = true ) {
178 $ret = false;
179 if ( 0 != $res->numRows() ) {
180 # Get first block
181 $row = $res->fetchObject();
182 $this->initFromRow( $row );
184 if ( $killExpired ) {
185 # If requested, delete expired rows
186 do {
187 $killed = $this->deleteIfExpired();
188 if ( $killed ) {
189 $row = $res->fetchObject();
190 if ( $row ) {
191 $this->initFromRow( $row );
194 } while ( $killed && $row );
196 # If there were any left after the killing finished, return true
197 if ( $row ) {
198 $ret = true;
200 } else {
201 $ret = true;
204 $res->free();
205 return $ret;
209 * Search the database for any range blocks matching the given address, and
210 * load the row if one is found.
212 function loadRange( $address, $killExpired = true )
214 $iaddr = IP::toHex( $address );
215 if ( $iaddr === false ) {
216 # Invalid address
217 return false;
220 # Only scan ranges which start in this /16, this improves search speed
221 # Blocks should not cross a /16 boundary.
222 $range = substr( $iaddr, 0, 4 );
224 $options = array();
225 $db =& $this->getDBOptions( $options );
226 $conds = array(
227 "ipb_range_start LIKE '$range%'",
228 "ipb_range_start <= '$iaddr'",
229 "ipb_range_end >= '$iaddr'"
232 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
233 $success = $this->loadFromResult( $res, $killExpired );
234 return $success;
238 * Determine if a given integer IPv4 address is in a given CIDR network
239 * @deprecated Use IP::isInRange
241 function isAddressInRange( $addr, $range ) {
242 return IP::isInRange( $addr, $range );
245 function initFromRow( $row )
247 $this->mAddress = $row->ipb_address;
248 $this->mReason = $row->ipb_reason;
249 $this->mTimestamp = wfTimestamp(TS_MW,$row->ipb_timestamp);
250 $this->mUser = $row->ipb_user;
251 $this->mBy = $row->ipb_by;
252 $this->mAuto = $row->ipb_auto;
253 $this->mAnonOnly = $row->ipb_anon_only;
254 $this->mCreateAccount = $row->ipb_create_account;
255 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
256 $this->mId = $row->ipb_id;
257 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
258 if ( isset( $row->user_name ) ) {
259 $this->mByName = $row->user_name;
260 } else {
261 $this->mByName = false;
263 $this->mRangeStart = $row->ipb_range_start;
264 $this->mRangeEnd = $row->ipb_range_end;
267 function initialiseRange()
269 $this->mRangeStart = '';
270 $this->mRangeEnd = '';
272 if ( $this->mUser == 0 ) {
273 list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress );
278 * Callback with a Block object for every block
279 * @return integer number of blocks;
281 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
283 global $wgAntiLockFlags;
285 $block = new Block();
286 if ( $flags & Block::EB_FOR_UPDATE ) {
287 $db =& wfGetDB( DB_MASTER );
288 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK ) {
289 $options = '';
290 } else {
291 $options = 'FOR UPDATE';
293 $block->forUpdate( true );
294 } else {
295 $db =& wfGetDB( DB_SLAVE );
296 $options = '';
298 if ( $flags & Block::EB_RANGE_ONLY ) {
299 $cond = " AND ipb_range_start <> ''";
300 } else {
301 $cond = '';
304 $now = wfTimestampNow();
306 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
308 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
309 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
310 $res = $db->query( $sql, 'Block::enumBlocks' );
311 $num_rows = $db->numRows( $res );
313 while ( $row = $db->fetchObject( $res ) ) {
314 $block->initFromRow( $row );
315 if ( ( $flags & Block::EB_RANGE_ONLY ) && $block->mRangeStart == '' ) {
316 continue;
319 if ( !( $flags & Block::EB_KEEP_EXPIRED ) ) {
320 if ( $block->mExpiry && $now > $block->mExpiry ) {
321 $block->delete();
322 } else {
323 call_user_func( $callback, $block, $tag );
325 } else {
326 call_user_func( $callback, $block, $tag );
329 $db->freeResult( $res );
330 return $num_rows;
333 function delete()
335 if (wfReadOnly()) {
336 return false;
338 if ( !$this->mId ) {
339 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
342 $dbw =& wfGetDB( DB_MASTER );
343 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
344 return $dbw->affectedRows() > 0;
348 * Insert a block into the block table.
349 *@return Whether or not the insertion was successful.
351 function insert()
353 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
354 $dbw =& wfGetDB( DB_MASTER );
355 $dbw->begin();
357 # Unset ipb_anon_only for user blocks, makes no sense
358 if ( $this->mUser ) {
359 $this->mAnonOnly = 0;
362 # Unset ipb_enable_autoblock for IP blocks, makes no sense
363 if ( !$this->mUser ) {
364 $this->mEnableAutoblock = 0;
367 # Don't collide with expired blocks
368 Block::purgeExpired();
370 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
371 $dbw->insert( 'ipblocks',
372 array(
373 'ipb_id' => $ipb_id,
374 'ipb_address' => $this->mAddress,
375 'ipb_user' => $this->mUser,
376 'ipb_by' => $this->mBy,
377 'ipb_reason' => $this->mReason,
378 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
379 'ipb_auto' => $this->mAuto,
380 'ipb_anon_only' => $this->mAnonOnly,
381 'ipb_create_account' => $this->mCreateAccount,
382 'ipb_enable_autoblock' => $this->mEnableAutoblock,
383 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
384 'ipb_range_start' => $this->mRangeStart,
385 'ipb_range_end' => $this->mRangeEnd,
386 ), 'Block::insert', array( 'IGNORE' )
388 $affected = $dbw->affectedRows();
389 $dbw->commit();
391 if ($affected)
392 $this->doRetroactiveAutoblock();
394 return $affected;
398 * Retroactively autoblocks the last IP used by the user (if it is a user)
399 * blocked by this Block.
400 *@return Whether or not a retroactive autoblock was made.
402 function doRetroactiveAutoblock() {
403 $dbr = wfGetDB( DB_SLAVE );
404 #If autoblock is enabled, autoblock the LAST IP used
405 # - stolen shamelessly from CheckUser_body.php
407 if ($this->mEnableAutoblock && $this->mUser) {
408 wfDebug("Doing retroactive autoblocks for " . $this->mAddress . "\n");
410 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress ),
411 __METHOD__ , array( 'ORDER BY' => 'rc_timestamp DESC' ) );
413 if ( !$row || !$row->rc_ip ) {
414 #No results, don't autoblock anything
415 wfDebug("No IP found to retroactively autoblock\n");
416 } else {
417 #Limit is 1, so no loop needed.
418 $retroblockip = $row->rc_ip;
419 return $this->doAutoblock($retroblockip);
425 * Autoblocks the given IP, referring to this Block.
426 * @param $autoblockip The IP to autoblock.
427 * @return bool Whether or not an autoblock was inserted.
429 function doAutoblock( $autoblockip ) {
430 # Check if this IP address is already blocked
431 $dbw =& wfGetDB( DB_MASTER );
432 $dbw->begin();
434 # If autoblocks are disabled, go away.
435 if ( !$this->mEnableAutoblock ) {
436 return;
439 # Check for presence on the autoblock whitelist
440 # TODO cache this?
441 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
443 $ip = $autoblockip;
445 wfDebug("Checking the autoblock whitelist..\n");
447 foreach( $lines as $line ) {
448 # List items only
449 if ( substr( $line, 0, 1 ) !== '*' ) {
450 continue;
453 $wlEntry = substr($line, 1);
454 $wlEntry = trim($wlEntry);
456 wfDebug("Checking $ip against $wlEntry...");
458 # Is the IP in this range?
459 if (IP::isInRange( $ip, $wlEntry )) {
460 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
461 #$autoblockip = null; # Don't autoblock a whitelisted IP.
462 return; #This /SHOULD/ introduce a dummy block - but
463 # I don't know a safe way to do so. -werdna
464 } else {
465 wfDebug( " No match\n" );
469 # It's okay to autoblock. Go ahead and create/insert the block.
471 $ipblock = Block::newFromDB( $autoblockip );
472 if ( $ipblock ) {
473 # If the user is already blocked. Then check if the autoblock would
474 # exceed the user block. If it would exceed, then do nothing, else
475 # prolong block time
476 if ($this->mExpiry &&
477 ($this->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
478 return;
480 # Just update the timestamp
481 $ipblock->updateTimestamp();
482 return;
483 } else {
484 $ipblock = new Block;
487 # Make a new block object with the desired properties
488 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
489 $ipblock->mAddress = $autoblockip;
490 $ipblock->mUser = 0;
491 $ipblock->mBy = $this->mBy;
492 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
493 $ipblock->mTimestamp = wfTimestampNow();
494 $ipblock->mAuto = 1;
495 $ipblock->mCreateAccount = $this->mCreateAccount;
497 # If the user is already blocked with an expiry date, we don't
498 # want to pile on top of that!
499 if($this->mExpiry) {
500 $ipblock->mExpiry = min ( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ));
501 } else {
502 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
504 # Insert it
505 return $ipblock->insert();
508 function deleteIfExpired()
510 $fname = 'Block::deleteIfExpired';
511 wfProfileIn( $fname );
512 if ( $this->isExpired() ) {
513 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
514 $this->delete();
515 $retVal = true;
516 } else {
517 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
518 $retVal = false;
520 wfProfileOut( $fname );
521 return $retVal;
524 function isExpired()
526 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
527 if ( !$this->mExpiry ) {
528 return false;
529 } else {
530 return wfTimestampNow() > $this->mExpiry;
534 function isValid()
536 return $this->mAddress != '';
539 function updateTimestamp()
541 if ( $this->mAuto ) {
542 $this->mTimestamp = wfTimestamp();
543 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
545 $dbw =& wfGetDB( DB_MASTER );
546 $dbw->update( 'ipblocks',
547 array( /* SET */
548 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
549 'ipb_expiry' => $dbw->timestamp($this->mExpiry),
550 ), array( /* WHERE */
551 'ipb_address' => $this->mAddress
552 ), 'Block::updateTimestamp'
558 function getIntegerAddr()
560 return $this->mIntegerAddr;
563 function getNetworkBits()
565 return $this->mNetworkBits;
569 * @return The blocker user ID.
571 public function getBy() {
572 return $this->mBy;
576 * @return The blocker user name.
578 function getByName()
580 if ( $this->mByName === false ) {
581 $this->mByName = User::whoIs( $this->mBy );
583 return $this->mByName;
586 function forUpdate( $x = NULL ) {
587 return wfSetVar( $this->mForUpdate, $x );
590 function fromMaster( $x = NULL ) {
591 return wfSetVar( $this->mFromMaster, $x );
594 function getRedactedName() {
595 if ( $this->mAuto ) {
596 return '#' . $this->mId;
597 } else {
598 return $this->mAddress;
603 * Encode expiry for DB
605 static function encodeExpiry( $expiry, $db ) {
606 if ( $expiry == '' || $expiry == Block::infinity() ) {
607 return Block::infinity();
608 } else {
609 return $db->timestamp( $expiry );
613 /**
614 * Decode expiry which has come from the DB
616 static function decodeExpiry( $expiry ) {
617 if ( $expiry == '' || $expiry == Block::infinity() ) {
618 return Block::infinity();
619 } else {
620 return wfTimestamp( TS_MW, $expiry );
624 static function getAutoblockExpiry( $timestamp )
626 global $wgAutoblockExpiry;
627 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
630 static function normaliseRange( $range )
632 $parts = explode( '/', $range );
633 if ( count( $parts ) == 2 ) {
634 $shift = 32 - $parts[1];
635 $ipint = IP::toUnsigned( $parts[0] );
636 $ipint = $ipint >> $shift << $shift;
637 $newip = long2ip( $ipint );
638 $range = "$newip/{$parts[1]}";
640 return $range;
643 /**
644 * Purge expired blocks from the ipblocks table
646 static function purgeExpired() {
647 $dbw =& wfGetDB( DB_MASTER );
648 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
651 static function infinity() {
652 # This is a special keyword for timestamps in PostgreSQL, and
653 # works with CHAR(14) as well because "i" sorts after all numbers.
654 return 'infinity';
657 static $infinity;
658 if ( !isset( $infinity ) ) {
659 $dbr =& wfGetDB( DB_SLAVE );
660 $infinity = $dbr->bigTimestamp();
662 return $infinity;