(bug 19441) Updated date formatting for Lithuanian
[mediawiki.git] / includes / Block.php
blob5c2b52ff7ff8e84d6f8947f7a414dd5a0ead9094
1 <?php
2 /**
3 * @file
4 * Blocks and bans object
5 */
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.
12 * Globals used: $wgAutoblockExpiry, $wgAntiLockFlags
14 * @todo This could be used everywhere, but it isn't.
16 class Block {
17 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
18 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock, $mHideName,
19 $mBlockEmail, $mByName, $mAngryAutoblock, $mAllowUsertalk;
20 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster;
22 const EB_KEEP_EXPIRED = 1;
23 const EB_FOR_UPDATE = 2;
24 const EB_RANGE_ONLY = 4;
26 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
27 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
28 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0 )
30 $this->mId = 0;
31 # Expand valid IPv6 addresses
32 $address = IP::sanitizeIP( $address );
33 $this->mAddress = $address;
34 $this->mUser = $user;
35 $this->mBy = $by;
36 $this->mReason = $reason;
37 $this->mTimestamp = wfTimestamp(TS_MW,$timestamp);
38 $this->mAuto = $auto;
39 $this->mAnonOnly = $anonOnly;
40 $this->mCreateAccount = $createAccount;
41 $this->mExpiry = self::decodeExpiry( $expiry );
42 $this->mEnableAutoblock = $enableAutoblock;
43 $this->mHideName = $hideName;
44 $this->mBlockEmail = $blockEmail;
45 $this->mAllowUsertalk = $allowUsertalk;
46 $this->mForUpdate = false;
47 $this->mFromMaster = false;
48 $this->mByName = false;
49 $this->mAngryAutoblock = false;
50 $this->initialiseRange();
53 /**
54 * Load a block from the database, using either the IP address or
55 * user ID. Tries the user ID first, and if that doesn't work, tries
56 * the address.
58 * @param $address String: IP address of user/anon
59 * @param $user Integer: user id of user
60 * @param $killExpired Boolean: delete expired blocks on load
61 * @return Block Object
63 public static function newFromDB( $address, $user = 0, $killExpired = true ) {
64 $block = new Block;
65 $block->load( $address, $user, $killExpired );
66 if ( $block->isValid() ) {
67 return $block;
68 } else {
69 return null;
73 /**
74 * Load a blocked user from their block id.
76 * @param $id Integer: Block id to search for
77 * @return Block object
79 public static function newFromID( $id ) {
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;
91 /**
92 * Check if two blocks are effectively equal
94 * @return Boolean
96 public function equals( Block $block ) {
97 return (
98 $this->mAddress == $block->mAddress
99 && $this->mUser == $block->mUser
100 && $this->mAuto == $block->mAuto
101 && $this->mAnonOnly == $block->mAnonOnly
102 && $this->mCreateAccount == $block->mCreateAccount
103 && $this->mExpiry == $block->mExpiry
104 && $this->mEnableAutoblock == $block->mEnableAutoblock
105 && $this->mHideName == $block->mHideName
106 && $this->mBlockEmail == $block->mBlockEmail
107 && $this->mAllowUsertalk == $block->mAllowUsertalk
108 && $this->mReason == $block->mReason
113 * Clear all member variables in the current object. Does not clear
114 * the block from the DB.
116 public function clear() {
117 $this->mAddress = $this->mReason = $this->mTimestamp = '';
118 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
119 $this->mEnableAutoblock = $this->mAuto = $this->mUser =
120 $this->mBy = $this->mHideName = $this->mBlockEmail = $this->mAllowUsertalk = 0;
121 $this->mByName = false;
125 * Get the DB object and set the reference parameter to the select options.
126 * The options array will contain FOR UPDATE if appropriate.
128 * @param $options Array
129 * @return Database
131 protected function &getDBOptions( &$options ) {
132 global $wgAntiLockFlags;
133 if ( $this->mForUpdate || $this->mFromMaster ) {
134 $db = wfGetDB( DB_MASTER );
135 if ( !$this->mForUpdate || ($wgAntiLockFlags & ALF_NO_BLOCK_LOCK) ) {
136 $options = array();
137 } else {
138 $options = array( 'FOR UPDATE' );
140 } else {
141 $db = wfGetDB( DB_SLAVE );
142 $options = array();
144 return $db;
148 * Get a block from the DB, with either the given address or the given username
150 * @param $address string The IP address of the user, or blank to skip IP blocks
151 * @param $user int The user ID, or zero for anonymous users
152 * @param $killExpired bool Whether to delete expired rows while loading
153 * @return Boolean: the user is blocked from editing
156 public function load( $address = '', $user = 0, $killExpired = true ) {
157 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
159 $options = array();
160 $db =& $this->getDBOptions( $options );
162 if ( 0 == $user && $address == '' ) {
163 # Invalid user specification, not blocked
164 $this->clear();
165 return false;
168 # Try user block
169 if ( $user ) {
170 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
171 __METHOD__, $options ) );
172 if ( $this->loadFromResult( $res, $killExpired ) ) {
173 return true;
177 # Try IP block
178 # TODO: improve performance by merging this query with the autoblock one
179 # Slightly tricky while handling killExpired as well
180 if ( $address ) {
181 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
182 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
183 if ( $this->loadFromResult( $res, $killExpired ) ) {
184 if ( $user && $this->mAnonOnly ) {
185 # Block is marked anon-only
186 # Whitelist this IP address against autoblocks and range blocks
187 # (but not account creation blocks -- bug 13611)
188 if( !$this->mCreateAccount ) {
189 $this->clear();
191 return false;
192 } else {
193 return true;
198 # Try range block
199 if ( $this->loadRange( $address, $killExpired, $user ) ) {
200 if ( $user && $this->mAnonOnly ) {
201 # Respect account creation blocks on logged-in users -- bug 13611
202 if( !$this->mCreateAccount ) {
203 $this->clear();
205 return false;
206 } else {
207 return true;
211 # Try autoblock
212 if ( $address ) {
213 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
214 if ( $user ) {
215 $conds['ipb_anon_only'] = 0;
217 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
218 if ( $this->loadFromResult( $res, $killExpired ) ) {
219 return true;
223 # Give up
224 $this->clear();
225 return false;
229 * Fill in member variables from a result wrapper
231 * @param $res ResultWrapper: row from the ipblocks table
232 * @param $killExpired Boolean: whether to delete expired rows while loading
233 * @return Boolean
235 protected function loadFromResult( ResultWrapper $res, $killExpired = true ) {
236 $ret = false;
237 if ( 0 != $res->numRows() ) {
238 # Get first block
239 $row = $res->fetchObject();
240 $this->initFromRow( $row );
242 if ( $killExpired ) {
243 # If requested, delete expired rows
244 do {
245 $killed = $this->deleteIfExpired();
246 if ( $killed ) {
247 $row = $res->fetchObject();
248 if ( $row ) {
249 $this->initFromRow( $row );
252 } while ( $killed && $row );
254 # If there were any left after the killing finished, return true
255 if ( $row ) {
256 $ret = true;
258 } else {
259 $ret = true;
262 $res->free();
263 return $ret;
267 * Search the database for any range blocks matching the given address, and
268 * load the row if one is found.
270 * @param $address String: IP address range
271 * @param $killExpired Boolean: whether to delete expired rows while loading
272 * @param $userid Integer: if not 0, then sets ipb_anon_only
273 * @return Boolean
275 public function loadRange( $address, $killExpired = true, $user = 0 ) {
276 $iaddr = IP::toHex( $address );
277 if ( $iaddr === false ) {
278 # Invalid address
279 return false;
282 # Only scan ranges which start in this /16, this improves search speed
283 # Blocks should not cross a /16 boundary.
284 $range = substr( $iaddr, 0, 4 );
286 $options = array();
287 $db =& $this->getDBOptions( $options );
288 $conds = array(
289 "ipb_range_start LIKE '$range%'",
290 "ipb_range_start <= '$iaddr'",
291 "ipb_range_end >= '$iaddr'"
294 if ( $user ) {
295 $conds['ipb_anon_only'] = 0;
298 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
299 $success = $this->loadFromResult( $res, $killExpired );
300 return $success;
304 * Given a database row from the ipblocks table, initialize
305 * member variables
307 * @param $row ResultWrapper: a row from the ipblocks table
309 public function initFromRow( $row ) {
310 $this->mAddress = $row->ipb_address;
311 $this->mReason = $row->ipb_reason;
312 $this->mTimestamp = wfTimestamp(TS_MW,$row->ipb_timestamp);
313 $this->mUser = $row->ipb_user;
314 $this->mBy = $row->ipb_by;
315 $this->mAuto = $row->ipb_auto;
316 $this->mAnonOnly = $row->ipb_anon_only;
317 $this->mCreateAccount = $row->ipb_create_account;
318 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
319 $this->mBlockEmail = $row->ipb_block_email;
320 $this->mAllowUsertalk = $row->ipb_allow_usertalk;
321 $this->mHideName = $row->ipb_deleted;
322 $this->mId = $row->ipb_id;
323 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
324 if ( isset( $row->user_name ) ) {
325 $this->mByName = $row->user_name;
326 } else {
327 $this->mByName = $row->ipb_by_text;
329 $this->mRangeStart = $row->ipb_range_start;
330 $this->mRangeEnd = $row->ipb_range_end;
334 * Once $mAddress has been set, get the range they came from.
335 * Wrapper for IP::parseRange
337 protected function initialiseRange() {
338 $this->mRangeStart = '';
339 $this->mRangeEnd = '';
341 if ( $this->mUser == 0 ) {
342 list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress );
347 * Delete the row from the IP blocks table.
349 * @return Boolean
351 public function delete() {
352 if ( wfReadOnly() ) {
353 return false;
355 if ( !$this->mId ) {
356 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
359 $dbw = wfGetDB( DB_MASTER );
360 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
361 return $dbw->affectedRows() > 0;
365 * Insert a block into the block table. Will fail if there is a conflicting
366 * block (same name and options) already in the database.
368 * @return Boolean: whether or not the insertion was successful.
370 public function insert() {
371 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
372 $dbw = wfGetDB( DB_MASTER );
374 $this->validateBlockParams();
375 $this->initialiseRange();
377 # Don't collide with expired blocks
378 Block::purgeExpired();
380 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
381 $dbw->insert( 'ipblocks',
382 array(
383 'ipb_id' => $ipb_id,
384 'ipb_address' => $this->mAddress,
385 'ipb_user' => $this->mUser,
386 'ipb_by' => $this->mBy,
387 'ipb_by_text' => $this->mByName,
388 'ipb_reason' => $this->mReason,
389 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
390 'ipb_auto' => $this->mAuto,
391 'ipb_anon_only' => $this->mAnonOnly,
392 'ipb_create_account' => $this->mCreateAccount,
393 'ipb_enable_autoblock' => $this->mEnableAutoblock,
394 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
395 'ipb_range_start' => $this->mRangeStart,
396 'ipb_range_end' => $this->mRangeEnd,
397 'ipb_deleted' => $this->mHideName,
398 'ipb_block_email' => $this->mBlockEmail,
399 'ipb_allow_usertalk' => $this->mAllowUsertalk
400 ), 'Block::insert', array( 'IGNORE' )
402 $affected = $dbw->affectedRows();
404 if ($affected)
405 $this->doRetroactiveAutoblock();
407 return (bool)$affected;
411 * Update a block in the DB with new parameters.
412 * The ID field needs to be loaded first.
414 public function update() {
415 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
416 $dbw = wfGetDB( DB_MASTER );
418 $this->validateBlockParams();
420 $dbw->update( 'ipblocks',
421 array(
422 'ipb_user' => $this->mUser,
423 'ipb_by' => $this->mBy,
424 'ipb_by_text' => $this->mByName,
425 'ipb_reason' => $this->mReason,
426 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
427 'ipb_auto' => $this->mAuto,
428 'ipb_anon_only' => $this->mAnonOnly,
429 'ipb_create_account' => $this->mCreateAccount,
430 'ipb_enable_autoblock' => $this->mEnableAutoblock,
431 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
432 'ipb_range_start' => $this->mRangeStart,
433 'ipb_range_end' => $this->mRangeEnd,
434 'ipb_deleted' => $this->mHideName,
435 'ipb_block_email' => $this->mBlockEmail,
436 'ipb_allow_usertalk' => $this->mAllowUsertalk ),
437 array( 'ipb_id' => $this->mId ),
438 'Block::update' );
440 return $dbw->affectedRows();
444 * Make sure all the proper members are set to sane values
445 * before adding/updating a block
447 protected function validateBlockParams() {
448 # Unset ipb_anon_only for user blocks, makes no sense
449 if ( $this->mUser ) {
450 $this->mAnonOnly = 0;
453 # Unset ipb_enable_autoblock for IP blocks, makes no sense
454 if ( !$this->mUser ) {
455 $this->mEnableAutoblock = 0;
458 # bug 18860: non-anon-only IP blocks should be allowed to block email
459 if ( !$this->mUser && $this->mAnonOnly ) {
460 $this->mBlockEmail = 0;
462 if( !$this->mByName ) {
463 if( $this->mBy ) {
464 $this->mByName = User::whoIs( $this->mBy );
465 } else {
466 global $wgUser;
467 $this->mByName = $wgUser->getName();
474 * Retroactively autoblocks the last IP used by the user (if it is a user)
475 * blocked by this Block.
477 * @return Boolean: whether or not a retroactive autoblock was made.
479 public function doRetroactiveAutoblock() {
480 $dbr = wfGetDB( DB_SLAVE );
481 #If autoblock is enabled, autoblock the LAST IP used
482 # - stolen shamelessly from CheckUser_body.php
484 if ($this->mEnableAutoblock && $this->mUser) {
485 wfDebug("Doing retroactive autoblocks for " . $this->mAddress . "\n");
487 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
488 $conds = array( 'rc_user_text' => $this->mAddress );
490 if ($this->mAngryAutoblock) {
491 // Block any IP used in the last 7 days. Up to five IPs.
492 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - (7*86400) ) );
493 $options['LIMIT'] = 5;
494 } else {
495 // Just the last IP used.
496 $options['LIMIT'] = 1;
499 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
500 __METHOD__ , $options);
502 if ( !$dbr->numRows( $res ) ) {
503 #No results, don't autoblock anything
504 wfDebug("No IP found to retroactively autoblock\n");
505 } else {
506 while ( $row = $dbr->fetchObject( $res ) ) {
507 if ( $row->rc_ip )
508 $this->doAutoblock( $row->rc_ip );
515 * Checks whether a given IP is on the autoblock whitelist.
517 * @param $ip String: The IP to check
518 * @return Boolean
520 public static function isWhitelistedFromAutoblocks( $ip ) {
521 global $wgMemc;
523 // Try to get the autoblock_whitelist from the cache, as it's faster
524 // than getting the msg raw and explode()'ing it.
525 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
526 $lines = $wgMemc->get( $key );
527 if ( !$lines ) {
528 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
529 $wgMemc->set( $key, $lines, 3600 * 24 );
532 wfDebug("Checking the autoblock whitelist..\n");
534 foreach( $lines as $line ) {
535 # List items only
536 if ( substr( $line, 0, 1 ) !== '*' ) {
537 continue;
540 $wlEntry = substr($line, 1);
541 $wlEntry = trim($wlEntry);
543 wfDebug("Checking $ip against $wlEntry...");
545 # Is the IP in this range?
546 if (IP::isInRange( $ip, $wlEntry )) {
547 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
548 return true;
549 } else {
550 wfDebug( " No match\n" );
554 return false;
558 * Autoblocks the given IP, referring to this Block.
560 * @param $autoblockIP String: the IP to autoblock.
561 * @param $justInserted Boolean: the main block was just inserted
562 * @return Boolean: whether or not an autoblock was inserted.
564 public function doAutoblock( $autoblockIP, $justInserted = false ) {
565 # If autoblocks are disabled, go away.
566 if ( !$this->mEnableAutoblock ) {
567 return;
570 # Check for presence on the autoblock whitelist
571 if (Block::isWhitelistedFromAutoblocks($autoblockIP)) {
572 return;
575 ## Allow hooks to cancel the autoblock.
576 if (!wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) )) {
577 wfDebug( "Autoblock aborted by hook.\n" );
578 return false;
581 # It's okay to autoblock. Go ahead and create/insert the block.
583 $ipblock = Block::newFromDB( $autoblockIP );
584 if ( $ipblock ) {
585 # If the user is already blocked. Then check if the autoblock would
586 # exceed the user block. If it would exceed, then do nothing, else
587 # prolong block time
588 if ($this->mExpiry &&
589 ($this->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
590 return;
592 # Just update the timestamp
593 if ( !$justInserted ) {
594 $ipblock->updateTimestamp();
596 return;
597 } else {
598 $ipblock = new Block;
601 # Make a new block object with the desired properties
602 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockIP . "\n" );
603 $ipblock->mAddress = $autoblockIP;
604 $ipblock->mUser = 0;
605 $ipblock->mBy = $this->mBy;
606 $ipblock->mByName = $this->mByName;
607 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
608 $ipblock->mTimestamp = wfTimestampNow();
609 $ipblock->mAuto = 1;
610 $ipblock->mCreateAccount = $this->mCreateAccount;
611 # Continue suppressing the name if needed
612 $ipblock->mHideName = $this->mHideName;
613 $ipblock->mAllowUsertalk = $this->mAllowUsertalk;
614 # If the user is already blocked with an expiry date, we don't
615 # want to pile on top of that!
616 if($this->mExpiry) {
617 $ipblock->mExpiry = min ( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ));
618 } else {
619 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
621 # Insert it
622 return $ipblock->insert();
626 * Check if a block has expired. Delete it if it is.
627 * @return Boolean
629 public function deleteIfExpired() {
630 $fname = 'Block::deleteIfExpired';
631 wfProfileIn( $fname );
632 if ( $this->isExpired() ) {
633 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
634 $this->delete();
635 $retVal = true;
636 } else {
637 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
638 $retVal = false;
640 wfProfileOut( $fname );
641 return $retVal;
645 * Has the block expired?
646 * @return Boolean
648 public function isExpired() {
649 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
650 if ( !$this->mExpiry ) {
651 return false;
652 } else {
653 return wfTimestampNow() > $this->mExpiry;
658 * Is the block address valid (i.e. not a null string?)
659 * @return Boolean
661 public function isValid() {
662 return $this->mAddress != '';
666 * Update the timestamp on autoblocks.
668 public function updateTimestamp() {
669 if ( $this->mAuto ) {
670 $this->mTimestamp = wfTimestamp();
671 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
673 $dbw = wfGetDB( DB_MASTER );
674 $dbw->update( 'ipblocks',
675 array( /* SET */
676 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
677 'ipb_expiry' => $dbw->timestamp($this->mExpiry),
678 ), array( /* WHERE */
679 'ipb_address' => $this->mAddress
680 ), 'Block::updateTimestamp'
686 * Get the user id of the blocking sysop
688 * @return Integer
690 public function getBy() {
691 return $this->mBy;
695 * Get the username of the blocking sysop
697 * @return String
699 public function getByName() {
700 return $this->mByName;
704 * Get/set the SELECT ... FOR UPDATE flag
706 public function forUpdate( $x = NULL ) {
707 return wfSetVar( $this->mForUpdate, $x );
711 * Get/set a flag determining whether the master is used for reads
713 public function fromMaster( $x = NULL ) {
714 return wfSetVar( $this->mFromMaster, $x );
718 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
719 * @return String
721 public function getRedactedName() {
722 if ( $this->mAuto ) {
723 return '#' . $this->mId;
724 } else {
725 return $this->mAddress;
730 * Encode expiry for DB
732 * @param $expiry String: timestamp for expiry, or
733 * @param $db Database object
734 * @return String
736 public static function encodeExpiry( $expiry, $db ) {
737 if ( $expiry == '' || $expiry == Block::infinity() ) {
738 return Block::infinity();
739 } else {
740 return $db->timestamp( $expiry );
745 * Decode expiry which has come from the DB
747 * @param $expiry String: Database expiry format
748 * @param $timestampType Requested timestamp format
749 * @return String
751 public static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
752 if ( $expiry == '' || $expiry == Block::infinity() ) {
753 return Block::infinity();
754 } else {
755 return wfTimestamp( $timestampType, $expiry );
760 * Get a timestamp of the expiry for autoblocks
762 * @return String
764 public static function getAutoblockExpiry( $timestamp ) {
765 global $wgAutoblockExpiry;
766 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
770 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
771 * For example, 127.111.113.151/24 -> 127.111.113.0/24
772 * @param $range String: IP address to normalize
773 * @return string
775 public static function normaliseRange( $range ) {
776 $parts = explode( '/', $range );
777 if ( count( $parts ) == 2 ) {
778 // IPv6
779 if ( IP::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
780 $bits = $parts[1];
781 $ipint = IP::toUnsigned6( $parts[0] );
782 # Native 32 bit functions WONT work here!!!
783 # Convert to a padded binary number
784 $network = wfBaseConvert( $ipint, 10, 2, 128 );
785 # Truncate the last (128-$bits) bits and replace them with zeros
786 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
787 # Convert back to an integer
788 $network = wfBaseConvert( $network, 2, 10 );
789 # Reform octet address
790 $newip = IP::toOctet( $network );
791 $range = "$newip/{$parts[1]}";
792 } // IPv4
793 else if ( IP::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
794 $shift = 32 - $parts[1];
795 $ipint = IP::toUnsigned( $parts[0] );
796 $ipint = $ipint >> $shift << $shift;
797 $newip = long2ip( $ipint );
798 $range = "$newip/{$parts[1]}";
801 return $range;
805 * Purge expired blocks from the ipblocks table
807 public static function purgeExpired() {
808 $dbw = wfGetDB( DB_MASTER );
809 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
813 * Get a value to insert into expiry field of the database when infinite expiry
814 * is desired. In principle this could be DBMS-dependant, but currently all
815 * supported DBMS's support the string "infinity", so we just use that.
817 * @return String
819 public static function infinity() {
820 # This is a special keyword for timestamps in PostgreSQL, and
821 # works with CHAR(14) as well because "i" sorts after all numbers.
822 return 'infinity';
826 * Convert a DB-encoded expiry into a real string that humans can read.
828 * @param $encoded_expiry String: Database encoded expiry time
829 * @return Html-escaped String
831 public static function formatExpiry( $encoded_expiry ) {
832 static $msg = null;
834 if( is_null( $msg ) ) {
835 $msg = array();
836 $keys = array( 'infiniteblock', 'expiringblock' );
837 foreach( $keys as $key ) {
838 $msg[$key] = wfMsgHtml( $key );
842 $expiry = Block::decodeExpiry( $encoded_expiry );
843 if ($expiry == 'infinity') {
844 $expirystr = $msg['infiniteblock'];
845 } else {
846 global $wgLang;
847 $expiredatestr = htmlspecialchars($wgLang->date( $expiry, true ));
848 $expiretimestr = htmlspecialchars($wgLang->time( $expiry, true ));
849 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
851 return $expirystr;
855 * Convert a typed-in expiry time into something we can put into the database.
856 * @param $expiry_input String: whatever was typed into the form
857 * @return String: more database friendly
859 public static function parseExpiryInput( $expiry_input ) {
860 if ( $expiry_input == 'infinite' || $expiry_input == 'indefinite' ) {
861 $expiry = 'infinity';
862 } else {
863 $expiry = strtotime( $expiry_input );
864 if ($expiry < 0 || $expiry === false) {
865 return false;
868 return $expiry;