Fix bug reported by Slowking_Man where retroactive autoblocks take effect even if...
[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 */
245 function isAddressInRange( $addr, $range ) {
246 list( $network, $bits ) = wfParseCIDR( $range );
247 if ( $network !== false && $addr >> ( 32 - $bits ) == $network >> ( 32 - $bits ) ) {
248 return true;
249 } else {
250 return false;
251 }
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->mId = $row->ipb_id;
266 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
267 if ( isset( $row->user_name ) ) {
268 $this->mByName = $row->user_name;
269 } else {
270 $this->mByName = false;
271 }
272 $this->mRangeStart = $row->ipb_range_start;
273 $this->mRangeEnd = $row->ipb_range_end;
274 }
275
276 function initialiseRange()
277 {
278 $this->mRangeStart = '';
279 $this->mRangeEnd = '';
280 if ( $this->mUser == 0 ) {
281 list( $network, $bits ) = wfParseCIDR( $this->mAddress );
282 if ( $network !== false ) {
283 $this->mRangeStart = sprintf( '%08X', $network );
284 $this->mRangeEnd = sprintf( '%08X', $network + (1 << (32 - $bits)) - 1 );
285 }
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 extract( $db->tableNames( '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 wfFreeResult( $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 $dbw->begin();
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 }
378
379 # Don't collide with expired blocks
380 Block::purgeExpired();
381
382 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
383 $dbw->insert( 'ipblocks',
384 array(
385 'ipb_id' => $ipb_id,
386 'ipb_address' => $this->mAddress,
387 'ipb_user' => $this->mUser,
388 'ipb_by' => $this->mBy,
389 'ipb_reason' => $this->mReason,
390 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
391 'ipb_auto' => $this->mAuto,
392 'ipb_anon_only' => $this->mAnonOnly,
393 'ipb_create_account' => $this->mCreateAccount,
394 'ipb_enable_autoblock' => $this->mEnableAutoblock,
395 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
396 'ipb_range_start' => $this->mRangeStart,
397 'ipb_range_end' => $this->mRangeEnd,
398 ), 'Block::insert', array( 'IGNORE' )
399 );
400 $affected = $dbw->affectedRows();
401 $dbw->commit();
402
403 if ($affected)
404 $this->doRetroactiveAutoblock();
405
406 return $affected;
407 }
408
409 /**
410 * Retroactively autoblocks the last IP used by the user (if it is a user)
411 * blocked by this Block.
412 *@return Whether or not a retroactive autoblock was made.
413 */
414 function doRetroactiveAutoblock() {
415 $dbr = wfGetDb( DB_SLAVE );
416 #If autoblock is enabled, autoblock the LAST IP used
417 # - stolen shamelessly from CheckUser_body.php
418
419 if ($this->mEnableAutoblock && $this->mUser) {
420 wfDebug("Doing retroactive autoblocks for " . $this->mAddress . "\n");
421
422 $row = $dbr->selectRow( 'recentchanges', array( 'rc_ip' ), array( 'rc_user_text' => $this->mAddress ),
423 $fname, array( 'ORDER BY' => 'rc_timestamp DESC' ) );
424
425 if ( !$row || !$row->rc_ip ) {
426 #No results, don't autoblock anything
427 wfDebug("No IP found to retroactively autoblock\n");
428 } else {
429 #Limit is 1, so no loop needed.
430 $retroblockip = $row->rc_ip;
431 return $this->doAutoblock($retroblockip);
432 }
433 }
434 }
435
436 /**
437 * Autoblocks the given IP, referring to this Block.
438 *@param $autoblockip The IP to autoblock.
439 *@return Whether or not an autoblock was inserted.
440 */
441 function doAutoblock( $autoblockip ) {
442 # Check if this IP address is already blocked
443 $dbw =& wfGetDb( DB_MASTER );
444 $dbw->begin();
445
446 if ( !$this->mEnableAutoblock ) {
447 return;
448 }
449
450 $ipblock = Block::newFromDB( $autoblockip );
451 if ( $ipblock ) {
452 # If the user is already blocked. Then check if the autoblock would
453 # exceed the user block. If it would exceed, then do nothing, else
454 # prolong block time
455 if ($this->mExpiry &&
456 ($this->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
457 return;
458 }
459 # Just update the timestamp
460 $ipblock->updateTimestamp();
461 return;
462 } else {
463 $ipblock = new Block;
464 }
465
466 # Make a new block object with the desired properties
467 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
468 $ipblock->mAddress = $autoblockip;
469 $ipblock->mUser = 0;
470 $ipblock->mBy = $this->mBy;
471 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
472 $ipblock->mTimestamp = wfTimestampNow();
473 $ipblock->mAuto = 1;
474 $ipblock->mCreateAccount = $this->mCreateAccount;
475
476 # If the user is already blocked with an expiry date, we don't
477 # want to pile on top of that!
478 if($this->mExpiry) {
479 $ipblock->mExpiry = min ( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ));
480 } else {
481 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
482 }
483 # Insert it
484 return $ipblock->insert();
485 }
486
487 function deleteIfExpired()
488 {
489 $fname = 'Block::deleteIfExpired';
490 wfProfileIn( $fname );
491 if ( $this->isExpired() ) {
492 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
493 $this->delete();
494 $retVal = true;
495 } else {
496 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
497 $retVal = false;
498 }
499 wfProfileOut( $fname );
500 return $retVal;
501 }
502
503 function isExpired()
504 {
505 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
506 if ( !$this->mExpiry ) {
507 return false;
508 } else {
509 return wfTimestampNow() > $this->mExpiry;
510 }
511 }
512
513 function isValid()
514 {
515 return $this->mAddress != '';
516 }
517
518 function updateTimestamp()
519 {
520 if ( $this->mAuto ) {
521 $this->mTimestamp = wfTimestamp();
522 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
523
524 $dbw =& wfGetDB( DB_MASTER );
525 $dbw->update( 'ipblocks',
526 array( /* SET */
527 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
528 'ipb_expiry' => $dbw->timestamp($this->mExpiry),
529 ), array( /* WHERE */
530 'ipb_address' => $this->mAddress
531 ), 'Block::updateTimestamp'
532 );
533 }
534 }
535
536 /*
537 function getIntegerAddr()
538 {
539 return $this->mIntegerAddr;
540 }
541
542 function getNetworkBits()
543 {
544 return $this->mNetworkBits;
545 }*/
546
547 function getByName()
548 {
549 if ( $this->mByName === false ) {
550 $this->mByName = User::whoIs( $this->mBy );
551 }
552 return $this->mByName;
553 }
554
555 function forUpdate( $x = NULL ) {
556 return wfSetVar( $this->mForUpdate, $x );
557 }
558
559 function fromMaster( $x = NULL ) {
560 return wfSetVar( $this->mFromMaster, $x );
561 }
562
563 function getRedactedName() {
564 if ( $this->mAuto ) {
565 return '#' . $this->mId;
566 } else {
567 return $this->mAddress;
568 }
569 }
570
571 /**
572 * Encode expiry for DB
573 */
574 static function encodeExpiry( $expiry, $db ) {
575 if ( $expiry == '' || $expiry == Block::infinity() ) {
576 return Block::infinity();
577 } else {
578 return $db->timestamp( $expiry );
579 }
580 }
581
582 /**
583 * Decode expiry which has come from the DB
584 */
585 static function decodeExpiry( $expiry ) {
586 if ( $expiry == '' || $expiry == Block::infinity() ) {
587 return Block::infinity();
588 } else {
589 return wfTimestamp( TS_MW, $expiry );
590 }
591 }
592
593 static function getAutoblockExpiry( $timestamp )
594 {
595 global $wgAutoblockExpiry;
596 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
597 }
598
599 static function normaliseRange( $range )
600 {
601 $parts = explode( '/', $range );
602 if ( count( $parts ) == 2 ) {
603 $shift = 32 - $parts[1];
604 $ipint = IP::toUnsigned( $parts[0] );
605 $ipint = $ipint >> $shift << $shift;
606 $newip = long2ip( $ipint );
607 $range = "$newip/{$parts[1]}";
608 }
609 return $range;
610 }
611
612 /**
613 * Purge expired blocks from the ipblocks table
614 */
615 static function purgeExpired() {
616 $dbw =& wfGetDB( DB_MASTER );
617 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
618 }
619
620 static function infinity() {
621 # This is a special keyword for timestamps in PostgreSQL, and
622 # works with CHAR(14) as well because "i" sorts after all numbers.
623 return 'infinity';
624
625 /*
626 static $infinity;
627 if ( !isset( $infinity ) ) {
628 $dbr =& wfGetDB( DB_SLAVE );
629 $infinity = $dbr->bigTimestamp();
630 }
631 return $infinity;
632 */
633 }
634
635 }
636 ?>