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