remove unused message
[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;
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 )
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
41 $this->mForUpdate = false;
42 $this->mFromMaster = false;
43 $this->mByName = false;
44 $this->initialiseRange();
45 }
46
47 static function newFromDB( $address, $user = 0, $killExpired = true )
48 {
49 $block = new Block();
50 $block->load( $address, $user, $killExpired );
51 if ( $block->isValid() ) {
52 return $block;
53 } else {
54 return null;
55 }
56 }
57
58 static function newFromID( $id )
59 {
60 $dbr =& wfGetDB( DB_SLAVE );
61 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
62 array( 'ipb_id' => $id ), __METHOD__ ) );
63 $block = new Block;
64 if ( $block->loadFromResult( $res ) ) {
65 return $block;
66 } else {
67 return null;
68 }
69 }
70
71 function clear()
72 {
73 $this->mAddress = $this->mReason = $this->mTimestamp = '';
74 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
75 $this->mAuto = $this->mUser = $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 $ret = false;
115 $killed = false;
116
117 if ( 0 == $user && $address == '' ) {
118 # Invalid user specification, not blocked
119 $this->clear();
120 return false;
121 }
122
123 # Try user block
124 if ( $user ) {
125 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
126 __METHOD__, $options ) );
127 if ( $this->loadFromResult( $res, $killExpired ) ) {
128 return true;
129 }
130 }
131
132 # Try IP block
133 # TODO: improve performance by merging this query with the autoblock one
134 # Slightly tricky while handling killExpired as well
135 if ( $address ) {
136 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
137 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
138 if ( $this->loadFromResult( $res, $killExpired ) ) {
139 if ( $user && $this->mAnonOnly ) {
140 # Block is marked anon-only
141 # Whitelist this IP address against autoblocks and range blocks
142 $this->clear();
143 return false;
144 } else {
145 return true;
146 }
147 }
148 }
149
150 # Try range block
151 if ( $this->loadRange( $address, $killExpired, $user == 0 ) ) {
152 if ( $user && $this->mAnonOnly ) {
153 $this->clear();
154 return false;
155 } else {
156 return true;
157 }
158 }
159
160 # Try autoblock
161 if ( $address ) {
162 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
163 if ( $user ) {
164 $conds['ipb_anon_only'] = 0;
165 }
166 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
167 if ( $this->loadFromResult( $res, $killExpired ) ) {
168 return true;
169 }
170 }
171
172 # Give up
173 $this->clear();
174 return false;
175 }
176
177 /**
178 * Fill in member variables from a result wrapper
179 */
180 function loadFromResult( ResultWrapper $res, $killExpired = true ) {
181 $ret = false;
182 if ( 0 != $res->numRows() ) {
183 # Get first block
184 $row = $res->fetchObject();
185 $this->initFromRow( $row );
186
187 if ( $killExpired ) {
188 # If requested, delete expired rows
189 do {
190 $killed = $this->deleteIfExpired();
191 if ( $killed ) {
192 $row = $res->fetchObject();
193 if ( $row ) {
194 $this->initFromRow( $row );
195 }
196 }
197 } while ( $killed && $row );
198
199 # If there were any left after the killing finished, return true
200 if ( $row ) {
201 $ret = true;
202 }
203 } else {
204 $ret = true;
205 }
206 }
207 $res->free();
208 return $ret;
209 }
210
211 /**
212 * Search the database for any range blocks matching the given address, and
213 * load the row if one is found.
214 */
215 function loadRange( $address, $killExpired = true )
216 {
217 $iaddr = IP::toHex( $address );
218 if ( $iaddr === false ) {
219 # Invalid address
220 return false;
221 }
222
223 # Only scan ranges which start in this /16, this improves search speed
224 # Blocks should not cross a /16 boundary.
225 $range = substr( $iaddr, 0, 4 );
226
227 $options = array();
228 $db =& $this->getDBOptions( $options );
229 $conds = array(
230 "ipb_range_start LIKE '$range%'",
231 "ipb_range_start <= '$iaddr'",
232 "ipb_range_end >= '$iaddr'"
233 );
234
235 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
236 $success = $this->loadFromResult( $res, $killExpired );
237 return $success;
238 }
239
240 /**
241 * Determine if a given integer IPv4 address is in a given CIDR network
242 */
243 function isAddressInRange( $addr, $range ) {
244 list( $network, $bits ) = wfParseCIDR( $range );
245 if ( $network !== false && $addr >> ( 32 - $bits ) == $network >> ( 32 - $bits ) ) {
246 return true;
247 } else {
248 return false;
249 }
250 }
251
252 function initFromRow( $row )
253 {
254 $this->mAddress = $row->ipb_address;
255 $this->mReason = $row->ipb_reason;
256 $this->mTimestamp = wfTimestamp(TS_MW,$row->ipb_timestamp);
257 $this->mUser = $row->ipb_user;
258 $this->mBy = $row->ipb_by;
259 $this->mAuto = $row->ipb_auto;
260 $this->mAnonOnly = $row->ipb_anon_only;
261 $this->mCreateAccount = $row->ipb_create_account;
262 $this->mId = $row->ipb_id;
263 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
264 if ( isset( $row->user_name ) ) {
265 $this->mByName = $row->user_name;
266 } else {
267 $this->mByName = false;
268 }
269 $this->mRangeStart = $row->ipb_range_start;
270 $this->mRangeEnd = $row->ipb_range_end;
271 }
272
273 function initialiseRange()
274 {
275 $this->mRangeStart = '';
276 $this->mRangeEnd = '';
277 if ( $this->mUser == 0 ) {
278 list( $network, $bits ) = wfParseCIDR( $this->mAddress );
279 if ( $network !== false ) {
280 $this->mRangeStart = sprintf( '%08X', $network );
281 $this->mRangeEnd = sprintf( '%08X', $network + (1 << (32 - $bits)) - 1 );
282 }
283 }
284 }
285
286 /**
287 * Callback with a Block object for every block
288 * @return integer number of blocks;
289 */
290 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
291 {
292 global $wgAntiLockFlags;
293
294 $block = new Block();
295 if ( $flags & Block::EB_FOR_UPDATE ) {
296 $db =& wfGetDB( DB_MASTER );
297 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK ) {
298 $options = '';
299 } else {
300 $options = 'FOR UPDATE';
301 }
302 $block->forUpdate( true );
303 } else {
304 $db =& wfGetDB( DB_SLAVE );
305 $options = '';
306 }
307 if ( $flags & Block::EB_RANGE_ONLY ) {
308 $cond = " AND ipb_range_start <> ''";
309 } else {
310 $cond = '';
311 }
312
313 $now = wfTimestampNow();
314
315 extract( $db->tableNames( 'ipblocks', 'user' ) );
316
317 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
318 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
319 $res = $db->query( $sql, 'Block::enumBlocks' );
320 $num_rows = $db->numRows( $res );
321
322 while ( $row = $db->fetchObject( $res ) ) {
323 $block->initFromRow( $row );
324 if ( ( $flags & Block::EB_RANGE_ONLY ) && $block->mRangeStart == '' ) {
325 continue;
326 }
327
328 if ( !( $flags & Block::EB_KEEP_EXPIRED ) ) {
329 if ( $block->mExpiry && $now > $block->mExpiry ) {
330 $block->delete();
331 } else {
332 call_user_func( $callback, $block, $tag );
333 }
334 } else {
335 call_user_func( $callback, $block, $tag );
336 }
337 }
338 wfFreeResult( $res );
339 return $num_rows;
340 }
341
342 function delete()
343 {
344 if (wfReadOnly()) {
345 return false;
346 }
347 if ( !$this->mId ) {
348 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
349 }
350
351 $dbw =& wfGetDB( DB_MASTER );
352 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
353 return $dbw->affectedRows() > 0;
354 }
355
356 function insert()
357 {
358 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
359 $dbw =& wfGetDB( DB_MASTER );
360 $dbw->begin();
361
362 # Unset ipb_anon_only for user blocks, makes no sense
363 if ( $this->mUser ) {
364 $this->mAnonOnly = 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_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
383 'ipb_range_start' => $this->mRangeStart,
384 'ipb_range_end' => $this->mRangeEnd,
385 ), 'Block::insert', array( 'IGNORE' )
386 );
387 $affected = $dbw->affectedRows();
388 $dbw->commit();
389 return $affected;
390 }
391
392 function deleteIfExpired()
393 {
394 $fname = 'Block::deleteIfExpired';
395 wfProfileIn( $fname );
396 if ( $this->isExpired() ) {
397 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
398 $this->delete();
399 $retVal = true;
400 } else {
401 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
402 $retVal = false;
403 }
404 wfProfileOut( $fname );
405 return $retVal;
406 }
407
408 function isExpired()
409 {
410 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
411 if ( !$this->mExpiry ) {
412 return false;
413 } else {
414 return wfTimestampNow() > $this->mExpiry;
415 }
416 }
417
418 function isValid()
419 {
420 return $this->mAddress != '';
421 }
422
423 function updateTimestamp()
424 {
425 if ( $this->mAuto ) {
426 $this->mTimestamp = wfTimestamp();
427 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
428
429 $dbw =& wfGetDB( DB_MASTER );
430 $dbw->update( 'ipblocks',
431 array( /* SET */
432 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
433 'ipb_expiry' => $dbw->timestamp($this->mExpiry),
434 ), array( /* WHERE */
435 'ipb_address' => $this->mAddress
436 ), 'Block::updateTimestamp'
437 );
438 }
439 }
440
441 /*
442 function getIntegerAddr()
443 {
444 return $this->mIntegerAddr;
445 }
446
447 function getNetworkBits()
448 {
449 return $this->mNetworkBits;
450 }*/
451
452 function getByName()
453 {
454 if ( $this->mByName === false ) {
455 $this->mByName = User::whoIs( $this->mBy );
456 }
457 return $this->mByName;
458 }
459
460 function forUpdate( $x = NULL ) {
461 return wfSetVar( $this->mForUpdate, $x );
462 }
463
464 function fromMaster( $x = NULL ) {
465 return wfSetVar( $this->mFromMaster, $x );
466 }
467
468 function getRedactedName() {
469 if ( $this->mAuto ) {
470 return '#' . $this->mId;
471 } else {
472 return $this->mAddress;
473 }
474 }
475
476 /**
477 * Encode expiry for DB
478 */
479 static function encodeExpiry( $expiry, $db ) {
480 if ( $expiry == '' || $expiry == Block::infinity() ) {
481 return Block::infinity();
482 } else {
483 return $db->timestamp( $expiry );
484 }
485 }
486
487 /**
488 * Decode expiry which has come from the DB
489 */
490 static function decodeExpiry( $expiry ) {
491 if ( $expiry == '' || $expiry == Block::infinity() ) {
492 return Block::infinity();
493 } else {
494 return wfTimestamp( TS_MW, $expiry );
495 }
496 }
497
498 static function getAutoblockExpiry( $timestamp )
499 {
500 global $wgAutoblockExpiry;
501 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
502 }
503
504 static function normaliseRange( $range )
505 {
506 $parts = explode( '/', $range );
507 if ( count( $parts ) == 2 ) {
508 $shift = 32 - $parts[1];
509 $ipint = IP::toUnsigned( $parts[0] );
510 $ipint = $ipint >> $shift << $shift;
511 $newip = long2ip( $ipint );
512 $range = "$newip/{$parts[1]}";
513 }
514 return $range;
515 }
516
517 /**
518 * Purge expired blocks from the ipblocks table
519 */
520 static function purgeExpired() {
521 $dbw =& wfGetDB( DB_MASTER );
522 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
523 }
524
525 static function infinity() {
526 # This is a special keyword for timestamps in PostgreSQL, and
527 # works with CHAR(14) as well because "i" sorts after all numbers.
528 return 'infinity';
529
530 /*
531 static $infinity;
532 if ( !isset( $infinity ) ) {
533 $dbr =& wfGetDB( DB_SLAVE );
534 $infinity = $dbr->bigTimestamp();
535 }
536 return $infinity;
537 */
538 }
539
540 }
541 ?>