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;
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->mFromMaster
= false;
50 $this->mByName
= $byName;
51 $this->mAngryAutoblock
= false;
52 $this->initialiseRange();
56 * Load a block from the database, using either the IP address or
57 * user ID. Tries the user ID first, and if that doesn't work, tries
60 * @param $address String: IP address of user/anon
61 * @param $user Integer: user id of user
62 * @param $killExpired Boolean: delete expired blocks on load
63 * @return Block Object
65 public static function newFromDB( $address, $user = 0, $killExpired = true ) {
67 $block->load( $address, $user, $killExpired );
68 if ( $block->isValid() ) {
76 * Load a blocked user from their block id.
78 * @param $id Integer: Block id to search for
79 * @return Block object
81 public static function newFromID( $id ) {
82 $dbr = wfGetDB( DB_SLAVE
);
83 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
84 array( 'ipb_id' => $id ), __METHOD__
) );
87 if ( $block->loadFromResult( $res ) ) {
95 * Check if two blocks are effectively equal
99 public function equals( Block
$block ) {
101 $this->mAddress
== $block->mAddress
102 && $this->mUser
== $block->mUser
103 && $this->mAuto
== $block->mAuto
104 && $this->mAnonOnly
== $block->mAnonOnly
105 && $this->mCreateAccount
== $block->mCreateAccount
106 && $this->mExpiry
== $block->mExpiry
107 && $this->mEnableAutoblock
== $block->mEnableAutoblock
108 && $this->mHideName
== $block->mHideName
109 && $this->mBlockEmail
== $block->mBlockEmail
110 && $this->mAllowUsertalk
== $block->mAllowUsertalk
111 && $this->mReason
== $block->mReason
116 * Clear all member variables in the current object. Does not clear
117 * the block from the DB.
119 public function clear() {
120 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
121 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
122 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
123 $this->mBy
= $this->mHideName
= $this->mBlockEmail
= $this->mAllowUsertalk
= 0;
124 $this->mByName
= false;
128 * Get a block from the DB, with either the given address or the given username
130 * @param $address string The IP address of the user, or blank to skip IP blocks
131 * @param $user int The user ID, or zero for anonymous users
132 * @param $killExpired bool Whether to delete expired rows while loading
133 * @return Boolean: the user is blocked from editing
136 public function load( $address = '', $user = 0, $killExpired = true ) {
137 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
139 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
141 if ( 0 == $user && $address === '' ) {
142 # Invalid user specification, not blocked
150 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
153 if ( $this->loadFromResult( $res, $killExpired ) ) {
159 # TODO: improve performance by merging this query with the autoblock one
160 # Slightly tricky while handling killExpired as well
161 if ( $address !== '' ) {
162 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
163 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
165 if ( $this->loadFromResult( $res, $killExpired ) ) {
166 if ( $user && $this->mAnonOnly
) {
167 # Block is marked anon-only
168 # Whitelist this IP address against autoblocks and range blocks
169 # (but not account creation blocks -- bug 13611)
170 if ( !$this->mCreateAccount
) {
182 if ( $this->loadRange( $address, $killExpired, $user ) ) {
183 if ( $user && $this->mAnonOnly
) {
184 # Respect account creation blocks on logged-in users -- bug 13611
185 if ( !$this->mCreateAccount
) {
197 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
200 $conds['ipb_anon_only'] = 0;
203 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
205 if ( $this->loadFromResult( $res, $killExpired ) ) {
216 * Fill in member variables from a result wrapper
218 * @param $res ResultWrapper: row from the ipblocks table
219 * @param $killExpired Boolean: whether to delete expired rows while loading
222 protected function loadFromResult( ResultWrapper
$res, $killExpired = true ) {
225 if ( 0 != $res->numRows() ) {
227 $row = $res->fetchObject();
228 $this->initFromRow( $row );
230 if ( $killExpired ) {
231 # If requested, delete expired rows
233 $killed = $this->deleteIfExpired();
235 $row = $res->fetchObject();
237 $this->initFromRow( $row );
240 } while ( $killed && $row );
242 # If there were any left after the killing finished, return true
256 * Search the database for any range blocks matching the given address, and
257 * load the row if one is found.
259 * @param $address String: IP address range
260 * @param $killExpired Boolean: whether to delete expired rows while loading
261 * @param $user Integer: if not 0, then sets ipb_anon_only
264 public function loadRange( $address, $killExpired = true, $user = 0 ) {
265 $iaddr = IP
::toHex( $address );
267 if ( $iaddr === false ) {
272 # Only scan ranges which start in this /16, this improves search speed
273 # Blocks should not cross a /16 boundary.
274 $range = substr( $iaddr, 0, 4 );
276 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
278 'ipb_range_start' . $db->buildLike( $range, $db->anyString() ),
279 "ipb_range_start <= '$iaddr'",
280 "ipb_range_end >= '$iaddr'"
284 $conds['ipb_anon_only'] = 0;
287 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
) );
288 $success = $this->loadFromResult( $res, $killExpired );
294 * Given a database row from the ipblocks table, initialize
297 * @param $row ResultWrapper: a row from the ipblocks table
299 public function initFromRow( $row ) {
300 $this->mAddress
= $row->ipb_address
;
301 $this->mReason
= $row->ipb_reason
;
302 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
303 $this->mUser
= $row->ipb_user
;
304 $this->mBy
= $row->ipb_by
;
305 $this->mAuto
= $row->ipb_auto
;
306 $this->mAnonOnly
= $row->ipb_anon_only
;
307 $this->mCreateAccount
= $row->ipb_create_account
;
308 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
309 $this->mBlockEmail
= $row->ipb_block_email
;
310 $this->mAllowUsertalk
= $row->ipb_allow_usertalk
;
311 $this->mHideName
= $row->ipb_deleted
;
312 $this->mId
= $row->ipb_id
;
313 $this->mExpiry
= $row->ipb_expiry
;
315 if ( isset( $row->user_name
) ) {
316 $this->mByName
= $row->user_name
;
318 $this->mByName
= $row->ipb_by_text
;
321 $this->mRangeStart
= $row->ipb_range_start
;
322 $this->mRangeEnd
= $row->ipb_range_end
;
326 * Once $mAddress has been set, get the range they came from.
327 * Wrapper for IP::parseRange
329 protected function initialiseRange() {
330 $this->mRangeStart
= '';
331 $this->mRangeEnd
= '';
333 if ( $this->mUser
== 0 ) {
334 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
339 * Delete the row from the IP blocks table.
343 public function delete() {
344 if ( wfReadOnly() ) {
349 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
352 $dbw = wfGetDB( DB_MASTER
);
353 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
355 return $dbw->affectedRows() > 0;
359 * Insert a block into the block table. Will fail if there is a conflicting
360 * block (same name and options) already in the database.
362 * @return Boolean: whether or not the insertion was successful.
364 public function insert( $dbw = null ) {
365 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
368 $dbw = wfGetDB( DB_MASTER
);
370 $this->validateBlockParams();
371 $this->initialiseRange();
373 # Don't collide with expired blocks
374 Block
::purgeExpired();
376 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
381 'ipb_address' => $this->mAddress
,
382 'ipb_user' => $this->mUser
,
383 'ipb_by' => $this->mBy
,
384 'ipb_by_text' => $this->mByName
,
385 'ipb_reason' => $this->mReason
,
386 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
387 'ipb_auto' => $this->mAuto
,
388 'ipb_anon_only' => $this->mAnonOnly
,
389 'ipb_create_account' => $this->mCreateAccount
,
390 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
391 'ipb_expiry' => $dbw->encodeExpiry( $this->mExpiry
),
392 'ipb_range_start' => $this->mRangeStart
,
393 'ipb_range_end' => $this->mRangeEnd
,
394 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
395 'ipb_block_email' => $this->mBlockEmail
,
396 'ipb_allow_usertalk' => $this->mAllowUsertalk
401 $affected = $dbw->affectedRows();
404 $this->doRetroactiveAutoblock();
406 return (bool)$affected;
410 * Update a block in the DB with new parameters.
411 * The ID field needs to be loaded first.
413 public function update() {
414 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
415 $dbw = wfGetDB( DB_MASTER
);
417 $this->validateBlockParams();
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' => $dbw->encodeExpiry( $this->mExpiry
),
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
438 array( 'ipb_id' => $this->mId
),
442 return $dbw->affectedRows();
446 * Make sure all the proper members are set to sane values
447 * before adding/updating a block
449 protected function validateBlockParams() {
450 # Unset ipb_anon_only for user blocks, makes no sense
451 if ( $this->mUser
) {
452 $this->mAnonOnly
= 0;
455 # Unset ipb_enable_autoblock for IP blocks, makes no sense
456 if ( !$this->mUser
) {
457 $this->mEnableAutoblock
= 0;
460 # bug 18860: non-anon-only IP blocks should be allowed to block email
461 if ( !$this->mUser
&& $this->mAnonOnly
) {
462 $this->mBlockEmail
= 0;
465 if ( !$this->mByName
) {
467 $this->mByName
= User
::whoIs( $this->mBy
);
470 $this->mByName
= $wgUser->getName();
476 * Retroactively autoblocks the last IP used by the user (if it is a user)
477 * blocked by this Block.
479 * @return Boolean: whether or not a retroactive autoblock was made.
481 public function doRetroactiveAutoblock() {
482 $dbr = wfGetDB( DB_SLAVE
);
483 # If autoblock is enabled, autoblock the LAST IP used
484 # - stolen shamelessly from CheckUser_body.php
486 if ( $this->mEnableAutoblock
&& $this->mUser
) {
487 wfDebug( "Doing retroactive autoblocks for " . $this->mAddress
. "\n" );
489 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
490 $conds = array( 'rc_user_text' => $this->mAddress
);
492 if ( $this->mAngryAutoblock
) {
493 // Block any IP used in the last 7 days. Up to five IPs.
494 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
495 $options['LIMIT'] = 5;
497 // Just the last IP used.
498 $options['LIMIT'] = 1;
501 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
502 __METHOD__
, $options );
504 if ( !$dbr->numRows( $res ) ) {
505 # No results, don't autoblock anything
506 wfDebug( "No IP found to retroactively autoblock\n" );
508 foreach ( $res as $row ) {
510 $this->doAutoblock( $row->rc_ip
);
518 * Checks whether a given IP is on the autoblock whitelist.
520 * @param $ip String: The IP to check
523 public static function isWhitelistedFromAutoblocks( $ip ) {
526 // Try to get the autoblock_whitelist from the cache, as it's faster
527 // than getting the msg raw and explode()'ing it.
528 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
529 $lines = $wgMemc->get( $key );
531 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
532 $wgMemc->set( $key, $lines, 3600 * 24 );
535 wfDebug( "Checking the autoblock whitelist..\n" );
537 foreach ( $lines as $line ) {
539 if ( substr( $line, 0, 1 ) !== '*' ) {
543 $wlEntry = substr( $line, 1 );
544 $wlEntry = trim( $wlEntry );
546 wfDebug( "Checking $ip against $wlEntry..." );
548 # Is the IP in this range?
549 if ( IP
::isInRange( $ip, $wlEntry ) ) {
550 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
553 wfDebug( " No match\n" );
561 * Autoblocks the given IP, referring to this Block.
563 * @param $autoblockIP String: the IP to autoblock.
564 * @param $justInserted Boolean: the main block was just inserted
565 * @return Boolean: whether or not an autoblock was inserted.
567 public function doAutoblock( $autoblockIP, $justInserted = false ) {
568 # If autoblocks are disabled, go away.
569 if ( !$this->mEnableAutoblock
) {
573 # Check for presence on the autoblock whitelist
574 if ( Block
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
578 # # Allow hooks to cancel the autoblock.
579 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
580 wfDebug( "Autoblock aborted by hook.\n" );
584 # It's okay to autoblock. Go ahead and create/insert the block.
586 $ipblock = Block
::newFromDB( $autoblockIP );
588 # If the user is already blocked. Then check if the autoblock would
589 # exceed the user block. If it would exceed, then do nothing, else
591 if ( $this->mExpiry
&&
592 ( $this->mExpiry
< Block
::getAutoblockExpiry( $ipblock->mTimestamp
) )
597 # Just update the timestamp
598 if ( !$justInserted ) {
599 $ipblock->updateTimestamp();
604 $ipblock = new Block
;
607 # Make a new block object with the desired properties
608 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockIP . "\n" );
609 $ipblock->mAddress
= $autoblockIP;
611 $ipblock->mBy
= $this->mBy
;
612 $ipblock->mByName
= $this->mByName
;
613 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
614 $ipblock->mTimestamp
= wfTimestampNow();
616 $ipblock->mCreateAccount
= $this->mCreateAccount
;
617 # Continue suppressing the name if needed
618 $ipblock->mHideName
= $this->mHideName
;
619 $ipblock->mAllowUsertalk
= $this->mAllowUsertalk
;
621 # If the user is already blocked with an expiry date, we don't
622 # want to pile on top of that!
623 if ( $this->mExpiry
) {
624 $ipblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
) );
626 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
630 return $ipblock->insert();
634 * Check if a block has expired. Delete it if it is.
637 public function deleteIfExpired() {
638 wfProfileIn( __METHOD__
);
640 if ( $this->isExpired() ) {
641 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
645 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
649 wfProfileOut( __METHOD__
);
654 * Has the block expired?
657 public function isExpired() {
658 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
660 if ( !$this->mExpiry
) {
663 return wfTimestampNow() > $this->mExpiry
;
668 * Is the block address valid (i.e. not a null string?)
671 public function isValid() {
672 return $this->mAddress
!= '';
676 * Update the timestamp on autoblocks.
678 public function updateTimestamp() {
679 if ( $this->mAuto
) {
680 $this->mTimestamp
= wfTimestamp();
681 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
683 $dbw = wfGetDB( DB_MASTER
);
684 $dbw->update( 'ipblocks',
686 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
687 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
688 ), array( /* WHERE */
689 'ipb_address' => $this->mAddress
690 ), 'Block::updateTimestamp'
696 * Get the user id of the blocking sysop
700 public function getBy() {
705 * Get the username of the blocking sysop
709 public function getByName() {
710 return $this->mByName
;
714 * Get/set the SELECT ... FOR UPDATE flag
715 * @deprecated since 1.18
717 public function forUpdate( $x = null ) {
722 * Get/set a flag determining whether the master is used for reads
724 public function fromMaster( $x = null ) {
725 return wfSetVar( $this->mFromMaster
, $x );
729 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
730 * @return String, text is escaped
732 public function getRedactedName() {
733 if ( $this->mAuto
) {
734 return HTML
::rawElement(
736 array( 'class' => 'mw-autoblockid' ),
737 wfMessage( 'autoblockid', $this->mId
)
740 return htmlspecialchars( $this->mAddress
);
745 * Encode expiry for DB
747 * @param $expiry String: timestamp for expiry, or
748 * @param $db Database object
750 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
752 public static function encodeExpiry( $expiry, $db ) {
753 return $db->encodeExpiry( $expiry );
757 * Decode expiry which has come from the DB
759 * @param $expiry String: Database expiry format
760 * @param $timestampType Requested timestamp format
762 * @deprecated since 1.18; use $wgLang->decodeExpiry() instead
764 public static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
766 return $wgContLang->formatExpiry( $expiry, $timestampType );
770 * Get a timestamp of the expiry for autoblocks
774 public static function getAutoblockExpiry( $timestamp ) {
775 global $wgAutoblockExpiry;
777 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
781 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
782 * For example, 127.111.113.151/24 -> 127.111.113.0/24
783 * @param $range String: IP address to normalize
785 * @deprecated since 1.18, call IP::sanitizeRange() directly
787 public static function normaliseRange( $range ) {
788 return IP
::sanitizeRange( $range );
792 * Purge expired blocks from the ipblocks table
794 public static function purgeExpired() {
795 $dbw = wfGetDB( DB_MASTER
);
796 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
800 * Get a value to insert into expiry field of the database when infinite expiry
802 * @deprecated since 1.18, call $dbr->getInfinity() directly
805 public static function infinity() {
806 return wfGetDB( DB_SLAVE
)->getInfinity();
810 * Convert a DB-encoded expiry into a real string that humans can read.
812 * @param $encoded_expiry String: Database encoded expiry time
813 * @return Html-escaped String
814 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
816 public static function formatExpiry( $encoded_expiry ) {
820 if ( is_null( $msg ) ) {
822 $keys = array( 'infiniteblock', 'expiringblock' );
824 foreach ( $keys as $key ) {
825 $msg[$key] = wfMsgHtml( $key );
829 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW
);
830 if ( $expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
831 $expirystr = $msg['infiniteblock'];
834 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
835 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
836 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
842 # FIXME: everything above here is a mess, needs much cleaning up
845 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
846 * ("24 May 2034"), into an absolute timestamp we can put into the database.
847 * @param $expiry String: whatever was typed into the form
848 * @return String: timestamp or "infinity" string for th DB implementation
849 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
851 public static function parseExpiryInput( $expiry ) {
852 wfDeprecated( __METHOD__
);
853 return SpecialBlock
::parseExpiryInput( $expiry );
857 * Given a target and the target's type, get an existing Block object if possible.
858 * Note that passing an IP address will get an applicable rangeblock if the IP is
859 * not individually blocked but falls within that range
860 * TODO: check that that fallback handles nested rangeblocks nicely (should return
862 * @param $target String|User|Int a block target, which may be one of several types:
863 * * A user to block, in which case $target will be a User
864 * * An IP to block, in which case $target will be a User generated by using
865 * User::newFromName( $ip, false ) to turn off name validation
866 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
867 * * The ID of an existing block, in which case $target will be an Int
868 * @param $type Block::TYPE_ constant the type of block as described above
869 * @return Block|null (null if the target is not blocked)
871 public static function newFromTargetAndType( $target, $type ){
872 if( $target instanceof User
){
873 if( $type == Block
::TYPE_IP
){
874 return Block
::newFromDB( $target->getName(), 0 );
875 } elseif( $type == Block
::TYPE_USER
) {
876 return Block
::newFromDB( '', $target->getId() );
878 # Should be unreachable;
882 } elseif( $type == Block
::TYPE_RANGE
){
883 return Block
::newFromDB( $target, 0 );
885 } elseif( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
){
886 return Block
::newFromID( $target );
893 public static function newFromTarget( $target ){
894 list( $target, $type ) = self
::parseTarget( $target );
895 return self
::newFromTargetAndType( $target, $type );
899 * From an existing Block, get the target and the type of target. Note that it is
900 * always safe to treat the target as a string; for User objects this will return
901 * User::__toString() which in turn gives User::getName().
902 * @return array( User|String, Block::TYPE_ constant )
904 public static function parseTarget( $target ){
905 $target = trim( $target );
907 $userObj = User
::newFromName( $target );
908 if( $userObj instanceof User
){
909 # Note that since numbers are valid usernames, a $target of "12345" will be
910 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
911 # since hash characters are not valid in usernames or titles generally.
912 return array( $userObj, Block
::TYPE_USER
);
914 } elseif( IP
::isValid( $target ) ){
915 # We can still create a User if it's an IP address, but we need to turn
916 # off validation checking (which would exclude IP addresses)
918 User
::newFromName( IP
::sanitizeIP( $target ), false ),
922 } elseif( IP
::isValidBlock( $target ) ){
923 # Can't create a User from an IP range
924 return array( Block
::normaliseRange( $target ), Block
::TYPE_RANGE
);
926 } elseif( preg_match( '/^#\d+$/', $target ) ){
927 # Autoblock reference in the form "#12345"
928 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
932 return array( null, null );
937 * Get the target and target type for this particular Block. Note that for autoblocks,
938 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
940 * @return array( User|String, Block::TYPE_ constant )
941 * FIXME: this should be an integral part of the Block member variables
943 public function getTargetAndType(){
944 list( $target, $type ) = self
::parseTarget( $this->mAddress
);
946 # Check whether it's an autoblock
948 $type = self
::TYPE_AUTO
;
951 return array( $target, $type );
954 public function getType(){
955 list( /*...*/, $type ) = $this->getTargetAndType();
959 public function getTarget(){
960 list( $target, /*...*/ ) = $this->getTargetAndType();