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