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