* (bug 12999) introduce ipb_by_text colomn
[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, $mByName;
20 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster;
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 = $row->ipb_by_text;
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 if( !$this->mByName ) {
380 if( $this->mBy ) {
381 $this->mByName = User::whoIs( $this->mBy );
382 } else {
383 global $wgUser;
384 $this->mByName = $wgUser->getName();
385 }
386 }
387
388 # Don't collide with expired blocks
389 Block::purgeExpired();
390
391 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
392 $dbw->insert( 'ipblocks',
393 array(
394 'ipb_id' => $ipb_id,
395 'ipb_address' => $this->mAddress,
396 'ipb_user' => $this->mUser,
397 'ipb_by' => $this->mBy,
398 'ipb_by_text' => $this->mByName,
399 'ipb_reason' => $this->mReason,
400 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
401 'ipb_auto' => $this->mAuto,
402 'ipb_anon_only' => $this->mAnonOnly,
403 'ipb_create_account' => $this->mCreateAccount,
404 'ipb_enable_autoblock' => $this->mEnableAutoblock,
405 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
406 'ipb_range_start' => $this->mRangeStart,
407 'ipb_range_end' => $this->mRangeEnd,
408 'ipb_deleted' => $this->mHideName,
409 'ipb_block_email' => $this->mBlockEmail
410 ), 'Block::insert', array( 'IGNORE' )
411 );
412 $affected = $dbw->affectedRows();
413 $dbw->commit();
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 }
709