Revert last three commits. I totally broke autoblock and didn't notice somehow. :|
[lhc/web/wiklou.git] / includes / Block.php
1 <?php
2 /**
3 * Blocks and bans object
4 * @package MediaWiki
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 * @package MediaWiki
16 */
17 class Block
18 {
19 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
20 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock;
21 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster, $mByName;
22
23 const EB_KEEP_EXPIRED = 1;
24 const EB_FOR_UPDATE = 2;
25 const EB_RANGE_ONLY = 4;
26
27 function Block( $address = '', $user = 0, $by = 0, $reason = '',
28 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0 )
29 {
30 $this->mId = 0;
31 $this->mAddress = $address;
32 $this->mUser = $user;
33 $this->mBy = $by;
34 $this->mReason = $reason;
35 $this->mTimestamp = wfTimestamp(TS_MW,$timestamp);
36 $this->mAuto = $auto;
37 $this->mAnonOnly = $anonOnly;
38 $this->mCreateAccount = $createAccount;
39 $this->mExpiry = self::decodeExpiry( $expiry );
40 $this->mEnableAutoblock = $enableAutoblock;
41
42 $this->mForUpdate = false;
43 $this->mFromMaster = false;
44 $this->mByName = false;
45 $this->initialiseRange();
46 }
47
48 static function newFromDB( $address, $user = 0, $killExpired = true )
49 {
50 $block = new Block();
51 $block->load( $address, $user, $killExpired );
52 if ( $block->isValid() ) {
53 return $block;
54 } else {
55 return null;
56 }
57 }
58
59 static function newFromID( $id )
60 {
61 $dbr =& wfGetDB( DB_SLAVE );
62 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
63 array( 'ipb_id' => $id ), __METHOD__ ) );
64 $block = new Block;
65 if ( $block->loadFromResult( $res ) ) {
66 return $block;
67 } else {
68 return null;
69 }
70 }
71
72 function clear()
73 {
74 $this->mAddress = $this->mReason = $this->mTimestamp = '';
75 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
76 $this->mEnableAutoblock = $this->mAuto = $this->mUser =
77 $this->mBy = 0;
78 $this->mByName = false;
79 }
80
81 /**
82 * Get the DB object and set the reference parameter to the query options
83 */
84 function &getDBOptions( &$options )
85 {
86 global $wgAntiLockFlags;
87 if ( $this->mForUpdate || $this->mFromMaster ) {
88 $db =& wfGetDB( DB_MASTER );
89 if ( !$this->mForUpdate || ($wgAntiLockFlags & ALF_NO_BLOCK_LOCK) ) {
90 $options = array();
91 } else {
92 $options = array( 'FOR UPDATE' );
93 }
94 } else {
95 $db =& wfGetDB( DB_SLAVE );
96 $options = array();
97 }
98 return $db;
99 }
100
101 /**
102 * Get a ban from the DB, with either the given address or the given username
103 *
104 * @param string $address The IP address of the user, or blank to skip IP blocks
105 * @param integer $user The user ID, or zero for anonymous users
106 * @param bool $killExpired Whether to delete expired rows while loading
107 *
108 */
109 function load( $address = '', $user = 0, $killExpired = true )
110 {
111 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
112
113 $options = array();
114 $db =& $this->getDBOptions( $options );
115
116 $ret = false;
117 $killed = false;
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 == 0 ) ) {
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 $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 )
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 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
238 $success = $this->loadFromResult( $res, $killExpired );
239 return $success;
240 }
241
242 /**
243 * Determine if a given integer IPv4 address is in a given CIDR network
244 * @deprecated Use wfIsAddressInRange
245 */
246 function isAddressInRange( $addr, $range ) {
247 return wfIsAddressInRange( $addr, $range );
248 }
249
250 function initFromRow( $row )
251 {
252 $this->mAddress = $row->ipb_address;
253 $this->mReason = $row->ipb_reason;
254 $this->mTimestamp = wfTimestamp(TS_MW,$row->ipb_timestamp);
255 $this->mUser = $row->ipb_user;
256 $this->mBy = $row->ipb_by;
257 $this->mAuto = $row->ipb_auto;
258 $this->mAnonOnly = $row->ipb_anon_only;
259 $this->mCreateAccount = $row->ipb_create_account;
260 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
261 $this->mId = $row->ipb_id;
262 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
263 if ( isset( $row->user_name ) ) {
264 $this->mByName = $row->user_name;
265 } else {
266 $this->mByName = false;
267 }
268 $this->mRangeStart = $row->ipb_range_start;
269 $this->mRangeEnd = $row->ipb_range_end;
270 }
271
272 function initialiseRange()
273 {
274 $this->mRangeStart = '';
275 $this->mRangeEnd = '';
276
277 if ( $this->mUser == 0 ) {
278 $startend = wfRangeStartEnd($this->mAddress);
279 $this->mRangeStart = $startend[0];
280 $this->mRangeEnd = $startend[1];
281 }
282 }
283
284 /**
285 * Callback with a Block object for every block
286 * @return integer number of blocks;
287 */
288 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
289 {
290 global $wgAntiLockFlags;
291
292 $block = new Block();
293 if ( $flags & Block::EB_FOR_UPDATE ) {
294 $db =& wfGetDB( DB_MASTER );
295 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK ) {
296 $options = '';
297 } else {
298 $options = 'FOR UPDATE';
299 }
300 $block->forUpdate( true );
301 } else {
302 $db =& wfGetDB( DB_SLAVE );
303 $options = '';
304 }
305 if ( $flags & Block::EB_RANGE_ONLY ) {
306 $cond = " AND ipb_range_start <> ''";
307 } else {
308 $cond = '';
309 }
310
311 $now = wfTimestampNow();
312
313 extract( $db->tableNames( 'ipblocks', 'user' ) );
314
315 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
316 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
317 $res = $db->query( $sql, 'Block::enumBlocks' );
318 $num_rows = $db->numRows( $res );
319
320 while ( $row = $db->fetchObject( $res ) ) {
321 $block->initFromRow( $row );
322 if ( ( $flags & Block::EB_RANGE_ONLY ) && $block->mRangeStart == '' ) {
323 continue;
324 }
325
326 if ( !( $flags & Block::EB_KEEP_EXPIRED ) ) {
327 if ( $block->mExpiry && $now > $block->mExpiry ) {
328 $block->delete();
329 } else {
330 call_user_func( $callback, $block, $tag );
331 }
332 } else {
333 call_user_func( $callback, $block, $tag );
334 }
335 }
336 $db->freeResult( $res );
337 return $num_rows;
338 }
339
340 function delete()
341 {
342 if (wfReadOnly()) {
343 return false;
344 }
345 if ( !$this->mId ) {
346 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
347 }
348
349 $dbw =& wfGetDB( DB_MASTER );
350 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
351 return $dbw->affectedRows() > 0;
352 }
353
354 /**
355 * Insert a block into the block table.
356 *@return Whether or not the insertion was successful.
357 */
358 function insert()
359 {
360 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
361 $dbw =& wfGetDB( DB_MASTER );
362 $dbw->begin();
363
364 # Unset ipb_anon_only for user blocks, makes no sense
365 if ( $this->mUser ) {
366 $this->mAnonOnly = 0;
367 }
368
369 # Unset ipb_enable_autoblock for IP blocks, makes no sense
370 if ( !$this->mUser ) {
371 $this->mEnableAutoblock = 0;
372 }
373
374 # Don't collide with expired blocks
375 Block::purgeExpired();
376
377 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
378 $dbw->insert( 'ipblocks',
379 array(
380 'ipb_id' => $ipb_id,
381 'ipb_address' => $this->mAddress,
382 'ipb_user' => $this->mUser,
383 'ipb_by' => $this->mBy,
384 'ipb_reason' => $this->mReason,
385 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
386 'ipb_auto' => $this->mAuto,
387 'ipb_anon_only' => $this->mAnonOnly,
388 'ipb_create_account' => $this->mCreateAccount,
389 'ipb_enable_autoblock' => $this->mEnableAutoblock,
390 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
391 'ipb_range_start' => $this->mRangeStart,
392 'ipb_range_end' => $this->mRangeEnd,
393 ), 'Block::insert', array( 'IGNORE' )
394 );
395 $affected = $dbw->affectedRows();
396 $dbw->commit();
397
398 if ($affected)
399 $this->doRetroactiveAutoblock();
400
401 return $affected;
402 }
403
404 /**
405 * Retroactively autoblocks the last IP used by the user (if it is a user)
406 * blocked by this Block.
407 *@return Whether or not a retroactive autoblock was made.
408 */
409 function doRetroactiveAutoblock() {
410 $dbr = wfGetDb( DB_SLAVE );
411 #If autoblock is enabled, autoblock the LAST IP used
412 # - stolen shamelessly from CheckUser_body.php
413
414 if ($this->mEnableAutoblock && $this->mUser) {
415 wfDebug("Doing retroactive autoblocks for " . $this->mAddress . "\n");
416
417 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress ),
418 $fname, array( 'ORDER BY' => 'rc_timestamp DESC' ) );
419
420 if ( !$row || !$row->rc_ip ) {
421 #No results, don't autoblock anything
422 wfDebug("No IP found to retroactively autoblock\n");
423 } else {
424 #Limit is 1, so no loop needed.
425 $retroblockip = $row->rc_ip;
426 return $this->doAutoblock($retroblockip);
427 }
428 }
429 }
430
431 /**
432 * Autoblocks the given IP, referring to this Block.
433 * @param $autoblockip The IP to autoblock.
434 * @return bool Whether or not an autoblock was inserted.
435 */
436 function doAutoblock( $autoblockip ) {
437 # Check if this IP address is already blocked
438 $dbw =& wfGetDb( DB_MASTER );
439 $dbw->begin();
440
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 = wfGetIp();
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 $wlEntry\n");
464
465 # Is the IP in this range?
466 if (wfIsAddressInRange( $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 }
472 }
473
474 # It's okay to autoblock. Go ahead and create/insert the block.
475
476 $ipblock = Block::newFromDB( $autoblockip );
477 if ( $ipblock ) {
478 # If the user is already blocked. Then check if the autoblock would
479 # exceed the user block. If it would exceed, then do nothing, else
480 # prolong block time
481 if ($this->mExpiry &&
482 ($this->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
483 return;
484 }
485 # Just update the timestamp
486 $ipblock->updateTimestamp();
487 return;
488 } else {
489 $ipblock = new Block;
490 }
491
492 # Make a new block object with the desired properties
493 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
494 $ipblock->mAddress = $autoblockip;
495 $ipblock->mUser = 0;
496 $ipblock->mBy = $this->mBy;
497 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
498 $ipblock->mTimestamp = wfTimestampNow();
499 $ipblock->mAuto = 1;
500 $ipblock->mCreateAccount = $this->mCreateAccount;
501
502 # If the user is already blocked with an expiry date, we don't
503 # want to pile on top of that!
504 if($this->mExpiry) {
505 $ipblock->mExpiry = min ( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ));
506 } else {
507 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
508 }
509 # Insert it
510 return $ipblock->insert();
511 }
512
513 function deleteIfExpired()
514 {
515 $fname = 'Block::deleteIfExpired';
516 wfProfileIn( $fname );
517 if ( $this->isExpired() ) {
518 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
519 $this->delete();
520 $retVal = true;
521 } else {
522 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
523 $retVal = false;
524 }
525 wfProfileOut( $fname );
526 return $retVal;
527 }
528
529 function isExpired()
530 {
531 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
532 if ( !$this->mExpiry ) {
533 return false;
534 } else {
535 return wfTimestampNow() > $this->mExpiry;
536 }
537 }
538
539 function isValid()
540 {
541 return $this->mAddress != '';
542 }
543
544 function updateTimestamp()
545 {
546 if ( $this->mAuto ) {
547 $this->mTimestamp = wfTimestamp();
548 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
549
550 $dbw =& wfGetDB( DB_MASTER );
551 $dbw->update( 'ipblocks',
552 array( /* SET */
553 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
554 'ipb_expiry' => $dbw->timestamp($this->mExpiry),
555 ), array( /* WHERE */
556 'ipb_address' => $this->mAddress
557 ), 'Block::updateTimestamp'
558 );
559 }
560 }
561
562 /*
563 function getIntegerAddr()
564 {
565 return $this->mIntegerAddr;
566 }
567
568 function getNetworkBits()
569 {
570 return $this->mNetworkBits;
571 }*/
572
573 /**
574 * @return The blocker user ID.
575 */
576 public function getBy() {
577 return $this->mBy;
578 }
579
580 /**
581 * @return The blocker user name.
582 */
583 function getByName()
584 {
585 if ( $this->mByName === false ) {
586 $this->mByName = User::whoIs( $this->mBy );
587 }
588 return $this->mByName;
589 }
590
591 function forUpdate( $x = NULL ) {
592 return wfSetVar( $this->mForUpdate, $x );
593 }
594
595 function fromMaster( $x = NULL ) {
596 return wfSetVar( $this->mFromMaster, $x );
597 }
598
599 function getRedactedName() {
600 if ( $this->mAuto ) {
601 return '#' . $this->mId;
602 } else {
603 return $this->mAddress;
604 }
605 }
606
607 /**
608 * Encode expiry for DB
609 */
610 static function encodeExpiry( $expiry, $db ) {
611 if ( $expiry == '' || $expiry == Block::infinity() ) {
612 return Block::infinity();
613 } else {
614 return $db->timestamp( $expiry );
615 }
616 }
617
618 /**
619 * Decode expiry which has come from the DB
620 */
621 static function decodeExpiry( $expiry ) {
622 if ( $expiry == '' || $expiry == Block::infinity() ) {
623 return Block::infinity();
624 } else {
625 return wfTimestamp( TS_MW, $expiry );
626 }
627 }
628
629 static function getAutoblockExpiry( $timestamp )
630 {
631 global $wgAutoblockExpiry;
632 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
633 }
634
635 static function normaliseRange( $range )
636 {
637 $parts = explode( '/', $range );
638 if ( count( $parts ) == 2 ) {
639 $shift = 32 - $parts[1];
640 $ipint = IP::toUnsigned( $parts[0] );
641 $ipint = $ipint >> $shift << $shift;
642 $newip = long2ip( $ipint );
643 $range = "$newip/{$parts[1]}";
644 }
645 return $range;
646 }
647
648 /**
649 * Purge expired blocks from the ipblocks table
650 */
651 static function purgeExpired() {
652 $dbw =& wfGetDB( DB_MASTER );
653 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
654 }
655
656 static function infinity() {
657 # This is a special keyword for timestamps in PostgreSQL, and
658 # works with CHAR(14) as well because "i" sorts after all numbers.
659 return 'infinity';
660
661 /*
662 static $infinity;
663 if ( !isset( $infinity ) ) {
664 $dbr =& wfGetDB( DB_SLAVE );
665 $infinity = $dbr->bigTimestamp();
666 }
667 return $infinity;
668 */
669 }
670
671 }
672 ?>