4 * Blocks and bans object
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.
15 * FIXME: this whole class is a cesspit, needs a complete rewrite
18 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
19 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock, $mHideName,
20 $mBlockEmail, $mByName, $mAngryAutoblock, $mAllowUsertalk;
21 private $mForUpdate, $mFromMaster;
29 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
30 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
31 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byName = false )
34 # Expand valid IPv6 addresses
35 $address = IP
::sanitizeIP( $address );
36 $this->mAddress
= $address;
39 $this->mReason
= $reason;
40 $this->mTimestamp
= wfTimestamp( TS_MW
, $timestamp );
42 $this->mAnonOnly
= $anonOnly;
43 $this->mCreateAccount
= $createAccount;
44 $this->mExpiry
= $expiry;
45 $this->mEnableAutoblock
= $enableAutoblock;
46 $this->mHideName
= $hideName;
47 $this->mBlockEmail
= $blockEmail;
48 $this->mAllowUsertalk
= $allowUsertalk;
49 $this->mForUpdate
= false;
50 $this->mFromMaster
= false;
51 $this->mByName
= $byName;
52 $this->mAngryAutoblock
= false;
53 $this->initialiseRange();
57 * Load a block from the database, using either the IP address or
58 * user ID. Tries the user ID first, and if that doesn't work, tries
61 * @param $address String: IP address of user/anon
62 * @param $user Integer: user id of user
63 * @param $killExpired Boolean: delete expired blocks on load
64 * @return Block Object
66 public static function newFromDB( $address, $user = 0, $killExpired = true ) {
68 $block->load( $address, $user, $killExpired );
69 if ( $block->isValid() ) {
77 * Load a blocked user from their block id.
79 * @param $id Integer: Block id to search for
80 * @return Block object
82 public static function newFromID( $id ) {
83 $dbr = wfGetDB( DB_SLAVE
);
84 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
85 array( 'ipb_id' => $id ), __METHOD__
) );
88 if ( $block->loadFromResult( $res ) ) {
96 * Check if two blocks are effectively equal
100 public function equals( Block
$block ) {
102 $this->mAddress
== $block->mAddress
103 && $this->mUser
== $block->mUser
104 && $this->mAuto
== $block->mAuto
105 && $this->mAnonOnly
== $block->mAnonOnly
106 && $this->mCreateAccount
== $block->mCreateAccount
107 && $this->mExpiry
== $block->mExpiry
108 && $this->mEnableAutoblock
== $block->mEnableAutoblock
109 && $this->mHideName
== $block->mHideName
110 && $this->mBlockEmail
== $block->mBlockEmail
111 && $this->mAllowUsertalk
== $block->mAllowUsertalk
112 && $this->mReason
== $block->mReason
117 * Clear all member variables in the current object. Does not clear
118 * the block from the DB.
120 public function clear() {
121 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
122 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
123 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
124 $this->mBy
= $this->mHideName
= $this->mBlockEmail
= $this->mAllowUsertalk
= 0;
125 $this->mByName
= false;
129 * Get the DB object and set the reference parameter to the select options.
130 * The options array will contain FOR UPDATE if appropriate.
132 * @param $options Array
135 protected function &getDBOptions( &$options ) {
136 global $wgAntiLockFlags;
138 if ( $this->mForUpdate ||
$this->mFromMaster
) {
139 $db = wfGetDB( DB_MASTER
);
140 if ( !$this->mForUpdate ||
( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) ) {
143 $options = array( 'FOR UPDATE' );
146 $db = wfGetDB( DB_SLAVE
);
154 * Get a block from the DB, with either the given address or the given username
156 * @param $address string The IP address of the user, or blank to skip IP blocks
157 * @param $user int The user ID, or zero for anonymous users
158 * @param $killExpired bool Whether to delete expired rows while loading
159 * @return Boolean: the user is blocked from editing
162 public function load( $address = '', $user = 0, $killExpired = true ) {
163 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
166 $db = $this->getDBOptions( $options );
168 if ( 0 == $user && $address === '' ) {
169 # Invalid user specification, not blocked
177 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
178 __METHOD__
, $options ) );
180 if ( $this->loadFromResult( $res, $killExpired ) ) {
186 # TODO: improve performance by merging this query with the autoblock one
187 # Slightly tricky while handling killExpired as well
188 if ( $address !== '' ) {
189 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
190 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
192 if ( $this->loadFromResult( $res, $killExpired ) ) {
193 if ( $user && $this->mAnonOnly
) {
194 # Block is marked anon-only
195 # Whitelist this IP address against autoblocks and range blocks
196 # (but not account creation blocks -- bug 13611)
197 if ( !$this->mCreateAccount
) {
209 if ( $this->loadRange( $address, $killExpired, $user ) ) {
210 if ( $user && $this->mAnonOnly
) {
211 # Respect account creation blocks on logged-in users -- bug 13611
212 if ( !$this->mCreateAccount
) {
224 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
227 $conds['ipb_anon_only'] = 0;
230 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
232 if ( $this->loadFromResult( $res, $killExpired ) ) {
243 * Fill in member variables from a result wrapper
245 * @param $res ResultWrapper: row from the ipblocks table
246 * @param $killExpired Boolean: whether to delete expired rows while loading
249 protected function loadFromResult( ResultWrapper
$res, $killExpired = true ) {
252 if ( 0 != $res->numRows() ) {
254 $row = $res->fetchObject();
255 $this->initFromRow( $row );
257 if ( $killExpired ) {
258 # If requested, delete expired rows
260 $killed = $this->deleteIfExpired();
262 $row = $res->fetchObject();
264 $this->initFromRow( $row );
267 } while ( $killed && $row );
269 # If there were any left after the killing finished, return true
283 * Search the database for any range blocks matching the given address, and
284 * load the row if one is found.
286 * @param $address String: IP address range
287 * @param $killExpired Boolean: whether to delete expired rows while loading
288 * @param $user Integer: if not 0, then sets ipb_anon_only
291 public function loadRange( $address, $killExpired = true, $user = 0 ) {
292 $iaddr = IP
::toHex( $address );
294 if ( $iaddr === false ) {
299 # Only scan ranges which start in this /16, this improves search speed
300 # Blocks should not cross a /16 boundary.
301 $range = substr( $iaddr, 0, 4 );
304 $db = $this->getDBOptions( $options );
306 'ipb_range_start' . $db->buildLike( $range, $db->anyString() ),
307 "ipb_range_start <= '$iaddr'",
308 "ipb_range_end >= '$iaddr'"
312 $conds['ipb_anon_only'] = 0;
315 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
316 $success = $this->loadFromResult( $res, $killExpired );
322 * Given a database row from the ipblocks table, initialize
325 * @param $row ResultWrapper: a row from the ipblocks table
327 public function initFromRow( $row ) {
328 $this->mAddress
= $row->ipb_address
;
329 $this->mReason
= $row->ipb_reason
;
330 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
331 $this->mUser
= $row->ipb_user
;
332 $this->mBy
= $row->ipb_by
;
333 $this->mAuto
= $row->ipb_auto
;
334 $this->mAnonOnly
= $row->ipb_anon_only
;
335 $this->mCreateAccount
= $row->ipb_create_account
;
336 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
337 $this->mBlockEmail
= $row->ipb_block_email
;
338 $this->mAllowUsertalk
= $row->ipb_allow_usertalk
;
339 $this->mHideName
= $row->ipb_deleted
;
340 $this->mId
= $row->ipb_id
;
341 $this->mExpiry
= $row->ipb_expiry
;
343 if ( isset( $row->user_name
) ) {
344 $this->mByName
= $row->user_name
;
346 $this->mByName
= $row->ipb_by_text
;
349 $this->mRangeStart
= $row->ipb_range_start
;
350 $this->mRangeEnd
= $row->ipb_range_end
;
354 * Once $mAddress has been set, get the range they came from.
355 * Wrapper for IP::parseRange
357 protected function initialiseRange() {
358 $this->mRangeStart
= '';
359 $this->mRangeEnd
= '';
361 if ( $this->mUser
== 0 ) {
362 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
367 * Delete the row from the IP blocks table.
371 public function delete() {
372 if ( wfReadOnly() ) {
377 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
380 $dbw = wfGetDB( DB_MASTER
);
381 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
383 return $dbw->affectedRows() > 0;
387 * Insert a block into the block table. Will fail if there is a conflicting
388 * block (same name and options) already in the database.
390 * @return Boolean: whether or not the insertion was successful.
392 public function insert( $dbw = null ) {
393 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
396 $dbw = wfGetDB( DB_MASTER
);
398 $this->validateBlockParams();
399 $this->initialiseRange();
401 # Don't collide with expired blocks
402 Block
::purgeExpired();
404 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
409 'ipb_address' => $this->mAddress
,
410 'ipb_user' => $this->mUser
,
411 'ipb_by' => $this->mBy
,
412 'ipb_by_text' => $this->mByName
,
413 'ipb_reason' => $this->mReason
,
414 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
415 'ipb_auto' => $this->mAuto
,
416 'ipb_anon_only' => $this->mAnonOnly
,
417 'ipb_create_account' => $this->mCreateAccount
,
418 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
419 'ipb_expiry' => $dbw->encodeExpiry( $this->mExpiry
),
420 'ipb_range_start' => $this->mRangeStart
,
421 'ipb_range_end' => $this->mRangeEnd
,
422 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
423 'ipb_block_email' => $this->mBlockEmail
,
424 'ipb_allow_usertalk' => $this->mAllowUsertalk
429 $affected = $dbw->affectedRows();
432 $this->doRetroactiveAutoblock();
434 return (bool)$affected;
438 * Update a block in the DB with new parameters.
439 * The ID field needs to be loaded first.
441 public function update() {
442 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
443 $dbw = wfGetDB( DB_MASTER
);
445 $this->validateBlockParams();
450 'ipb_user' => $this->mUser
,
451 'ipb_by' => $this->mBy
,
452 'ipb_by_text' => $this->mByName
,
453 'ipb_reason' => $this->mReason
,
454 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
455 'ipb_auto' => $this->mAuto
,
456 'ipb_anon_only' => $this->mAnonOnly
,
457 'ipb_create_account' => $this->mCreateAccount
,
458 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
459 'ipb_expiry' => $dbw->encodeExpiry( $this->mExpiry
),
460 'ipb_range_start' => $this->mRangeStart
,
461 'ipb_range_end' => $this->mRangeEnd
,
462 'ipb_deleted' => $this->mHideName
,
463 'ipb_block_email' => $this->mBlockEmail
,
464 'ipb_allow_usertalk' => $this->mAllowUsertalk
466 array( 'ipb_id' => $this->mId
),
470 return $dbw->affectedRows();
474 * Make sure all the proper members are set to sane values
475 * before adding/updating a block
477 protected function validateBlockParams() {
478 # Unset ipb_anon_only for user blocks, makes no sense
479 if ( $this->mUser
) {
480 $this->mAnonOnly
= 0;
483 # Unset ipb_enable_autoblock for IP blocks, makes no sense
484 if ( !$this->mUser
) {
485 $this->mEnableAutoblock
= 0;
488 # bug 18860: non-anon-only IP blocks should be allowed to block email
489 if ( !$this->mUser
&& $this->mAnonOnly
) {
490 $this->mBlockEmail
= 0;
493 if ( !$this->mByName
) {
495 $this->mByName
= User
::whoIs( $this->mBy
);
498 $this->mByName
= $wgUser->getName();
504 * Retroactively autoblocks the last IP used by the user (if it is a user)
505 * blocked by this Block.
507 * @return Boolean: whether or not a retroactive autoblock was made.
509 public function doRetroactiveAutoblock() {
510 $dbr = wfGetDB( DB_SLAVE
);
511 # If autoblock is enabled, autoblock the LAST IP used
512 # - stolen shamelessly from CheckUser_body.php
514 if ( $this->mEnableAutoblock
&& $this->mUser
) {
515 wfDebug( "Doing retroactive autoblocks for " . $this->mAddress
. "\n" );
517 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
518 $conds = array( 'rc_user_text' => $this->mAddress
);
520 if ( $this->mAngryAutoblock
) {
521 // Block any IP used in the last 7 days. Up to five IPs.
522 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
523 $options['LIMIT'] = 5;
525 // Just the last IP used.
526 $options['LIMIT'] = 1;
529 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
530 __METHOD__
, $options );
532 if ( !$dbr->numRows( $res ) ) {
533 # No results, don't autoblock anything
534 wfDebug( "No IP found to retroactively autoblock\n" );
536 foreach ( $res as $row ) {
538 $this->doAutoblock( $row->rc_ip
);
546 * Checks whether a given IP is on the autoblock whitelist.
548 * @param $ip String: The IP to check
551 public static function isWhitelistedFromAutoblocks( $ip ) {
554 // Try to get the autoblock_whitelist from the cache, as it's faster
555 // than getting the msg raw and explode()'ing it.
556 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
557 $lines = $wgMemc->get( $key );
559 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
560 $wgMemc->set( $key, $lines, 3600 * 24 );
563 wfDebug( "Checking the autoblock whitelist..\n" );
565 foreach ( $lines as $line ) {
567 if ( substr( $line, 0, 1 ) !== '*' ) {
571 $wlEntry = substr( $line, 1 );
572 $wlEntry = trim( $wlEntry );
574 wfDebug( "Checking $ip against $wlEntry..." );
576 # Is the IP in this range?
577 if ( IP
::isInRange( $ip, $wlEntry ) ) {
578 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
581 wfDebug( " No match\n" );
589 * Autoblocks the given IP, referring to this Block.
591 * @param $autoblockIP String: the IP to autoblock.
592 * @param $justInserted Boolean: the main block was just inserted
593 * @return Boolean: whether or not an autoblock was inserted.
595 public function doAutoblock( $autoblockIP, $justInserted = false ) {
596 # If autoblocks are disabled, go away.
597 if ( !$this->mEnableAutoblock
) {
601 # Check for presence on the autoblock whitelist
602 if ( Block
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
606 # # Allow hooks to cancel the autoblock.
607 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
608 wfDebug( "Autoblock aborted by hook.\n" );
612 # It's okay to autoblock. Go ahead and create/insert the block.
614 $ipblock = Block
::newFromDB( $autoblockIP );
616 # If the user is already blocked. Then check if the autoblock would
617 # exceed the user block. If it would exceed, then do nothing, else
619 if ( $this->mExpiry
&&
620 ( $this->mExpiry
< Block
::getAutoblockExpiry( $ipblock->mTimestamp
) )
625 # Just update the timestamp
626 if ( !$justInserted ) {
627 $ipblock->updateTimestamp();
632 $ipblock = new Block
;
635 # Make a new block object with the desired properties
636 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockIP . "\n" );
637 $ipblock->mAddress
= $autoblockIP;
639 $ipblock->mBy
= $this->mBy
;
640 $ipblock->mByName
= $this->mByName
;
641 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
642 $ipblock->mTimestamp
= wfTimestampNow();
644 $ipblock->mCreateAccount
= $this->mCreateAccount
;
645 # Continue suppressing the name if needed
646 $ipblock->mHideName
= $this->mHideName
;
647 $ipblock->mAllowUsertalk
= $this->mAllowUsertalk
;
649 # If the user is already blocked with an expiry date, we don't
650 # want to pile on top of that!
651 if ( $this->mExpiry
) {
652 $ipblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
) );
654 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
658 return $ipblock->insert();
662 * Check if a block has expired. Delete it if it is.
665 public function deleteIfExpired() {
666 wfProfileIn( __METHOD__
);
668 if ( $this->isExpired() ) {
669 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
673 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
677 wfProfileOut( __METHOD__
);
682 * Has the block expired?
685 public function isExpired() {
686 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
688 if ( !$this->mExpiry
) {
691 return wfTimestampNow() > $this->mExpiry
;
696 * Is the block address valid (i.e. not a null string?)
699 public function isValid() {
700 return $this->mAddress
!= '';
704 * Update the timestamp on autoblocks.
706 public function updateTimestamp() {
707 if ( $this->mAuto
) {
708 $this->mTimestamp
= wfTimestamp();
709 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
711 $dbw = wfGetDB( DB_MASTER
);
712 $dbw->update( 'ipblocks',
714 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
715 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
716 ), array( /* WHERE */
717 'ipb_address' => $this->mAddress
718 ), 'Block::updateTimestamp'
724 * Get the user id of the blocking sysop
728 public function getBy() {
733 * Get the username of the blocking sysop
737 public function getByName() {
738 return $this->mByName
;
742 * Get/set the SELECT ... FOR UPDATE flag
744 public function forUpdate( $x = null ) {
745 return wfSetVar( $this->mForUpdate
, $x );
749 * Get/set a flag determining whether the master is used for reads
751 public function fromMaster( $x = null ) {
752 return wfSetVar( $this->mFromMaster
, $x );
756 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
757 * @return String, text is escaped
759 public function getRedactedName() {
760 if ( $this->mAuto
) {
761 return HTML
::rawElement(
763 array( 'class' => 'mw-autoblockid' ),
764 wfMessage( 'autoblockid', $this->mId
)
767 return htmlspecialchars( $this->mAddress
);
772 * Encode expiry for DB
774 * @param $expiry String: timestamp for expiry, or
775 * @param $db Database object
777 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
779 public static function encodeExpiry( $expiry, $db ) {
780 return $db->encodeExpiry( $expiry );
784 * Decode expiry which has come from the DB
786 * @param $expiry String: Database expiry format
787 * @param $timestampType Requested timestamp format
789 * @deprecated since 1.18; use $wgLang->decodeExpiry() instead
791 public static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
793 return $wgContLang->formatExpiry( $expiry, $timestampType );
797 * Get a timestamp of the expiry for autoblocks
801 public static function getAutoblockExpiry( $timestamp ) {
802 global $wgAutoblockExpiry;
804 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
808 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
809 * For example, 127.111.113.151/24 -> 127.111.113.0/24
810 * @param $range String: IP address to normalize
812 * @deprecated since 1.18, call IP::sanitizeRange() directly
814 public static function normaliseRange( $range ) {
815 return IP
::sanitizeRange( $range );
819 * Purge expired blocks from the ipblocks table
821 public static function purgeExpired() {
822 $dbw = wfGetDB( DB_MASTER
);
823 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
827 * Get a value to insert into expiry field of the database when infinite expiry
829 * @deprecated since 1.18, call $dbr->getInfinity() directly
832 public static function infinity() {
833 return wfGetDB( DB_SLAVE
)->getInfinity();
837 * Convert a DB-encoded expiry into a real string that humans can read.
839 * @param $encoded_expiry String: Database encoded expiry time
840 * @return Html-escaped String
841 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
843 public static function formatExpiry( $encoded_expiry ) {
847 if ( is_null( $msg ) ) {
849 $keys = array( 'infiniteblock', 'expiringblock' );
851 foreach ( $keys as $key ) {
852 $msg[$key] = wfMsgHtml( $key );
856 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW
);
857 if ( $expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
858 $expirystr = $msg['infiniteblock'];
861 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
862 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
863 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
869 # FIXME: everything above here is a mess, needs much cleaning up
872 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
873 * ("24 May 2034"), into an absolute timestamp we can put into the database.
874 * @param $expiry String: whatever was typed into the form
875 * @return String: timestamp or "infinity" string for th DB implementation
876 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
878 public static function parseExpiryInput( $expiry ) {
879 wfDeprecated( __METHOD__
);
880 return SpecialBlock
::parseExpiryInput( $expiry );
884 * Given a target and the target's type, get an existing Block object if possible.
885 * Note that passing an IP address will get an applicable rangeblock if the IP is
886 * not individually blocked but falls within that range
887 * TODO: check that that fallback handles nested rangeblocks nicely (should return
889 * @param $target String|User|Int a block target, which may be one of several types:
890 * * A user to block, in which case $target will be a User
891 * * An IP to block, in which case $target will be a User generated by using
892 * User::newFromName( $ip, false ) to turn off name validation
893 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
894 * * The ID of an existing block, in which case $target will be an Int
895 * @param $type Block::TYPE_ constant the type of block as described above
896 * @return Block|null (null if the target is not blocked)
898 public static function newFromTargetAndType( $target, $type ){
899 if( $target instanceof User
){
900 if( $type == Block
::TYPE_IP
){
901 return Block
::newFromDB( $target->getName(), 0 );
902 } elseif( $type == Block
::TYPE_USER
) {
903 return Block
::newFromDB( '', $target->getId() );
905 # Should be unreachable;
909 } elseif( $type == Block
::TYPE_RANGE
){
910 return Block
::newFromDB( $target, 0 );
912 } elseif( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
){
913 return Block
::newFromID( $target );
920 public static function newFromTarget( $target ){
921 list( $target, $type ) = self
::parseTarget( $target );
922 return self
::newFromTargetAndType( $target, $type );
926 * From an existing Block, get the target and the type of target. Note that it is
927 * always safe to treat the target as a string; for User objects this will return
928 * User::__toString() which in turn gives User::getName().
929 * @return array( User|String, Block::TYPE_ constant )
931 public static function parseTarget( $target ){
932 $target = trim( $target );
934 $userObj = User
::newFromName( $target );
935 if( $userObj instanceof User
){
936 return array( $userObj, Block
::TYPE_USER
);
938 } elseif( IP
::isValid( $target ) ){
939 # We can still create a User if it's an IP address, but we need to turn
940 # off validation checking (which would exclude IP addresses)
942 User
::newFromName( IP
::sanitizeIP( $target ), false ),
946 } elseif( IP
::isValidBlock( $target ) ){
947 # Can't create a User from an IP range
948 return array( Block
::normaliseRange( $target ), Block
::TYPE_RANGE
);
950 } elseif( preg_match( '/^#\d+$/', $target ) ){
951 # Autoblock reference in the form "#12345"
952 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
954 } elseif( preg_match( '/^\d+$/', $target ) ){
955 # Block id reference as a pure number
956 return array( $target, Block
::TYPE_ID
);
961 * Get the target and target type for this particular Block. Note that for autoblocks,
962 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
964 * @return array( User|String, Block::TYPE_ constant )
965 * FIXME: this should be an integral part of the Block member variables
967 public function getTargetAndType(){
968 list( $target, $type ) = self
::parseTarget( $this->mAddress
);
970 # Check whether it's an autoblock
972 $type = self
::TYPE_AUTO
;
975 return array( $target, $type );
978 public function getType(){
979 list( /*...*/, $type ) = $this->getTargetAndType();
983 public function getTarget(){
984 list( $target, /*...*/ ) = $this->getTargetAndType();