Restored line accidentally removed in r70520
[mediawiki.git] / includes / Block.php
blobde0155554912e28bc336f73f72c935844efb921e
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, $byName = false )
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 = $byName;
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 );
67 if ( $block->isValid() ) {
68 return $block;
69 } else {
70 return null;
74 /**
75 * Load a blocked user from their block id.
77 * @param $id Integer: Block id to search for
78 * @return Block object
80 public static function newFromID( $id ) {
81 $dbr = wfGetDB( DB_SLAVE );
82 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
83 array( 'ipb_id' => $id ), __METHOD__ ) );
84 $block = new Block;
86 if ( $block->loadFromResult( $res ) ) {
87 return $block;
88 } else {
89 return null;
93 /**
94 * Check if two blocks are effectively equal
96 * @return Boolean
98 public function equals( Block $block ) {
99 return (
100 $this->mAddress == $block->mAddress
101 && $this->mUser == $block->mUser
102 && $this->mAuto == $block->mAuto
103 && $this->mAnonOnly == $block->mAnonOnly
104 && $this->mCreateAccount == $block->mCreateAccount
105 && $this->mExpiry == $block->mExpiry
106 && $this->mEnableAutoblock == $block->mEnableAutoblock
107 && $this->mHideName == $block->mHideName
108 && $this->mBlockEmail == $block->mBlockEmail
109 && $this->mAllowUsertalk == $block->mAllowUsertalk
110 && $this->mReason == $block->mReason
115 * Clear all member variables in the current object. Does not clear
116 * the block from the DB.
118 public function clear() {
119 $this->mAddress = $this->mReason = $this->mTimestamp = '';
120 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
121 $this->mEnableAutoblock = $this->mAuto = $this->mUser =
122 $this->mBy = $this->mHideName = $this->mBlockEmail = $this->mAllowUsertalk = 0;
123 $this->mByName = false;
127 * Get the DB object and set the reference parameter to the select options.
128 * The options array will contain FOR UPDATE if appropriate.
130 * @param $options Array
131 * @return Database
133 protected function &getDBOptions( &$options ) {
134 global $wgAntiLockFlags;
136 if ( $this->mForUpdate || $this->mFromMaster ) {
137 $db = wfGetDB( DB_MASTER );
138 if ( !$this->mForUpdate || ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK ) ) {
139 $options = array();
140 } else {
141 $options = array( 'FOR UPDATE' );
143 } else {
144 $db = wfGetDB( DB_SLAVE );
145 $options = array();
148 return $db;
152 * Get a block from the DB, with either the given address or the given username
154 * @param $address string The IP address of the user, or blank to skip IP blocks
155 * @param $user int The user ID, or zero for anonymous users
156 * @param $killExpired bool Whether to delete expired rows while loading
157 * @return Boolean: the user is blocked from editing
160 public function load( $address = '', $user = 0, $killExpired = true ) {
161 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
163 $options = array();
164 $db = $this->getDBOptions( $options );
166 if ( 0 == $user && $address === '' ) {
167 # Invalid user specification, not blocked
168 $this->clear();
170 return false;
173 # Try user block
174 if ( $user ) {
175 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
176 __METHOD__, $options ) );
178 if ( $this->loadFromResult( $res, $killExpired ) ) {
179 return true;
183 # Try IP block
184 # TODO: improve performance by merging this query with the autoblock one
185 # Slightly tricky while handling killExpired as well
186 if ( $address !== '' ) {
187 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
188 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
190 if ( $this->loadFromResult( $res, $killExpired ) ) {
191 if ( $user && $this->mAnonOnly ) {
192 # Block is marked anon-only
193 # Whitelist this IP address against autoblocks and range blocks
194 # (but not account creation blocks -- bug 13611)
195 if ( !$this->mCreateAccount ) {
196 $this->clear();
199 return false;
200 } else {
201 return true;
206 # Try range block
207 if ( $this->loadRange( $address, $killExpired, $user ) ) {
208 if ( $user && $this->mAnonOnly ) {
209 # Respect account creation blocks on logged-in users -- bug 13611
210 if ( !$this->mCreateAccount ) {
211 $this->clear();
214 return false;
215 } else {
216 return true;
220 # Try autoblock
221 if ( $address ) {
222 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
224 if ( $user ) {
225 $conds['ipb_anon_only'] = 0;
228 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
230 if ( $this->loadFromResult( $res, $killExpired ) ) {
231 return true;
235 # Give up
236 $this->clear();
237 return false;
241 * Fill in member variables from a result wrapper
243 * @param $res ResultWrapper: row from the ipblocks table
244 * @param $killExpired Boolean: whether to delete expired rows while loading
245 * @return Boolean
247 protected function loadFromResult( ResultWrapper $res, $killExpired = true ) {
248 $ret = false;
250 if ( 0 != $res->numRows() ) {
251 # Get first block
252 $row = $res->fetchObject();
253 $this->initFromRow( $row );
255 if ( $killExpired ) {
256 # If requested, delete expired rows
257 do {
258 $killed = $this->deleteIfExpired();
259 if ( $killed ) {
260 $row = $res->fetchObject();
261 if ( $row ) {
262 $this->initFromRow( $row );
265 } while ( $killed && $row );
267 # If there were any left after the killing finished, return true
268 if ( $row ) {
269 $ret = true;
271 } else {
272 $ret = true;
275 $res->free();
277 return $ret;
281 * Search the database for any range blocks matching the given address, and
282 * load the row if one is found.
284 * @param $address String: IP address range
285 * @param $killExpired Boolean: whether to delete expired rows while loading
286 * @param $user Integer: if not 0, then sets ipb_anon_only
287 * @return Boolean
289 public function loadRange( $address, $killExpired = true, $user = 0 ) {
290 $iaddr = IP::toHex( $address );
292 if ( $iaddr === false ) {
293 # Invalid address
294 return false;
297 # Only scan ranges which start in this /16, this improves search speed
298 # Blocks should not cross a /16 boundary.
299 $range = substr( $iaddr, 0, 4 );
301 $options = array();
302 $db = $this->getDBOptions( $options );
303 $conds = array(
304 'ipb_range_start' . $db->buildLike( $range, $db->anyString() ),
305 "ipb_range_start <= '$iaddr'",
306 "ipb_range_end >= '$iaddr'"
309 if ( $user ) {
310 $conds['ipb_anon_only'] = 0;
313 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
314 $success = $this->loadFromResult( $res, $killExpired );
316 return $success;
320 * Given a database row from the ipblocks table, initialize
321 * member variables
323 * @param $row ResultWrapper: a row from the ipblocks table
325 public function initFromRow( $row ) {
326 $this->mAddress = $row->ipb_address;
327 $this->mReason = $row->ipb_reason;
328 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
329 $this->mUser = $row->ipb_user;
330 $this->mBy = $row->ipb_by;
331 $this->mAuto = $row->ipb_auto;
332 $this->mAnonOnly = $row->ipb_anon_only;
333 $this->mCreateAccount = $row->ipb_create_account;
334 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
335 $this->mBlockEmail = $row->ipb_block_email;
336 $this->mAllowUsertalk = $row->ipb_allow_usertalk;
337 $this->mHideName = $row->ipb_deleted;
338 $this->mId = $row->ipb_id;
339 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
341 if ( isset( $row->user_name ) ) {
342 $this->mByName = $row->user_name;
343 } else {
344 $this->mByName = $row->ipb_by_text;
347 $this->mRangeStart = $row->ipb_range_start;
348 $this->mRangeEnd = $row->ipb_range_end;
352 * Once $mAddress has been set, get the range they came from.
353 * Wrapper for IP::parseRange
355 protected function initialiseRange() {
356 $this->mRangeStart = '';
357 $this->mRangeEnd = '';
359 if ( $this->mUser == 0 ) {
360 list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress );
365 * Delete the row from the IP blocks table.
367 * @return Boolean
369 public function delete() {
370 if ( wfReadOnly() ) {
371 return false;
374 if ( !$this->mId ) {
375 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
378 $dbw = wfGetDB( DB_MASTER );
379 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
381 return $dbw->affectedRows() > 0;
385 * Insert a block into the block table. Will fail if there is a conflicting
386 * block (same name and options) already in the database.
388 * @return Boolean: whether or not the insertion was successful.
390 public function insert( $dbw = null ) {
391 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
393 if ( $dbw === null )
394 $dbw = wfGetDB( DB_MASTER );
396 $this->validateBlockParams();
397 $this->initialiseRange();
399 # Don't collide with expired blocks
400 Block::purgeExpired();
402 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
403 $dbw->insert(
404 'ipblocks',
405 array(
406 'ipb_id' => $ipb_id,
407 'ipb_address' => $this->mAddress,
408 'ipb_user' => $this->mUser,
409 'ipb_by' => $this->mBy,
410 'ipb_by_text' => $this->mByName,
411 'ipb_reason' => $this->mReason,
412 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
413 'ipb_auto' => $this->mAuto,
414 'ipb_anon_only' => $this->mAnonOnly,
415 'ipb_create_account' => $this->mCreateAccount,
416 'ipb_enable_autoblock' => $this->mEnableAutoblock,
417 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
418 'ipb_range_start' => $this->mRangeStart,
419 'ipb_range_end' => $this->mRangeEnd,
420 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
421 'ipb_block_email' => $this->mBlockEmail,
422 'ipb_allow_usertalk' => $this->mAllowUsertalk
424 'Block::insert',
425 array( 'IGNORE' )
427 $affected = $dbw->affectedRows();
429 if ( $affected )
430 $this->doRetroactiveAutoblock();
432 return (bool)$affected;
436 * Update a block in the DB with new parameters.
437 * The ID field needs to be loaded first.
439 public function update() {
440 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
441 $dbw = wfGetDB( DB_MASTER );
443 $this->validateBlockParams();
445 $dbw->update(
446 'ipblocks',
447 array(
448 'ipb_user' => $this->mUser,
449 'ipb_by' => $this->mBy,
450 'ipb_by_text' => $this->mByName,
451 'ipb_reason' => $this->mReason,
452 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
453 'ipb_auto' => $this->mAuto,
454 'ipb_anon_only' => $this->mAnonOnly,
455 'ipb_create_account' => $this->mCreateAccount,
456 'ipb_enable_autoblock' => $this->mEnableAutoblock,
457 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
458 'ipb_range_start' => $this->mRangeStart,
459 'ipb_range_end' => $this->mRangeEnd,
460 'ipb_deleted' => $this->mHideName,
461 'ipb_block_email' => $this->mBlockEmail,
462 'ipb_allow_usertalk' => $this->mAllowUsertalk
464 array( 'ipb_id' => $this->mId ),
465 'Block::update'
468 return $dbw->affectedRows();
472 * Make sure all the proper members are set to sane values
473 * before adding/updating a block
475 protected function validateBlockParams() {
476 # Unset ipb_anon_only for user blocks, makes no sense
477 if ( $this->mUser ) {
478 $this->mAnonOnly = 0;
481 # Unset ipb_enable_autoblock for IP blocks, makes no sense
482 if ( !$this->mUser ) {
483 $this->mEnableAutoblock = 0;
486 # bug 18860: non-anon-only IP blocks should be allowed to block email
487 if ( !$this->mUser && $this->mAnonOnly ) {
488 $this->mBlockEmail = 0;
491 if ( !$this->mByName ) {
492 if ( $this->mBy ) {
493 $this->mByName = User::whoIs( $this->mBy );
494 } else {
495 global $wgUser;
496 $this->mByName = $wgUser->getName();
502 * Retroactively autoblocks the last IP used by the user (if it is a user)
503 * blocked by this Block.
505 * @return Boolean: whether or not a retroactive autoblock was made.
507 public function doRetroactiveAutoblock() {
508 $dbr = wfGetDB( DB_SLAVE );
509 # If autoblock is enabled, autoblock the LAST IP used
510 # - stolen shamelessly from CheckUser_body.php
512 if ( $this->mEnableAutoblock && $this->mUser ) {
513 wfDebug( "Doing retroactive autoblocks for " . $this->mAddress . "\n" );
515 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
516 $conds = array( 'rc_user_text' => $this->mAddress );
518 if ( $this->mAngryAutoblock ) {
519 // Block any IP used in the last 7 days. Up to five IPs.
520 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
521 $options['LIMIT'] = 5;
522 } else {
523 // Just the last IP used.
524 $options['LIMIT'] = 1;
527 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
528 __METHOD__ , $options );
530 if ( !$dbr->numRows( $res ) ) {
531 # No results, don't autoblock anything
532 wfDebug( "No IP found to retroactively autoblock\n" );
533 } else {
534 while ( $row = $dbr->fetchObject( $res ) ) {
535 if ( $row->rc_ip ) {
536 $this->doAutoblock( $row->rc_ip );
544 * Checks whether a given IP is on the autoblock whitelist.
546 * @param $ip String: The IP to check
547 * @return Boolean
549 public static function isWhitelistedFromAutoblocks( $ip ) {
550 global $wgMemc;
552 // Try to get the autoblock_whitelist from the cache, as it's faster
553 // than getting the msg raw and explode()'ing it.
554 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
555 $lines = $wgMemc->get( $key );
556 if ( !$lines ) {
557 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
558 $wgMemc->set( $key, $lines, 3600 * 24 );
561 wfDebug( "Checking the autoblock whitelist..\n" );
563 foreach ( $lines as $line ) {
564 # List items only
565 if ( substr( $line, 0, 1 ) !== '*' ) {
566 continue;
569 $wlEntry = substr( $line, 1 );
570 $wlEntry = trim( $wlEntry );
572 wfDebug( "Checking $ip against $wlEntry..." );
574 # Is the IP in this range?
575 if ( IP::isInRange( $ip, $wlEntry ) ) {
576 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
577 return true;
578 } else {
579 wfDebug( " No match\n" );
583 return false;
587 * Autoblocks the given IP, referring to this Block.
589 * @param $autoblockIP String: the IP to autoblock.
590 * @param $justInserted Boolean: the main block was just inserted
591 * @return Boolean: whether or not an autoblock was inserted.
593 public function doAutoblock( $autoblockIP, $justInserted = false ) {
594 # If autoblocks are disabled, go away.
595 if ( !$this->mEnableAutoblock ) {
596 return;
599 # Check for presence on the autoblock whitelist
600 if ( Block::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
601 return;
604 # # Allow hooks to cancel the autoblock.
605 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
606 wfDebug( "Autoblock aborted by hook.\n" );
607 return false;
610 # It's okay to autoblock. Go ahead and create/insert the block.
612 $ipblock = Block::newFromDB( $autoblockIP );
613 if ( $ipblock ) {
614 # If the user is already blocked. Then check if the autoblock would
615 # exceed the user block. If it would exceed, then do nothing, else
616 # prolong block time
617 if ( $this->mExpiry &&
618 ( $this->mExpiry < Block::getAutoblockExpiry( $ipblock->mTimestamp ) )
620 return;
623 # Just update the timestamp
624 if ( !$justInserted ) {
625 $ipblock->updateTimestamp();
628 return;
629 } else {
630 $ipblock = new Block;
633 # Make a new block object with the desired properties
634 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockIP . "\n" );
635 $ipblock->mAddress = $autoblockIP;
636 $ipblock->mUser = 0;
637 $ipblock->mBy = $this->mBy;
638 $ipblock->mByName = $this->mByName;
639 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
640 $ipblock->mTimestamp = wfTimestampNow();
641 $ipblock->mAuto = 1;
642 $ipblock->mCreateAccount = $this->mCreateAccount;
643 # Continue suppressing the name if needed
644 $ipblock->mHideName = $this->mHideName;
645 $ipblock->mAllowUsertalk = $this->mAllowUsertalk;
647 # If the user is already blocked with an expiry date, we don't
648 # want to pile on top of that!
649 if ( $this->mExpiry ) {
650 $ipblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ) );
651 } else {
652 $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
655 # Insert it
656 return $ipblock->insert();
660 * Check if a block has expired. Delete it if it is.
661 * @return Boolean
663 public function deleteIfExpired() {
664 wfProfileIn( __METHOD__ );
666 if ( $this->isExpired() ) {
667 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
668 $this->delete();
669 $retVal = true;
670 } else {
671 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
672 $retVal = false;
675 wfProfileOut( __METHOD__ );
676 return $retVal;
680 * Has the block expired?
681 * @return Boolean
683 public function isExpired() {
684 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
686 if ( !$this->mExpiry ) {
687 return false;
688 } else {
689 return wfTimestampNow() > $this->mExpiry;
694 * Is the block address valid (i.e. not a null string?)
695 * @return Boolean
697 public function isValid() {
698 return $this->mAddress != '';
702 * Update the timestamp on autoblocks.
704 public function updateTimestamp() {
705 if ( $this->mAuto ) {
706 $this->mTimestamp = wfTimestamp();
707 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
709 $dbw = wfGetDB( DB_MASTER );
710 $dbw->update( 'ipblocks',
711 array( /* SET */
712 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
713 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
714 ), array( /* WHERE */
715 'ipb_address' => $this->mAddress
716 ), 'Block::updateTimestamp'
722 * Get the user id of the blocking sysop
724 * @return Integer
726 public function getBy() {
727 return $this->mBy;
731 * Get the username of the blocking sysop
733 * @return String
735 public function getByName() {
736 return $this->mByName;
740 * Get/set the SELECT ... FOR UPDATE flag
742 public function forUpdate( $x = null ) {
743 return wfSetVar( $this->mForUpdate, $x );
747 * Get/set a flag determining whether the master is used for reads
749 public function fromMaster( $x = null ) {
750 return wfSetVar( $this->mFromMaster, $x );
754 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
755 * @return String
757 public function getRedactedName() {
758 if ( $this->mAuto ) {
759 return '#' . $this->mId;
760 } else {
761 return $this->mAddress;
766 * Encode expiry for DB
768 * @param $expiry String: timestamp for expiry, or
769 * @param $db Database object
770 * @return String
772 public static function encodeExpiry( $expiry, $db ) {
773 if ( $expiry == '' || $expiry == Block::infinity() ) {
774 return Block::infinity();
775 } else {
776 return $db->timestamp( $expiry );
781 * Decode expiry which has come from the DB
783 * @param $expiry String: Database expiry format
784 * @param $timestampType Requested timestamp format
785 * @return String
787 public static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
788 if ( $expiry == '' || $expiry == Block::infinity() ) {
789 return Block::infinity();
790 } else {
791 return wfTimestamp( $timestampType, $expiry );
796 * Get a timestamp of the expiry for autoblocks
798 * @return String
800 public static function getAutoblockExpiry( $timestamp ) {
801 global $wgAutoblockExpiry;
803 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
807 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
808 * For example, 127.111.113.151/24 -> 127.111.113.0/24
809 * @param $range String: IP address to normalize
810 * @return string
812 public static function normaliseRange( $range ) {
813 $parts = explode( '/', $range );
814 if ( count( $parts ) == 2 ) {
815 // IPv6
816 if ( IP::isIPv6( $range ) && $parts[1] >= 64 && $parts[1] <= 128 ) {
817 $bits = $parts[1];
818 $ipint = IP::toUnsigned6( $parts[0] );
819 # Native 32 bit functions WON'T work here!!!
820 # Convert to a padded binary number
821 $network = wfBaseConvert( $ipint, 10, 2, 128 );
822 # Truncate the last (128-$bits) bits and replace them with zeros
823 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
824 # Convert back to an integer
825 $network = wfBaseConvert( $network, 2, 10 );
826 # Reform octet address
827 $newip = IP::toOctet( $network );
828 $range = "$newip/{$parts[1]}";
829 } // IPv4
830 elseif ( IP::isIPv4( $range ) && $parts[1] >= 16 && $parts[1] <= 32 ) {
831 $shift = 32 - $parts[1];
832 $ipint = IP::toUnsigned( $parts[0] );
833 $ipint = $ipint >> $shift << $shift;
834 $newip = long2ip( $ipint );
835 $range = "$newip/{$parts[1]}";
839 return $range;
843 * Purge expired blocks from the ipblocks table
845 public static function purgeExpired() {
846 $dbw = wfGetDB( DB_MASTER );
847 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
851 * Get a value to insert into expiry field of the database when infinite expiry
852 * is desired. In principle this could be DBMS-dependant, but currently all
853 * supported DBMS's support the string "infinity", so we just use that.
855 * @return String
857 public static function infinity() {
858 # This is a special keyword for timestamps in PostgreSQL, and
859 # works with CHAR(14) as well because "i" sorts after all numbers.
860 return 'infinity';
864 * Convert a DB-encoded expiry into a real string that humans can read.
866 * @param $encoded_expiry String: Database encoded expiry time
867 * @return Html-escaped String
869 public static function formatExpiry( $encoded_expiry ) {
870 static $msg = null;
872 if ( is_null( $msg ) ) {
873 $msg = array();
874 $keys = array( 'infiniteblock', 'expiringblock' );
876 foreach ( $keys as $key ) {
877 $msg[$key] = wfMsgHtml( $key );
881 $expiry = Block::decodeExpiry( $encoded_expiry );
882 if ( $expiry == 'infinity' ) {
883 $expirystr = $msg['infiniteblock'];
884 } else {
885 global $wgLang;
886 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
887 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
888 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
891 return $expirystr;
895 * Convert a typed-in expiry time into something we can put into the database.
896 * @param $expiry_input String: whatever was typed into the form
897 * @return String: more database friendly
899 public static function parseExpiryInput( $expiry_input ) {
900 if ( $expiry_input == 'infinite' || $expiry_input == 'indefinite' ) {
901 $expiry = 'infinity';
902 } else {
903 $expiry = strtotime( $expiry_input );
905 if ( $expiry < 0 || $expiry === false ) {
906 return false;
910 return $expiry;