* Lots and lots of docs
[lhc/web/wiklou.git] / includes / Block.php
1 <?php
2 /**
3 * @file
4 * Blocks and bans object
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 */
16 class Block
17 {
18 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
19 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock, $mHideName,
20 $mBlockEmail, $mByName, $mAngryAutoblock;
21 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster;
22
23 const EB_KEEP_EXPIRED = 1;
24 const EB_FOR_UPDATE = 2;
25 const EB_RANGE_ONLY = 4;
26
27 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
28 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
29 $hideName = 0, $blockEmail = 0 )
30 {
31 $this->mId = 0;
32 # Expand valid IPv6 addresses
33 $address = IP::sanitizeIP( $address );
34 $this->mAddress = $address;
35 $this->mUser = $user;
36 $this->mBy = $by;
37 $this->mReason = $reason;
38 $this->mTimestamp = wfTimestamp(TS_MW,$timestamp);
39 $this->mAuto = $auto;
40 $this->mAnonOnly = $anonOnly;
41 $this->mCreateAccount = $createAccount;
42 $this->mExpiry = self::decodeExpiry( $expiry );
43 $this->mEnableAutoblock = $enableAutoblock;
44 $this->mHideName = $hideName;
45 $this->mBlockEmail = $blockEmail;
46 $this->mForUpdate = false;
47 $this->mFromMaster = false;
48 $this->mByName = false;
49 $this->mAngryAutoblock = false;
50 $this->initialiseRange();
51 }
52
53 /**
54 * Load a block from the database, using either the IP address or
55 * userid.
56 *
57 * @return Block Object
58 * @param $address string IP address of user/anon
59 * @param $user int User id of user
60 * @param $killExpired bool Delete expired blocks on load
61 */
62 static function newFromDB( $address, $user = 0, $killExpired = true )
63 {
64 $block = new Block();
65 $block->load( $address, $user, $killExpired );
66 if ( $block->isValid() ) {
67 return $block;
68 } else {
69 return null;
70 }
71 }
72
73 /**
74 * Load a blocked user from their block id.
75 * @return Block object
76 * @param $id int Block id to search for
77 */
78 static function newFromID( $id )
79 {
80 $dbr = wfGetDB( DB_SLAVE );
81 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
82 array( 'ipb_id' => $id ), __METHOD__ ) );
83 $block = new Block;
84 if ( $block->loadFromResult( $res ) ) {
85 return $block;
86 } else {
87 return null;
88 }
89 }
90
91 /**
92 * Clear all member variables in the current object. Does not clear
93 * the block from the DB.
94 */
95 function clear()
96 {
97 $this->mAddress = $this->mReason = $this->mTimestamp = '';
98 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
99 $this->mEnableAutoblock = $this->mAuto = $this->mUser =
100 $this->mBy = $this->mHideName = $this->mBlockEmail = 0;
101 $this->mByName = false;
102 }
103
104 /**
105 * Get the DB object and set the reference parameter to the query options
106 * @return Database
107 */
108 function &getDBOptions( &$options ) {
109 global $wgAntiLockFlags;
110 if ( $this->mForUpdate || $this->mFromMaster ) {
111 $db = wfGetDB( DB_MASTER );
112 if ( !$this->mForUpdate || ($wgAntiLockFlags & ALF_NO_BLOCK_LOCK) ) {
113 $options = array();
114 } else {
115 $options = array( 'FOR UPDATE' );
116 }
117 } else {
118 $db = wfGetDB( DB_SLAVE );
119 $options = array();
120 }
121 return $db;
122 }
123
124 /**
125 * Get a ban from the DB, with either the given address or the given username
126 *
127 * @param $address string The IP address of the user, or blank to skip IP blocks
128 * @param $user int The user ID, or zero for anonymous users
129 * @param $killExpired bool Whether to delete expired rows while loading
130 *
131 */
132 function load( $address = '', $user = 0, $killExpired = true )
133 {
134 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
135
136 $options = array();
137 $db =& $this->getDBOptions( $options );
138
139 if ( 0 == $user && $address == '' ) {
140 # Invalid user specification, not blocked
141 $this->clear();
142 return false;
143 }
144
145 # Try user block
146 if ( $user ) {
147 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
148 __METHOD__, $options ) );
149 if ( $this->loadFromResult( $res, $killExpired ) ) {
150 return true;
151 }
152 }
153
154 # Try IP block
155 # TODO: improve performance by merging this query with the autoblock one
156 # Slightly tricky while handling killExpired as well
157 if ( $address ) {
158 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
159 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
160 if ( $this->loadFromResult( $res, $killExpired ) ) {
161 if ( $user && $this->mAnonOnly ) {
162 # Block is marked anon-only
163 # Whitelist this IP address against autoblocks and range blocks
164 $this->clear();
165 return false;
166 } else {
167 return true;
168 }
169 }
170 }
171
172 # Try range block
173 if ( $this->loadRange( $address, $killExpired, $user ) ) {
174 if ( $user && $this->mAnonOnly ) {
175 $this->clear();
176 return false;
177 } else {
178 return true;
179 }
180 }
181
182 # Try autoblock
183 if ( $address ) {
184 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
185 if ( $user ) {
186 $conds['ipb_anon_only'] = 0;
187 }
188 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
189 if ( $this->loadFromResult( $res, $killExpired ) ) {
190 return true;
191 }
192 }
193
194 # Give up
195 $this->clear();
196 return false;
197 }
198
199 /**
200 * Fill in member variables from a result wrapper
201 * @return bool
202 * @param $res ResultWrapper Row from the ipblocks table
203 * @param $killExpired bool Whether to delete expired rows while loading
204 */
205 function loadFromResult( ResultWrapper $res, $killExpired = true )
206 {
207 $ret = false;
208 if ( 0 != $res->numRows() ) {
209 # Get first block
210 $row = $res->fetchObject();
211 $this->initFromRow( $row );
212
213 if ( $killExpired ) {
214 # If requested, delete expired rows
215 do {
216 $killed = $this->deleteIfExpired();
217 if ( $killed ) {
218 $row = $res->fetchObject();
219 if ( $row ) {
220 $this->initFromRow( $row );
221 }
222 }
223 } while ( $killed && $row );
224
225 # If there were any left after the killing finished, return true
226 if ( $row ) {
227 $ret = true;
228 }
229 } else {
230 $ret = true;
231 }
232 }
233 $res->free();
234 return $ret;
235 }
236
237 /**
238 * Search the database for any range blocks matching the given address, and
239 * load the row if one is found.
240 * @return bool
241 * @param $address string IP address range
242 * @param $killExpired bool Whether to delete expired rows while loading
243 * @param $userid int If not 0, then sets ipb_anon_only
244 */
245 function loadRange( $address, $killExpired = true, $user = 0 )
246 {
247 $iaddr = IP::toHex( $address );
248 if ( $iaddr === false ) {
249 # Invalid address
250 return false;
251 }
252
253 # Only scan ranges which start in this /16, this improves search speed
254 # Blocks should not cross a /16 boundary.
255 $range = substr( $iaddr, 0, 4 );
256
257 $options = array();
258 $db =& $this->getDBOptions( $options );
259 $conds = array(
260 "ipb_range_start LIKE '$range%'",
261 "ipb_range_start <= '$iaddr'",
262 "ipb_range_end >= '$iaddr'"
263 );
264
265 if ( $user ) {
266 $conds['ipb_anon_only'] = 0;
267 }
268
269 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
270 $success = $this->loadFromResult( $res, $killExpired );
271 return $success;
272 }
273
274 /**
275 * Determine if a given integer IPv4 address is in a given CIDR network
276 * @deprecated Use IP::isInRange
277 */
278 function isAddressInRange( $addr, $range ) {
279 return IP::isInRange( $addr, $range );
280 }
281
282 /**
283 * Given a database row from the ipblocks table, initialize
284 * member variables
285 * @param $row ResultWrapper A row from the ipblocks table
286 */
287 function initFromRow( $row )
288 {
289 $this->mAddress = $row->ipb_address;
290 $this->mReason = $row->ipb_reason;
291 $this->mTimestamp = wfTimestamp(TS_MW,$row->ipb_timestamp);
292 $this->mUser = $row->ipb_user;
293 $this->mBy = $row->ipb_by;
294 $this->mAuto = $row->ipb_auto;
295 $this->mAnonOnly = $row->ipb_anon_only;
296 $this->mCreateAccount = $row->ipb_create_account;
297 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
298 $this->mBlockEmail = $row->ipb_block_email;
299 $this->mHideName = $row->ipb_deleted;
300 $this->mId = $row->ipb_id;
301 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
302 if ( isset( $row->user_name ) ) {
303 $this->mByName = $row->user_name;
304 } else {
305 $this->mByName = $row->ipb_by_text;
306 }
307 $this->mRangeStart = $row->ipb_range_start;
308 $this->mRangeEnd = $row->ipb_range_end;
309 }
310
311 /**
312 * Once $mAddress has been set, get the range they came from.
313 * Wrapper for IP::parseRange
314 */
315 function initialiseRange()
316 {
317 $this->mRangeStart = '';
318 $this->mRangeEnd = '';
319
320 if ( $this->mUser == 0 ) {
321 list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress );
322 }
323 }
324
325 /**
326 * Callback with a Block object for every block
327 * @return integer number of blocks;
328 */
329 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
330 {
331 global $wgAntiLockFlags;
332
333 $block = new Block();
334 if ( $flags & Block::EB_FOR_UPDATE ) {
335 $db = wfGetDB( DB_MASTER );
336 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK ) {
337 $options = '';
338 } else {
339 $options = 'FOR UPDATE';
340 }
341 $block->forUpdate( true );
342 } else {
343 $db = wfGetDB( DB_SLAVE );
344 $options = '';
345 }
346 if ( $flags & Block::EB_RANGE_ONLY ) {
347 $cond = " AND ipb_range_start <> ''";
348 } else {
349 $cond = '';
350 }
351
352 $now = wfTimestampNow();
353
354 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
355
356 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
357 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
358 $res = $db->query( $sql, 'Block::enumBlocks' );
359 $num_rows = $db->numRows( $res );
360
361 while ( $row = $db->fetchObject( $res ) ) {
362 $block->initFromRow( $row );
363 if ( ( $flags & Block::EB_RANGE_ONLY ) && $block->mRangeStart == '' ) {
364 continue;
365 }
366
367 if ( !( $flags & Block::EB_KEEP_EXPIRED ) ) {
368 if ( $block->mExpiry && $now > $block->mExpiry ) {
369 $block->delete();
370 } else {
371 call_user_func( $callback, $block, $tag );
372 }
373 } else {
374 call_user_func( $callback, $block, $tag );
375 }
376 }
377 $db->freeResult( $res );
378 return $num_rows;
379 }
380
381 /**
382 * Delete the row from the IP blocks table.
383 * @return bool
384 */
385 function delete()
386 {
387 if (wfReadOnly()) {
388 return false;
389 }
390 if ( !$this->mId ) {
391 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
392 }
393
394 $dbw = wfGetDB( DB_MASTER );
395 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
396 return $dbw->affectedRows() > 0;
397 }
398
399 /**
400 * Insert a block into the block table.
401 * @return bool Whether or not the insertion was successful.
402 */
403 function insert()
404 {
405 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
406 $dbw = wfGetDB( DB_MASTER );
407
408 # Unset ipb_anon_only for user blocks, makes no sense
409 if ( $this->mUser ) {
410 $this->mAnonOnly = 0;
411 }
412
413 # Unset ipb_enable_autoblock for IP blocks, makes no sense
414 if ( !$this->mUser ) {
415 $this->mEnableAutoblock = 0;
416 $this->mBlockEmail = 0; //Same goes for email...
417 }
418
419 if( !$this->mByName ) {
420 if( $this->mBy ) {
421 $this->mByName = User::whoIs( $this->mBy );
422 } else {
423 global $wgUser;
424 $this->mByName = $wgUser->getName();
425 }
426 }
427
428 # Don't collide with expired blocks
429 Block::purgeExpired();
430
431 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
432 $dbw->insert( 'ipblocks',
433 array(
434 'ipb_id' => $ipb_id,
435 'ipb_address' => $this->mAddress,
436 'ipb_user' => $this->mUser,
437 'ipb_by' => $this->mBy,
438 'ipb_by_text' => $this->mByName,
439 'ipb_reason' => $this->mReason,
440 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
441 'ipb_auto' => $this->mAuto,
442 'ipb_anon_only' => $this->mAnonOnly,
443 'ipb_create_account' => $this->mCreateAccount,
444 'ipb_enable_autoblock' => $this->mEnableAutoblock,
445 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
446 'ipb_range_start' => $this->mRangeStart,
447 'ipb_range_end' => $this->mRangeEnd,
448 'ipb_deleted' => $this->mHideName,
449 'ipb_block_email' => $this->mBlockEmail
450 ), 'Block::insert', array( 'IGNORE' )
451 );
452 $affected = $dbw->affectedRows();
453
454 if ($affected)
455 $this->doRetroactiveAutoblock();
456
457 return $affected;
458 }
459
460 /**
461 * Retroactively autoblocks the last IP used by the user (if it is a user)
462 * blocked by this Block.
463 * @return bool Whether or not a retroactive autoblock was made.
464 */
465 function doRetroactiveAutoblock() {
466 $dbr = wfGetDB( DB_SLAVE );
467 #If autoblock is enabled, autoblock the LAST IP used
468 # - stolen shamelessly from CheckUser_body.php
469
470 if ($this->mEnableAutoblock && $this->mUser) {
471 wfDebug("Doing retroactive autoblocks for " . $this->mAddress . "\n");
472
473 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
474 $conds = array( 'rc_user_text' => $this->mAddress );
475
476 if ($this->mAngryAutoblock) {
477 // Block any IP used in the last 7 days. Up to five IPs.
478 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - (7*86400) ) );
479 $options['LIMIT'] = 5;
480 } else {
481 // Just the last IP used.
482 $options['LIMIT'] = 1;
483 }
484
485 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
486 __METHOD__ , $options);
487
488 if ( !$dbr->numRows( $res ) ) {
489 #No results, don't autoblock anything
490 wfDebug("No IP found to retroactively autoblock\n");
491 } else {
492 while ( $row = $dbr->fetchObject( $res ) ) {
493 if ( $row->rc_ip )
494 $this->doAutoblock( $row->rc_ip );
495 }
496 }
497 }
498 }
499
500 /**
501 * Checks whether a given IP is on the autoblock whitelist.
502 * @return bool
503 * @param string $autoblockip The IP to check
504 */
505 function isWhitelistedFromAutoblocks( $ip ) {
506 global $wgMemc;
507
508 // Try to get the autoblock_whitelist from the cache, as it's faster
509 // than getting the msg raw and explode()'ing it.
510 $key = wfMemc( 'ipb', 'autoblock', 'whitelist' );
511 $lines = $wgMemc->get( $key );
512 if ( !$lines ) {
513 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
514 }
515
516 wfDebug("Checking the autoblock whitelist..\n");
517
518 foreach( $lines as $line ) {
519 # List items only
520 if ( substr( $line, 0, 1 ) !== '*' ) {
521 continue;
522 }
523
524 $wlEntry = substr($line, 1);
525 $wlEntry = trim($wlEntry);
526
527 wfDebug("Checking $ip against $wlEntry...");
528
529 # Is the IP in this range?
530 if (IP::isInRange( $ip, $wlEntry )) {
531 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
532 return true;
533 } else {
534 wfDebug( " No match\n" );
535 }
536 }
537
538 return false;
539 }
540
541 /**
542 * Autoblocks the given IP, referring to this Block.
543 * @param string $autoblockip The IP to autoblock.
544 * @param bool $justInserted The main block was just inserted
545 * @return bool Whether or not an autoblock was inserted.
546 */
547 function doAutoblock( $autoblockip, $justInserted = false ) {
548 # If autoblocks are disabled, go away.
549 if ( !$this->mEnableAutoblock ) {
550 return;
551 }
552
553 # Check for presence on the autoblock whitelist
554 if (Block::isWhitelistedFromAutoblocks($autoblockip)) {
555 return;
556 }
557
558 ## Allow hooks to cancel the autoblock.
559 if (!wfRunHooks( 'AbortAutoblock', array( $autoblockip, &$this ) )) {
560 wfDebug( "Autoblock aborted by hook." );
561 return false;
562 }
563
564 # It's okay to autoblock. Go ahead and create/insert the block.
565
566 $ipblock = Block::newFromDB( $autoblockip );
567 if ( $ipblock ) {
568 # If the user is already blocked. Then check if the autoblock would
569 # exceed the user block. If it would exceed, then do nothing, else
570 # prolong block time
571 if ($this->mExpiry &&
572 ($this->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
573 return;
574 }
575 # Just update the timestamp
576 if ( !$justInserted ) {
577 $ipblock->updateTimestamp();
578 }
579 return;
580 } else {
581 $ipblock = new Block;
582 }
583
584 # Make a new block object with the desired properties
585 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
586 $ipblock->mAddress = $autoblockip;
587 $ipblock->mUser = 0;
588 $ipblock->mBy = $this->mBy;
589 $ipblock->mByName = $this->mByName;
590 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
591 $ipblock->mTimestamp = wfTimestampNow();
592 $ipblock->mAuto = 1;
593 $ipblock->mCreateAccount = $this->mCreateAccount;
594 # Continue suppressing the name if needed
595 $ipblock->mHideName = $this->mHideName;
596
597 # If the user is already blocked with an expiry date, we don't
598 # want to pile on top of that!
599 if($this->mExpiry) {
600 $ipblock->mExpiry = min ( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ));
601 } else {
602 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
603 }
604 # Insert it
605 return $ipblock->insert();
606 }
607
608 /**
609 * Check if a block has expired. Delete it if it is.
610 * @return bool
611 */
612 function deleteIfExpired()
613 {
614 $fname = 'Block::deleteIfExpired';
615 wfProfileIn( $fname );
616 if ( $this->isExpired() ) {
617 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
618 $this->delete();
619 $retVal = true;
620 } else {
621 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
622 $retVal = false;
623 }
624 wfProfileOut( $fname );
625 return $retVal;
626 }
627
628 /**
629 * Has the block expired?
630 * @return bool
631 */
632 function isExpired()
633 {
634 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
635 if ( !$this->mExpiry ) {
636 return false;
637 } else {
638 return wfTimestampNow() > $this->mExpiry;
639 }
640 }
641
642 /**
643 * Is the block address valid (i.e. not a null string?)
644 * @return bool
645 */
646 function isValid()
647 {
648 return $this->mAddress != '';
649 }
650
651 /**
652 * Update the timestamp on autoblocks.
653 */
654 function updateTimestamp()
655 {
656 if ( $this->mAuto ) {
657 $this->mTimestamp = wfTimestamp();
658 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
659
660 $dbw = wfGetDB( DB_MASTER );
661 $dbw->update( 'ipblocks',
662 array( /* SET */
663 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
664 'ipb_expiry' => $dbw->timestamp($this->mExpiry),
665 ), array( /* WHERE */
666 'ipb_address' => $this->mAddress
667 ), 'Block::updateTimestamp'
668 );
669 }
670 }
671
672 /*
673 function getIntegerAddr()
674 {
675 return $this->mIntegerAddr;
676 }
677
678 function getNetworkBits()
679 {
680 return $this->mNetworkBits;
681 }*/
682
683 /**
684 * Get the user id of the blocking sysop
685 * @return int
686 */
687 public function getBy() {
688 return $this->mBy;
689 }
690
691 /**
692 * Get the username of the blocking sysop
693 * @return string
694 */
695 function getByName()
696 {
697 return $this->mByName;
698 }
699
700 function forUpdate( $x = NULL ) {
701 return wfSetVar( $this->mForUpdate, $x );
702 }
703
704 function fromMaster( $x = NULL ) {
705 return wfSetVar( $this->mFromMaster, $x );
706 }
707
708 function getRedactedName() {
709 if ( $this->mAuto ) {
710 return '#' . $this->mId;
711 } else {
712 return $this->mAddress;
713 }
714 }
715
716 /**
717 * Encode expiry for DB
718 * @return string
719 * @param $expiry string Timestamp for expiry, or
720 * @param $db Database object
721 */
722 static function encodeExpiry( $expiry, $db ) {
723 if ( $expiry == '' || $expiry == Block::infinity() ) {
724 return Block::infinity();
725 } else {
726 return $db->timestamp( $expiry );
727 }
728 }
729
730 /**
731 * Decode expiry which has come from the DB
732 * @return string
733 * @param $expiry string Database expiry format
734 * @param $timestampType Requested timestamp format
735 */
736 static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
737 if ( $expiry == '' || $expiry == Block::infinity() ) {
738 return Block::infinity();
739 } else {
740 return wfTimestamp( $timestampType, $expiry );
741 }
742 }
743
744 /**
745 * Get a timestamp of the expiry for autoblocks
746 * @return string
747 */
748 static function getAutoblockExpiry( $timestamp )
749 {
750 global $wgAutoblockExpiry;
751 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
752 }
753
754 /**
755 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
756 * For example, 127.111.113.151/24 -> 127.111.113.0/24
757 * @param $range string IP address to normalize
758 * @return string
759 */
760 static function normaliseRange( $range ) {
761 $parts = explode( '/', $range );
762 if ( count( $parts ) == 2 ) {
763 // IPv6
764 if ( IP::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
765 $bits = $parts[1];
766 $ipint = IP::toUnsigned6( $parts[0] );
767 # Native 32 bit functions WONT work here!!!
768 # Convert to a padded binary number
769 $network = wfBaseConvert( $ipint, 10, 2, 128 );
770 # Truncate the last (128-$bits) bits and replace them with zeros
771 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
772 # Convert back to an integer
773 $network = wfBaseConvert( $network, 2, 10 );
774 # Reform octet address
775 $newip = IP::toOctet( $network );
776 $range = "$newip/{$parts[1]}";
777 } // IPv4
778 else if ( IP::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
779 $shift = 32 - $parts[1];
780 $ipint = IP::toUnsigned( $parts[0] );
781 $ipint = $ipint >> $shift << $shift;
782 $newip = long2ip( $ipint );
783 $range = "$newip/{$parts[1]}";
784 }
785 }
786 return $range;
787 }
788
789 /**
790 * Purge expired blocks from the ipblocks table
791 */
792 static function purgeExpired() {
793 $dbw = wfGetDB( DB_MASTER );
794 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
795 }
796
797 /**
798 * This is a special keyword for timestamps in PostgreSQL, and
799 * works with CHAR(14) as well because "i" sorts after all numbers.
800 * @return string
801 */
802 static function infinity() {
803 return 'infinity';
804 }
805
806 /**
807 * Convert a DB-encoded expiry into a real string that humans can read.
808 * @param
809 * @return string
810 * @todo @fixme This is nasty. Forces a msg on the expiry, which isn't what
811 * we want. Probably want to abstract out the number formatting so it can
812 * be used elsewhere (some bug I forgot and can't find at the moment)
813 */
814 static function formatExpiry( $encoded_expiry ) {
815
816 static $msg = null;
817
818 if( is_null( $msg ) ) {
819 $msg = array();
820 $keys = array( 'infiniteblock', 'expiringblock' );
821 foreach( $keys as $key ) {
822 $msg[$key] = wfMsgHtml( $key );
823 }
824 }
825
826 $expiry = Block::decodeExpiry( $encoded_expiry );
827 if ($expiry == 'infinity') {
828 $expirystr = $msg['infiniteblock'];
829 } else {
830 global $wgLang;
831 $expiretimestr = $wgLang->timeanddate( $expiry, true );
832 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array($expiretimestr) );
833 }
834
835 return $expirystr;
836 }
837
838 /**
839 * Convert a typed-in expiry time into something we can put into the database.
840 * @param $expiry_input string Whatever was typed into the form
841 * @return string More database friendly
842 */
843 static function parseExpiryInput( $expiry_input ) {
844 if ( $expiry_input == 'infinite' || $expiry_input == 'indefinite' ) {
845 $expiry = 'infinity';
846 } else {
847 $expiry = strtotime( $expiry_input );
848 if ($expiry < 0 || $expiry === false) {
849 return false;
850 }
851 }
852
853 return $expiry;
854 }
855
856 }