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