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