*IPv6 sanitizing, avoid use of native hex functions, enlarge ip box for blockip a bit
[lhc/web/wiklou.git] / includes / Block.php
1 <?php
2 /**
3 * Blocks and bans object
4 */
5
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.
10 *
11 * Globals used: $wgAutoblockExpiry, $wgAntiLockFlags
12 *
13 * @todo This could be used everywhere, but it isn't.
14 */
15 class Block
16 {
17 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
18 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock;
19 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster, $mByName;
20
21 const EB_KEEP_EXPIRED = 1;
22 const EB_FOR_UPDATE = 2;
23 const EB_RANGE_ONLY = 4;
24
25 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
26 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0 )
27 {
28 $this->mId = 0;
29 # Expand valid IPv6 addresses
30 $address = IP::sanitizeIP( $address );
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;
41
42 $this->mForUpdate = false;
43 $this->mFromMaster = false;
44 $this->mByName = false;
45 $this->initialiseRange();
46 }
47
48 static function newFromDB( $address, $user = 0, $killExpired = true )
49 {
50 $block = new Block();
51 $block->load( $address, $user, $killExpired );
52 if ( $block->isValid() ) {
53 return $block;
54 } else {
55 return null;
56 }
57 }
58
59 static function newFromID( $id )
60 {
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;
69 }
70 }
71
72 function clear()
73 {
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;
79 }
80
81 /**
82 * Get the DB object and set the reference parameter to the query options
83 */
84 function &getDBOptions( &$options )
85 {
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' );
93 }
94 } else {
95 $db = wfGetDB( DB_SLAVE );
96 $options = array();
97 }
98 return $db;
99 }
100
101 /**
102 * Get a ban from the DB, with either the given address or the given username
103 *
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
107 *
108 */
109 function load( $address = '', $user = 0, $killExpired = true )
110 {
111 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
112
113 $options = array();
114 $db =& $this->getDBOptions( $options );
115
116 if ( 0 == $user && $address == '' ) {
117 # Invalid user specification, not blocked
118 $this->clear();
119 return false;
120 }
121
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;
128 }
129 }
130
131 # Try IP block
132 # TODO: improve performance by merging this query with the autoblock one
133 # Slightly tricky while handling killExpired as well
134 if ( $address ) {
135 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
136 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
137 if ( $this->loadFromResult( $res, $killExpired ) ) {
138 if ( $user && $this->mAnonOnly ) {
139 # Block is marked anon-only
140 # Whitelist this IP address against autoblocks and range blocks
141 $this->clear();
142 return false;
143 } else {
144 return true;
145 }
146 }
147 }
148
149 # Try range block
150 if ( $this->loadRange( $address, $killExpired, $user == 0 ) ) {
151 if ( $user && $this->mAnonOnly ) {
152 $this->clear();
153 return false;
154 } else {
155 return true;
156 }
157 }
158
159 # Try autoblock
160 if ( $address ) {
161 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
162 if ( $user ) {
163 $conds['ipb_anon_only'] = 0;
164 }
165 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
166 if ( $this->loadFromResult( $res, $killExpired ) ) {
167 return true;
168 }
169 }
170
171 # Give up
172 $this->clear();
173 return false;
174 }
175
176 /**
177 * Fill in member variables from a result wrapper
178 */
179 function loadFromResult( ResultWrapper $res, $killExpired = true )
180 {
181 $ret = false;
182 if ( 0 != $res->numRows() ) {
183 # Get first block
184 $row = $res->fetchObject();
185 $this->initFromRow( $row );
186
187 if ( $killExpired ) {
188 # If requested, delete expired rows
189 do {
190 $killed = $this->deleteIfExpired();
191 if ( $killed ) {
192 $row = $res->fetchObject();
193 if ( $row ) {
194 $this->initFromRow( $row );
195 }
196 }
197 } while ( $killed && $row );
198
199 # If there were any left after the killing finished, return true
200 if ( $row ) {
201 $ret = true;
202 }
203 } else {
204 $ret = true;
205 }
206 }
207 $res->free();
208 return $ret;
209 }
210
211 /**
212 * Search the database for any range blocks matching the given address, and
213 * load the row if one is found.
214 */
215 function loadRange( $address, $killExpired = true )
216 {
217 $iaddr = IP::toHex( $address );
218 if ( $iaddr === false ) {
219 # Invalid address
220 return false;
221 }
222
223 # Only scan ranges which start in this /16, this improves search speed
224 # Blocks should not cross a /16 boundary.
225 $range = substr( $iaddr, 0, 4 );
226
227 $options = array();
228 $db =& $this->getDBOptions( $options );
229 $conds = array(
230 "ipb_range_start LIKE '$range%'",
231 "ipb_range_start <= '$iaddr'",
232 "ipb_range_end >= '$iaddr'"
233 );
234
235 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
236 $success = $this->loadFromResult( $res, $killExpired );
237 return $success;
238 }
239
240 /**
241 * Determine if a given integer IPv4 address is in a given CIDR network
242 * @deprecated Use IP::isInRange
243 */
244 function isAddressInRange( $addr, $range ) {
245 return IP::isInRange( $addr, $range );
246 }
247
248 function initFromRow( $row )
249 {
250 $this->mAddress = $row->ipb_address;
251 $this->mReason = $row->ipb_reason;
252 $this->mTimestamp = wfTimestamp(TS_MW,$row->ipb_timestamp);
253 $this->mUser = $row->ipb_user;
254 $this->mBy = $row->ipb_by;
255 $this->mAuto = $row->ipb_auto;
256 $this->mAnonOnly = $row->ipb_anon_only;
257 $this->mCreateAccount = $row->ipb_create_account;
258 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
259 $this->mId = $row->ipb_id;
260 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
261 if ( isset( $row->user_name ) ) {
262 $this->mByName = $row->user_name;
263 } else {
264 $this->mByName = false;
265 }
266 $this->mRangeStart = $row->ipb_range_start;
267 $this->mRangeEnd = $row->ipb_range_end;
268 }
269
270 function initialiseRange()
271 {
272 $this->mRangeStart = '';
273 $this->mRangeEnd = '';
274
275 if ( $this->mUser == 0 ) {
276 list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress );
277 }
278 }
279
280 /**
281 * Callback with a Block object for every block
282 * @return integer number of blocks;
283 */
284 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
285 {
286 global $wgAntiLockFlags;
287
288 $block = new Block();
289 if ( $flags & Block::EB_FOR_UPDATE ) {
290 $db = wfGetDB( DB_MASTER );
291 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK ) {
292 $options = '';
293 } else {
294 $options = 'FOR UPDATE';
295 }
296 $block->forUpdate( true );
297 } else {
298 $db = wfGetDB( DB_SLAVE );
299 $options = '';
300 }
301 if ( $flags & Block::EB_RANGE_ONLY ) {
302 $cond = " AND ipb_range_start <> ''";
303 } else {
304 $cond = '';
305 }
306
307 $now = wfTimestampNow();
308
309 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
310
311 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
312 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
313 $res = $db->query( $sql, 'Block::enumBlocks' );
314 $num_rows = $db->numRows( $res );
315
316 while ( $row = $db->fetchObject( $res ) ) {
317 $block->initFromRow( $row );
318 if ( ( $flags & Block::EB_RANGE_ONLY ) && $block->mRangeStart == '' ) {
319 continue;
320 }
321
322 if ( !( $flags & Block::EB_KEEP_EXPIRED ) ) {
323 if ( $block->mExpiry && $now > $block->mExpiry ) {
324 $block->delete();
325 } else {
326 call_user_func( $callback, $block, $tag );
327 }
328 } else {
329 call_user_func( $callback, $block, $tag );
330 }
331 }
332 $db->freeResult( $res );
333 return $num_rows;
334 }
335
336 function delete()
337 {
338 if (wfReadOnly()) {
339 return false;
340 }
341 if ( !$this->mId ) {
342 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
343 }
344
345 $dbw = wfGetDB( DB_MASTER );
346 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
347 return $dbw->affectedRows() > 0;
348 }
349
350 /**
351 * Insert a block into the block table.
352 *@return Whether or not the insertion was successful.
353 */
354 function insert()
355 {
356 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
357 $dbw = wfGetDB( DB_MASTER );
358 $dbw->begin();
359
360 # Unset ipb_anon_only for user blocks, makes no sense
361 if ( $this->mUser ) {
362 $this->mAnonOnly = 0;
363 }
364
365 # Unset ipb_enable_autoblock for IP blocks, makes no sense
366 if ( !$this->mUser ) {
367 $this->mEnableAutoblock = 0;
368 }
369
370 # Don't collide with expired blocks
371 Block::purgeExpired();
372
373 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
374 $dbw->insert( 'ipblocks',
375 array(
376 'ipb_id' => $ipb_id,
377 'ipb_address' => $this->mAddress,
378 'ipb_user' => $this->mUser,
379 'ipb_by' => $this->mBy,
380 'ipb_reason' => $this->mReason,
381 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
382 'ipb_auto' => $this->mAuto,
383 'ipb_anon_only' => $this->mAnonOnly,
384 'ipb_create_account' => $this->mCreateAccount,
385 'ipb_enable_autoblock' => $this->mEnableAutoblock,
386 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
387 'ipb_range_start' => $this->mRangeStart,
388 'ipb_range_end' => $this->mRangeEnd,
389 ), 'Block::insert', array( 'IGNORE' )
390 );
391 $affected = $dbw->affectedRows();
392 $dbw->commit();
393
394 if ($affected)
395 $this->doRetroactiveAutoblock();
396
397 return $affected;
398 }
399
400 /**
401 * Retroactively autoblocks the last IP used by the user (if it is a user)
402 * blocked by this Block.
403 *@return Whether or not a retroactive autoblock was made.
404 */
405 function doRetroactiveAutoblock() {
406 $dbr = wfGetDB( DB_SLAVE );
407 #If autoblock is enabled, autoblock the LAST IP used
408 # - stolen shamelessly from CheckUser_body.php
409
410 if ($this->mEnableAutoblock && $this->mUser) {
411 wfDebug("Doing retroactive autoblocks for " . $this->mAddress . "\n");
412
413 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress ),
414 __METHOD__ , array( 'ORDER BY' => 'rc_timestamp DESC' ) );
415
416 if ( !$row || !$row->rc_ip ) {
417 #No results, don't autoblock anything
418 wfDebug("No IP found to retroactively autoblock\n");
419 } else {
420 #Limit is 1, so no loop needed.
421 $retroblockip = $row->rc_ip;
422 return $this->doAutoblock($retroblockip);
423 }
424 }
425 }
426
427 /**
428 * Autoblocks the given IP, referring to this Block.
429 * @param $autoblockip The IP to autoblock.
430 * @return bool Whether or not an autoblock was inserted.
431 */
432 function doAutoblock( $autoblockip ) {
433 # Check if this IP address is already blocked
434 $dbw = wfGetDB( DB_MASTER );
435 $dbw->begin();
436
437 # If autoblocks are disabled, go away.
438 if ( !$this->mEnableAutoblock ) {
439 return;
440 }
441
442 # Check for presence on the autoblock whitelist
443 # TODO cache this?
444 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
445
446 $ip = $autoblockip;
447
448 wfDebug("Checking the autoblock whitelist..\n");
449
450 foreach( $lines as $line ) {
451 # List items only
452 if ( substr( $line, 0, 1 ) !== '*' ) {
453 continue;
454 }
455
456 $wlEntry = substr($line, 1);
457 $wlEntry = trim($wlEntry);
458
459 wfDebug("Checking $ip against $wlEntry...");
460
461 # Is the IP in this range?
462 if (IP::isInRange( $ip, $wlEntry )) {
463 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
464 #$autoblockip = null; # Don't autoblock a whitelisted IP.
465 return; #This /SHOULD/ introduce a dummy block - but
466 # I don't know a safe way to do so. -werdna
467 } else {
468 wfDebug( " No match\n" );
469 }
470 }
471
472 # It's okay to autoblock. Go ahead and create/insert the block.
473
474 $ipblock = Block::newFromDB( $autoblockip );
475 if ( $ipblock ) {
476 # If the user is already blocked. Then check if the autoblock would
477 # exceed the user block. If it would exceed, then do nothing, else
478 # prolong block time
479 if ($this->mExpiry &&
480 ($this->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
481 return;
482 }
483 # Just update the timestamp
484 $ipblock->updateTimestamp();
485 return;
486 } else {
487 $ipblock = new Block;
488 }
489
490 # Make a new block object with the desired properties
491 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
492 $ipblock->mAddress = $autoblockip;
493 $ipblock->mUser = 0;
494 $ipblock->mBy = $this->mBy;
495 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
496 $ipblock->mTimestamp = wfTimestampNow();
497 $ipblock->mAuto = 1;
498 $ipblock->mCreateAccount = $this->mCreateAccount;
499
500 # If the user is already blocked with an expiry date, we don't
501 # want to pile on top of that!
502 if($this->mExpiry) {
503 $ipblock->mExpiry = min ( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ));
504 } else {
505 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
506 }
507 # Insert it
508 return $ipblock->insert();
509 }
510
511 function deleteIfExpired()
512 {
513 $fname = 'Block::deleteIfExpired';
514 wfProfileIn( $fname );
515 if ( $this->isExpired() ) {
516 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
517 $this->delete();
518 $retVal = true;
519 } else {
520 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
521 $retVal = false;
522 }
523 wfProfileOut( $fname );
524 return $retVal;
525 }
526
527 function isExpired()
528 {
529 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
530 if ( !$this->mExpiry ) {
531 return false;
532 } else {
533 return wfTimestampNow() > $this->mExpiry;
534 }
535 }
536
537 function isValid()
538 {
539 return $this->mAddress != '';
540 }
541
542 function updateTimestamp()
543 {
544 if ( $this->mAuto ) {
545 $this->mTimestamp = wfTimestamp();
546 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
547
548 $dbw = wfGetDB( DB_MASTER );
549 $dbw->update( 'ipblocks',
550 array( /* SET */
551 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
552 'ipb_expiry' => $dbw->timestamp($this->mExpiry),
553 ), array( /* WHERE */
554 'ipb_address' => $this->mAddress
555 ), 'Block::updateTimestamp'
556 );
557 }
558 }
559
560 /*
561 function getIntegerAddr()
562 {
563 return $this->mIntegerAddr;
564 }
565
566 function getNetworkBits()
567 {
568 return $this->mNetworkBits;
569 }*/
570
571 /**
572 * @return The blocker user ID.
573 */
574 public function getBy() {
575 return $this->mBy;
576 }
577
578 /**
579 * @return The blocker user name.
580 */
581 function getByName()
582 {
583 if ( $this->mByName === false ) {
584 $this->mByName = User::whoIs( $this->mBy );
585 }
586 return $this->mByName;
587 }
588
589 function forUpdate( $x = NULL ) {
590 return wfSetVar( $this->mForUpdate, $x );
591 }
592
593 function fromMaster( $x = NULL ) {
594 return wfSetVar( $this->mFromMaster, $x );
595 }
596
597 function getRedactedName() {
598 if ( $this->mAuto ) {
599 return '#' . $this->mId;
600 } else {
601 return $this->mAddress;
602 }
603 }
604
605 /**
606 * Encode expiry for DB
607 */
608 static function encodeExpiry( $expiry, $db ) {
609 if ( $expiry == '' || $expiry == Block::infinity() ) {
610 return Block::infinity();
611 } else {
612 return $db->timestamp( $expiry );
613 }
614 }
615
616 /**
617 * Decode expiry which has come from the DB
618 */
619 static function decodeExpiry( $expiry ) {
620 if ( $expiry == '' || $expiry == Block::infinity() ) {
621 return Block::infinity();
622 } else {
623 return wfTimestamp( TS_MW, $expiry );
624 }
625 }
626
627 static function getAutoblockExpiry( $timestamp )
628 {
629 global $wgAutoblockExpiry;
630 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
631 }
632
633 static function normaliseRange( $range )
634 {
635 $parts = explode( '/', $range );
636 if ( count( $parts ) == 2 ) {
637 $shift = 32 - $parts[1];
638 $ipint = IP::toUnsigned( $parts[0] );
639 $ipint = $ipint >> $shift << $shift;
640 $newip = long2ip( $ipint );
641 $range = "$newip/{$parts[1]}";
642 }
643 return $range;
644 }
645
646 // For IPv6
647 static function normaliseRange6( $range ) {
648 $parts = explode( '/', $range );
649 if ( count( $parts ) == 2 ) {
650 $bits = $parts[1];
651 $ipint = IP::toUnsigned6( $parts[0] );
652 # Native 32 bit functions WONT work here!!!
653 # Convert to a padded binary number
654 $network = wfBaseConvert( $ipint, 10, 2, 128 );
655 # Truncate the last (128-$bits) bits and replace them with zeros
656 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
657 # Convert back to an integer
658 $network = wfBaseConvert( $network, 2, 10 );
659 # Reform octet address
660 $newip = IP::toOctet( $network );
661 $range = "$newip/{$parts[1]}";
662 }
663 return $range;
664 }
665
666 /**
667 * Purge expired blocks from the ipblocks table
668 */
669 static function purgeExpired() {
670 $dbw = wfGetDB( DB_MASTER );
671 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
672 }
673
674 static function infinity() {
675 # This is a special keyword for timestamps in PostgreSQL, and
676 # works with CHAR(14) as well because "i" sorts after all numbers.
677 return 'infinity';
678
679 /*
680 static $infinity;
681 if ( !isset( $infinity ) ) {
682 $dbr = wfGetDB( DB_SLAVE );
683 $infinity = $dbr->bigTimestamp();
684 }
685 return $infinity;
686 */
687 }
688
689 }
690 ?>