disallow embedded line breaks in ISBNs; allowing them breaks things in a most interes...
[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 $wlEntry\n");
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 }
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 ?>