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