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