Revert Special:Log to r20745 with non-ugly form
[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 == 0 ) ) {
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 # Check if this IP address is already blocked
442 $dbw = wfGetDB( DB_MASTER );
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 if ( !$justInserted ) {
492 $ipblock->updateTimestamp();
493 }
494 return;
495 } else {
496 $ipblock = new Block;
497 }
498
499 # Make a new block object with the desired properties
500 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
501 $ipblock->mAddress = $autoblockip;
502 $ipblock->mUser = 0;
503 $ipblock->mBy = $this->mBy;
504 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
505 $ipblock->mTimestamp = wfTimestampNow();
506 $ipblock->mAuto = 1;
507 $ipblock->mCreateAccount = $this->mCreateAccount;
508 # Continue suppressing the name if needed
509 $ipblock->mHideName = $this->mHideName;
510
511 # If the user is already blocked with an expiry date, we don't
512 # want to pile on top of that!
513 if($this->mExpiry) {
514 $ipblock->mExpiry = min ( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ));
515 } else {
516 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
517 }
518 # Insert it
519 return $ipblock->insert();
520 }
521
522 function deleteIfExpired()
523 {
524 $fname = 'Block::deleteIfExpired';
525 wfProfileIn( $fname );
526 if ( $this->isExpired() ) {
527 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
528 $this->delete();
529 $retVal = true;
530 } else {
531 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
532 $retVal = false;
533 }
534 wfProfileOut( $fname );
535 return $retVal;
536 }
537
538 function isExpired()
539 {
540 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
541 if ( !$this->mExpiry ) {
542 return false;
543 } else {
544 return wfTimestampNow() > $this->mExpiry;
545 }
546 }
547
548 function isValid()
549 {
550 return $this->mAddress != '';
551 }
552
553 function updateTimestamp()
554 {
555 if ( $this->mAuto ) {
556 $this->mTimestamp = wfTimestamp();
557 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
558
559 $dbw = wfGetDB( DB_MASTER );
560 $dbw->update( 'ipblocks',
561 array( /* SET */
562 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
563 'ipb_expiry' => $dbw->timestamp($this->mExpiry),
564 ), array( /* WHERE */
565 'ipb_address' => $this->mAddress
566 ), 'Block::updateTimestamp'
567 );
568 }
569 }
570
571 /*
572 function getIntegerAddr()
573 {
574 return $this->mIntegerAddr;
575 }
576
577 function getNetworkBits()
578 {
579 return $this->mNetworkBits;
580 }*/
581
582 /**
583 * @return The blocker user ID.
584 */
585 public function getBy() {
586 return $this->mBy;
587 }
588
589 /**
590 * @return The blocker user name.
591 */
592 function getByName()
593 {
594 if ( $this->mByName === false ) {
595 $this->mByName = User::whoIs( $this->mBy );
596 }
597 return $this->mByName;
598 }
599
600 function forUpdate( $x = NULL ) {
601 return wfSetVar( $this->mForUpdate, $x );
602 }
603
604 function fromMaster( $x = NULL ) {
605 return wfSetVar( $this->mFromMaster, $x );
606 }
607
608 function getRedactedName() {
609 if ( $this->mAuto ) {
610 return '#' . $this->mId;
611 } else {
612 return $this->mAddress;
613 }
614 }
615
616 /**
617 * Encode expiry for DB
618 */
619 static function encodeExpiry( $expiry, $db ) {
620 if ( $expiry == '' || $expiry == Block::infinity() ) {
621 return Block::infinity();
622 } else {
623 return $db->timestamp( $expiry );
624 }
625 }
626
627 /**
628 * Decode expiry which has come from the DB
629 */
630 static function decodeExpiry( $expiry ) {
631 if ( $expiry == '' || $expiry == Block::infinity() ) {
632 return Block::infinity();
633 } else {
634 return wfTimestamp( TS_MW, $expiry );
635 }
636 }
637
638 static function getAutoblockExpiry( $timestamp )
639 {
640 global $wgAutoblockExpiry;
641 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
642 }
643
644 /**
645 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
646 * For example, 127.111.113.151/24 -> 127.111.113.0/24
647 */
648 static function normaliseRange( $range ) {
649 $parts = explode( '/', $range );
650 if ( count( $parts ) == 2 ) {
651 // IPv6
652 if ( IP::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
653 $bits = $parts[1];
654 $ipint = IP::toUnsigned6( $parts[0] );
655 # Native 32 bit functions WONT work here!!!
656 # Convert to a padded binary number
657 $network = wfBaseConvert( $ipint, 10, 2, 128 );
658 # Truncate the last (128-$bits) bits and replace them with zeros
659 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
660 # Convert back to an integer
661 $network = wfBaseConvert( $network, 2, 10 );
662 # Reform octet address
663 $newip = IP::toOctet( $network );
664 $range = "$newip/{$parts[1]}";
665 } // IPv4
666 else if ( IP::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
667 $shift = 32 - $parts[1];
668 $ipint = IP::toUnsigned( $parts[0] );
669 $ipint = $ipint >> $shift << $shift;
670 $newip = long2ip( $ipint );
671 $range = "$newip/{$parts[1]}";
672 }
673 }
674 return $range;
675 }
676
677 /**
678 * Purge expired blocks from the ipblocks table
679 */
680 static function purgeExpired() {
681 $dbw = wfGetDB( DB_MASTER );
682 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
683 }
684
685 static function infinity() {
686 # This is a special keyword for timestamps in PostgreSQL, and
687 # works with CHAR(14) as well because "i" sorts after all numbers.
688 return 'infinity';
689
690 /*
691 static $infinity;
692 if ( !isset( $infinity ) ) {
693 $dbr = wfGetDB( DB_SLAVE );
694 $infinity = $dbr->bigTimestamp();
695 }
696 return $infinity;
697 */
698 }
699
700 }
701 ?>