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 $mUser, $mReason, $mTimestamp, $mAuto, $mExpiry,
38 /// @var Block::TYPE_ constant. Can only be USER, IP or RANGE internally
53 * FIXME: Don't know what the best format to have for this constructor is, but fourteen
54 * optional parameters certainly isn't it.
56 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
57 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
58 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byName = false )
60 if( $timestamp === 0 ){
61 $timestamp = wfTimestampNow();
65 # Expand valid IPv6 addresses
66 $address = IP
::sanitizeIP( $address );
67 $this->mAddress
= $address;
70 $this->mReason
= $reason;
71 $this->mTimestamp
= wfTimestamp( TS_MW
, $timestamp );
73 $this->mAnonOnly
= $anonOnly;
74 $this->mCreateAccount
= $createAccount;
75 $this->mExpiry
= $expiry;
76 $this->mEnableAutoblock
= $enableAutoblock;
77 $this->mHideName
= $hideName;
78 $this->mBlockEmail
= $blockEmail;
79 $this->mAllowUsertalk
= $allowUsertalk;
80 $this->mFromMaster
= false;
81 $this->mByName
= $byName;
82 $this->mAngryAutoblock
= false;
83 $this->initialiseRange();
87 * Load a block from the database, using either the IP address or
88 * user ID. Tries the user ID first, and if that doesn't work, tries
91 * @param $address String: IP address of user/anon
92 * @param $user Integer: user id of user
93 * @param $killExpired Boolean: delete expired blocks on load
94 * @return Block Object
96 public static function newFromDB( $address, $user = 0, $killExpired = true ) {
98 $block->load( $address, $user, $killExpired );
99 if ( $block->isValid() ) {
107 * Load a blocked user from their block id.
109 * @param $id Integer: Block id to search for
110 * @return Block object
112 public static function newFromID( $id ) {
113 $dbr = wfGetDB( DB_SLAVE
);
114 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
115 array( 'ipb_id' => $id ), __METHOD__
) );
118 if ( $block->loadFromResult( $res ) ) {
126 * Check if two blocks are effectively equal
130 public function equals( Block
$block ) {
132 $this->mAddress
== $block->mAddress
133 && $this->mUser
== $block->mUser
134 && $this->mAuto
== $block->mAuto
135 && $this->mAnonOnly
== $block->mAnonOnly
136 && $this->mCreateAccount
== $block->mCreateAccount
137 && $this->mExpiry
== $block->mExpiry
138 && $this->mEnableAutoblock
== $block->mEnableAutoblock
139 && $this->mHideName
== $block->mHideName
140 && $this->mBlockEmail
== $block->mBlockEmail
141 && $this->mAllowUsertalk
== $block->mAllowUsertalk
142 && $this->mReason
== $block->mReason
147 * Clear all member variables in the current object. Does not clear
148 * the block from the DB.
150 public function clear() {
151 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
152 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
153 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
154 $this->mBy
= $this->mHideName
= $this->mBlockEmail
= $this->mAllowUsertalk
= 0;
155 $this->mByName
= false;
159 * Get a block from the DB, with either the given address or the given username
161 * @param $address string The IP address of the user, or blank to skip IP blocks
162 * @param $user int The user ID, or zero for anonymous users
163 * @param $killExpired bool Whether to delete expired rows while loading
164 * @return Boolean: the user is blocked from editing
165 * @deprecated since 1.18
167 public function load( $address = '', $user = 0, $killExpired = true ) {
168 wfDeprecated( __METHOD__
);
170 $username = User
::whoIs( $user );
171 $block = self
::newFromTarget( $username, $address );
173 $block = self
::newFromTarget( null, $address );
176 if( $block instanceof Block
){
177 # This is mildly evil, but hey, it's B/C :D
178 foreach( $block as $variable => $value ){
179 $this->$variable = $value;
188 * Load a block from the database which affects the already-set $this->target:
189 * 1) A block directly on the given user or IP
190 * 2) A rangeblock encompasing the given IP (smallest first)
191 * 3) An autoblock on the given IP
192 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
193 * make any sense to use TYPE_AUTO / TYPE_ID here
194 * @return Bool whether a relevant block was found
196 protected function newLoad( $vagueTarget = null ) {
197 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
199 if( $this->type
!== null ){
201 'ipb_address' => array( (string)$this->target
),
204 $conds = array( 'ipb_address' => array() );
207 if( $vagueTarget !== null ){
208 list( $target, $type ) = self
::parseTarget( $vagueTarget );
210 case self
::TYPE_USER
:
211 # Slightly wierd, but who are we to argue?
212 $conds['ipb_address'][] = (string)$target;
216 $conds['ipb_address'][] = (string)$target;
217 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
218 $conds = $db->makeList( $conds, LIST_OR
);
221 case self
::TYPE_RANGE
:
222 list( $start, $end ) = IP
::parseRange( $target );
223 $conds['ipb_address'][] = (string)$target;
224 $conds[] = self
::getRangeCond( $start, $end );
225 $conds = $db->makeList( $conds, LIST_OR
);
229 throw new MWException( "Tried to load block with invalid type" );
233 $res = $db->select( 'ipblocks', '*', $conds, __METHOD__
);
235 # This result could contain a block on the user, a block on the IP, and a russian-doll
236 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
239 # Lower will be better
240 $bestBlockScore = 100;
242 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
243 $bestBlockPreventsEdit = null;
245 foreach( $res as $row ){
246 $block = Block
::newFromRow( $row );
248 # Don't use expired blocks
249 if( $block->deleteIfExpired() ){
253 # Don't use anon only blocks on users
254 if( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ){
258 if( $block->getType() == self
::TYPE_RANGE
){
259 # This is the number of bits that are allowed to vary in the block, give
260 # or take some floating point errors
261 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
262 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
263 $size = log( $end - $start +
1, 2 );
265 # This has the nice property that a /32 block is ranked equally with a
266 # single-IP block, which is exactly what it is...
267 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
270 $score = $block->getType();
273 if( $score < $bestBlockScore ){
274 $bestBlockScore = $score;
276 $bestBlockPreventsEdit = $block->prevents( 'edit' );
280 if( $bestRow !== null ){
281 $this->initFromRow( $bestRow );
282 $this->prevents( 'edit', $bestBlockPreventsEdit );
290 * Get a set of SQL conditions which will select rangeblocks encompasing a given range
291 * @param $start String Hexadecimal IP representation
292 * @param $end String Hexadecimal IP represenation, or null to use $start = $end
295 public static function getRangeCond( $start, $end = null ) {
296 if ( $end === null ) {
299 # Per bug 14634, we want to include relevant active rangeblocks; for
300 # rangeblocks, we want to include larger ranges which enclose the given
301 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
302 # so we can improve performance by filtering on a LIKE clause
303 $chunk = self
::getIpFragment( $start );
304 $dbr = wfGetDB( DB_SLAVE
);
305 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
307 # Fairly hard to make a malicious SQL statement out of hex characters,
308 # but stranger things have happened...
309 $safeStart = $dbr->addQuotes( $start );
310 $safeEnd = $dbr->addQuotes( $end );
312 return $dbr->makeList(
314 "ipb_range_start $like",
315 "ipb_range_start <= $safeStart",
316 "ipb_range_end >= $safeEnd",
323 * Get the component of an IP address which is certain to be the same between an IP
324 * address and a rangeblock containing that IP address.
325 * @param $hex String Hexadecimal IP representation
328 protected static function getIpFragment( $hex ) {
329 global $wgBlockCIDRLimit;
330 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
331 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
333 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
338 * Fill in member variables from a result wrapper
340 * @param $res ResultWrapper: row from the ipblocks table
341 * @param $killExpired Boolean: whether to delete expired rows while loading
344 protected function loadFromResult( ResultWrapper
$res, $killExpired = true ) {
347 if ( 0 != $res->numRows() ) {
349 $row = $res->fetchObject();
350 $this->initFromRow( $row );
352 if ( $killExpired ) {
353 # If requested, delete expired rows
355 $killed = $this->deleteIfExpired();
357 $row = $res->fetchObject();
359 $this->initFromRow( $row );
362 } while ( $killed && $row );
364 # If there were any left after the killing finished, return true
378 * Search the database for any range blocks matching the given address, and
379 * load the row if one is found.
381 * @param $address String: IP address range
382 * @param $killExpired Boolean: whether to delete expired rows while loading
383 * @param $user Integer: if not 0, then sets ipb_anon_only
386 protected function loadRange( $address, $killExpired = true, $user = 0 ) {
387 $iaddr = IP
::toHex( $address );
389 if ( $iaddr === false ) {
394 # Only scan ranges which start in this /16, this improves search speed
395 # Blocks should not cross a /16 boundary.
396 $range = substr( $iaddr, 0, 4 );
398 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
400 'ipb_range_start' . $db->buildLike( $range, $db->anyString() ),
401 "ipb_range_start <= '$iaddr'",
402 "ipb_range_end >= '$iaddr'"
406 $conds['ipb_anon_only'] = 0;
409 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
) );
410 $success = $this->loadFromResult( $res, $killExpired );
416 * Given a database row from the ipblocks table, initialize
419 * @param $row ResultWrapper: a row from the ipblocks table
421 protected function initFromRow( $row ) {
422 list( $this->target
, $this->type
) = self
::parseTarget( $row->ipb_address
);
424 $this->setTarget( $row->ipb_address
);
425 $this->setBlocker( User
::newFromId( $row->ipb_by
) );
427 $this->mReason
= $row->ipb_reason
;
428 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
429 $this->mAuto
= $row->ipb_auto
;
430 $this->mAnonOnly
= $row->ipb_anon_only
;
431 $this->mCreateAccount
= $row->ipb_create_account
;
432 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
433 $this->mBlockEmail
= $row->ipb_block_email
;
434 $this->mAllowUsertalk
= $row->ipb_allow_usertalk
;
435 $this->mHideName
= $row->ipb_deleted
;
436 $this->mId
= $row->ipb_id
;
437 $this->mExpiry
= $row->ipb_expiry
;
438 $this->mRangeStart
= $row->ipb_range_start
;
439 $this->mRangeEnd
= $row->ipb_range_end
;
443 * Create a new Block object from a database row
444 * @param $row ResultWrapper row from the ipblocks table
447 public static function newFromRow( $row ){
449 $block->initFromRow( $row );
454 * Once $mAddress has been set, get the range they came from.
455 * Wrapper for IP::parseRange
457 protected function initialiseRange() {
458 $this->mRangeStart
= '';
459 $this->mRangeEnd
= '';
461 if ( $this->mUser
== 0 ) {
462 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
467 * Delete the row from the IP blocks table.
471 public function delete() {
472 if ( wfReadOnly() ) {
477 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
480 $dbw = wfGetDB( DB_MASTER
);
481 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
483 return $dbw->affectedRows() > 0;
487 * Insert a block into the block table. Will fail if there is a conflicting
488 * block (same name and options) already in the database.
490 * @return mixed: false on failure, assoc array on success:
491 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
493 public function insert( $dbw = null ) {
494 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
496 if ( $dbw === null ) {
497 $dbw = wfGetDB( DB_MASTER
);
500 $this->validateBlockParams();
501 $this->initialiseRange();
503 # Don't collide with expired blocks
504 Block
::purgeExpired();
506 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
511 'ipb_address' => $this->mAddress
,
512 'ipb_user' => $this->mUser
,
513 'ipb_by' => $this->mBy
,
514 'ipb_by_text' => $this->mByName
,
515 'ipb_reason' => $this->mReason
,
516 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
517 'ipb_auto' => $this->mAuto
,
518 'ipb_anon_only' => $this->mAnonOnly
,
519 'ipb_create_account' => $this->mCreateAccount
,
520 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
521 'ipb_expiry' => $dbw->encodeExpiry( $this->mExpiry
),
522 'ipb_range_start' => $this->mRangeStart
,
523 'ipb_range_end' => $this->mRangeEnd
,
524 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
525 'ipb_block_email' => $this->mBlockEmail
,
526 'ipb_allow_usertalk' => $this->mAllowUsertalk
531 $affected = $dbw->affectedRows();
534 $auto_ipd_ids = $this->doRetroactiveAutoblock();
535 return array( 'id' => $ipb_id, 'autoIds' => $auto_ipd_ids );
542 * Update a block in the DB with new parameters.
543 * The ID field needs to be loaded first.
545 public function update() {
546 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
547 $dbw = wfGetDB( DB_MASTER
);
549 $this->validateBlockParams();
554 'ipb_user' => $this->mUser
,
555 'ipb_by' => $this->mBy
,
556 'ipb_by_text' => $this->mByName
,
557 'ipb_reason' => $this->mReason
,
558 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
559 'ipb_auto' => $this->mAuto
,
560 'ipb_anon_only' => $this->mAnonOnly
,
561 'ipb_create_account' => $this->mCreateAccount
,
562 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
563 'ipb_expiry' => $dbw->encodeExpiry( $this->mExpiry
),
564 'ipb_range_start' => $this->mRangeStart
,
565 'ipb_range_end' => $this->mRangeEnd
,
566 'ipb_deleted' => $this->mHideName
,
567 'ipb_block_email' => $this->mBlockEmail
,
568 'ipb_allow_usertalk' => $this->mAllowUsertalk
570 array( 'ipb_id' => $this->mId
),
574 return $dbw->affectedRows();
578 * Make sure all the proper members are set to sane values
579 * before adding/updating a block
581 protected function validateBlockParams() {
582 # Unset ipb_anon_only for user blocks, makes no sense
583 if ( $this->mUser
) {
584 $this->mAnonOnly
= 0;
587 # Unset ipb_enable_autoblock for IP blocks, makes no sense
588 if ( !$this->mUser
) {
589 $this->mEnableAutoblock
= 0;
592 # bug 18860: non-anon-only IP blocks should be allowed to block email
593 if ( !$this->mUser
&& $this->mAnonOnly
) {
594 $this->mBlockEmail
= 0;
597 if ( !$this->mByName
) {
599 $this->mByName
= User
::whoIs( $this->mBy
);
602 $this->mByName
= $wgUser->getName();
608 * Retroactively autoblocks the last IP used by the user (if it is a user)
609 * blocked by this Block.
611 * @return Array: block IDs of retroactive autoblocks made
613 protected function doRetroactiveAutoblock() {
616 $dbr = wfGetDB( DB_SLAVE
);
617 # If autoblock is enabled, autoblock the LAST IP used
618 # - stolen shamelessly from CheckUser_body.php
620 if ( $this->mEnableAutoblock
&& $this->mUser
) {
621 wfDebug( "Doing retroactive autoblocks for " . $this->mAddress
. "\n" );
623 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
624 $conds = array( 'rc_user_text' => $this->mAddress
);
626 if ( $this->mAngryAutoblock
) {
627 // Block any IP used in the last 7 days. Up to five IPs.
628 $conds[] = 'rc_timestamp < ' .
629 $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
630 $options['LIMIT'] = 5;
632 // Just the last IP used.
633 $options['LIMIT'] = 1;
636 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
637 __METHOD__
, $options );
639 if ( !$dbr->numRows( $res ) ) {
640 # No results, don't autoblock anything
641 wfDebug( "No IP found to retroactively autoblock\n" );
643 foreach ( $res as $row ) {
645 $id = $this->doAutoblock( $row->rc_ip
);
646 if ( $id ) $blockIds[] = $id;
655 * Checks whether a given IP is on the autoblock whitelist.
657 * @param $ip String: The IP to check
660 public static function isWhitelistedFromAutoblocks( $ip ) {
663 // Try to get the autoblock_whitelist from the cache, as it's faster
664 // than getting the msg raw and explode()'ing it.
665 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
666 $lines = $wgMemc->get( $key );
668 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
669 $wgMemc->set( $key, $lines, 3600 * 24 );
672 wfDebug( "Checking the autoblock whitelist..\n" );
674 foreach ( $lines as $line ) {
676 if ( substr( $line, 0, 1 ) !== '*' ) {
680 $wlEntry = substr( $line, 1 );
681 $wlEntry = trim( $wlEntry );
683 wfDebug( "Checking $ip against $wlEntry..." );
685 # Is the IP in this range?
686 if ( IP
::isInRange( $ip, $wlEntry ) ) {
687 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
690 wfDebug( " No match\n" );
698 * Autoblocks the given IP, referring to this Block.
700 * @param $autoblockIP String: the IP to autoblock.
701 * @param $justInserted Boolean: the main block was just inserted.
702 * @return mixed: block ID if an autoblock was inserted, false if not.
704 public function doAutoblock( $autoblockIP, $justInserted = false ) {
705 # If autoblocks are disabled, go away.
706 if ( !$this->mEnableAutoblock
) {
710 # Check for presence on the autoblock whitelist
711 if ( Block
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
715 # # Allow hooks to cancel the autoblock.
716 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
717 wfDebug( "Autoblock aborted by hook.\n" );
721 # It's okay to autoblock. Go ahead and create/insert the block.
723 $ipblock = Block
::newFromTarget( $autoblockIP );
725 # If the user is already blocked. Then check if the autoblock would
726 # exceed the user block. If it would exceed, then do nothing, else
728 if ( $this->mExpiry
&&
729 ( $this->mExpiry
< Block
::getAutoblockExpiry( $ipblock->mTimestamp
) )
734 # Just update the timestamp
735 if ( !$justInserted ) {
736 $ipblock->updateTimestamp();
741 $ipblock = new Block
;
744 # Make a new block object with the desired properties
745 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockIP . "\n" );
746 $ipblock->mAddress
= $autoblockIP;
748 $ipblock->mBy
= $this->mBy
;
749 $ipblock->mByName
= $this->mByName
;
750 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
751 $ipblock->mTimestamp
= wfTimestampNow();
753 $ipblock->mCreateAccount
= $this->mCreateAccount
;
754 # Continue suppressing the name if needed
755 $ipblock->mHideName
= $this->mHideName
;
756 $ipblock->mAllowUsertalk
= $this->mAllowUsertalk
;
758 # If the user is already blocked with an expiry date, we don't
759 # want to pile on top of that!
760 if ( $this->mExpiry
) {
761 $ipblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
) );
763 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
767 $status = $ipblock->insert();
768 return $status ?
$status['id'] : false;
772 * Check if a block has expired. Delete it if it is.
775 public function deleteIfExpired() {
776 wfProfileIn( __METHOD__
);
778 if ( $this->isExpired() ) {
779 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
783 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
787 wfProfileOut( __METHOD__
);
792 * Has the block expired?
795 public function isExpired() {
796 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
798 if ( !$this->mExpiry
) {
801 return wfTimestampNow() > $this->mExpiry
;
806 * Is the block address valid (i.e. not a null string?)
809 public function isValid() {
810 return $this->mAddress
!= '';
814 * Update the timestamp on autoblocks.
816 public function updateTimestamp() {
817 if ( $this->mAuto
) {
818 $this->mTimestamp
= wfTimestamp();
819 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
821 $dbw = wfGetDB( DB_MASTER
);
822 $dbw->update( 'ipblocks',
824 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
825 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
826 ), array( /* WHERE */
827 'ipb_address' => $this->mAddress
828 ), 'Block::updateTimestamp'
834 * Get the IP address at the start of the range in Hex form
835 * @return String IP in Hex form
837 public function getRangeStart() {
838 switch( $this->type
) {
839 case self
::TYPE_USER
:
842 return IP
::toHex( $this->target
);
843 case self
::TYPE_RANGE
:
844 return $this->mRangeStart
;
845 default: throw new MWException( "Block with invalid type" );
850 * Get the IP address at the start of the range in Hex form
851 * @return String IP in Hex form
853 public function getRangeEnd() {
854 switch( $this->type
) {
855 case self
::TYPE_USER
:
858 return IP
::toHex( $this->target
);
859 case self
::TYPE_RANGE
:
860 return $this->mRangeEnd
;
861 default: throw new MWException( "Block with invalid type" );
866 * Get the user id of the blocking sysop
870 public function getBy() {
875 * Get the username of the blocking sysop
879 public function getByName() {
880 return $this->mByName
;
887 public function getId() {
892 * Get/set the SELECT ... FOR UPDATE flag
893 * @deprecated since 1.18
895 public function forUpdate( $x = null ) {
900 * Get/set a flag determining whether the master is used for reads
902 public function fromMaster( $x = null ) {
903 return wfSetVar( $this->mFromMaster
, $x );
907 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
911 public function isHardblock( $x = null ) {
912 $y = $this->mAnonOnly
;
914 $this->mAnonOnly
= !$x;
919 public function isAutoblocking( $x = null ) {
920 return wfSetVar( $this->mEnableAutoblock
, $x );
924 * Get/set whether the Block prevents a given action
925 * @param $action String
929 public function prevents( $action, $x = null ) {
932 # For now... <evil laugh>
935 case 'createaccount':
936 return wfSetVar( $this->mCreateAccount
, $x );
939 return wfSetVar( $this->mBlockEmail
, $x );
941 case 'editownusertalk':
942 $y = $this->mAllowUsertalk
;
944 $this->mAllowUsertalk
= !$x;
954 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
955 * @return String, text is escaped
957 public function getRedactedName() {
958 if ( $this->mAuto
) {
959 return HTML
::rawElement(
961 array( 'class' => 'mw-autoblockid' ),
962 wfMessage( 'autoblockid', $this->mId
)
965 return htmlspecialchars( $this->mAddress
);
970 * Encode expiry for DB
972 * @param $expiry String: timestamp for expiry, or
973 * @param $db Database object
975 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
977 public static function encodeExpiry( $expiry, $db ) {
978 return $db->encodeExpiry( $expiry );
982 * Decode expiry which has come from the DB
984 * @param $expiry String: Database expiry format
985 * @param $timestampType Requested timestamp format
987 * @deprecated since 1.18; use $wgLang->decodeExpiry() instead
989 public static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
991 return $wgContLang->formatExpiry( $expiry, $timestampType );
995 * Get a timestamp of the expiry for autoblocks
999 public static function getAutoblockExpiry( $timestamp ) {
1000 global $wgAutoblockExpiry;
1002 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1006 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
1007 * For example, 127.111.113.151/24 -> 127.111.113.0/24
1008 * @param $range String: IP address to normalize
1010 * @deprecated since 1.18, call IP::sanitizeRange() directly
1012 public static function normaliseRange( $range ) {
1013 return IP
::sanitizeRange( $range );
1017 * Purge expired blocks from the ipblocks table
1019 public static function purgeExpired() {
1020 $dbw = wfGetDB( DB_MASTER
);
1021 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
1025 * Get a value to insert into expiry field of the database when infinite expiry
1027 * @deprecated since 1.18, call $dbr->getInfinity() directly
1030 public static function infinity() {
1031 return wfGetDB( DB_SLAVE
)->getInfinity();
1035 * Convert a DB-encoded expiry into a real string that humans can read.
1037 * @param $encoded_expiry String: Database encoded expiry time
1038 * @return Html-escaped String
1039 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
1041 public static function formatExpiry( $encoded_expiry ) {
1045 if ( is_null( $msg ) ) {
1047 $keys = array( 'infiniteblock', 'expiringblock' );
1049 foreach ( $keys as $key ) {
1050 $msg[$key] = wfMsgHtml( $key );
1054 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW
);
1055 if ( $expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
1056 $expirystr = $msg['infiniteblock'];
1059 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
1060 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
1061 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
1067 # FIXME: everything above here is a mess, needs much cleaning up
1070 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1071 * ("24 May 2034"), into an absolute timestamp we can put into the database.
1072 * @param $expiry String: whatever was typed into the form
1073 * @return String: timestamp or "infinity" string for th DB implementation
1074 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
1076 public static function parseExpiryInput( $expiry ) {
1077 wfDeprecated( __METHOD__
);
1078 return SpecialBlock
::parseExpiryInput( $expiry );
1082 * Given a target and the target's type, get an existing Block object if possible.
1083 * @param $specificTarget String|User|Int a block target, which may be one of several types:
1084 * * A user to block, in which case $target will be a User
1085 * * An IP to block, in which case $target will be a User generated by using
1086 * User::newFromName( $ip, false ) to turn off name validation
1087 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1088 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1090 * Calling this with a user, IP address or range will not select autoblocks, and will
1091 * only select a block where the targets match exactly (so looking for blocks on
1092 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1093 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
1094 * affects that target (so for an IP address, get ranges containing that IP; and also
1095 * get any relevant autoblocks)
1096 * @param $fromMaster Bool whether to use the DB_MASTER database
1097 * @return Block|null (null if no relevant block could be found). The target and type
1098 * of the returned Block will refer to the actual block which was found, which might
1099 * not be the same as the target you gave if you used $vagueTarget!
1101 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1102 list( $target, $type ) = self
::parseTarget( $specificTarget );
1103 if( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
){
1104 return Block
::newFromID( $target );
1106 } elseif( $target === null && $vagueTarget === null ){
1107 # We're not going to find anything useful here
1110 } elseif( in_array( $type, array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) ) ) {
1111 $block = new Block();
1112 $block->fromMaster( $fromMaster );
1114 if( $type !== null ){
1115 $block->setTarget( $target );
1118 if( $block->newLoad( $vagueTarget ) ){
1129 * From an existing Block, get the target and the type of target. Note that it is
1130 * always safe to treat the target as a string; for User objects this will return
1131 * User::__toString() which in turn gives User::getName().
1132 * @return array( User|String, Block::TYPE_ constant )
1134 public static function parseTarget( $target ) {
1135 $target = trim( $target );
1137 # We may have been through this before
1138 if( $target instanceof User
){
1139 if( IP
::isValid( $target->getName() ) ){
1140 return self
::TYPE_IP
;
1142 return self
::TYPE_USER
;
1144 } elseif( $target === null ){
1145 return array( null, null );
1148 $userObj = User
::newFromName( $target );
1149 if ( $userObj instanceof User
) {
1150 # Note that since numbers are valid usernames, a $target of "12345" will be
1151 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1152 # since hash characters are not valid in usernames or titles generally.
1153 return array( $userObj, Block
::TYPE_USER
);
1155 } elseif ( IP
::isValid( $target ) ) {
1156 # We can still create a User if it's an IP address, but we need to turn
1157 # off validation checking (which would exclude IP addresses)
1159 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1163 } elseif ( IP
::isValidBlock( $target ) ) {
1164 # Can't create a User from an IP range
1165 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1167 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1168 # Autoblock reference in the form "#12345"
1169 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1173 return array( null, null );
1178 * Get the type of target for this particular block
1179 * @return Block::TYPE_ constant, will never be TYPE_ID
1181 public function getType() {
1188 * Get the target and target type for this particular Block. Note that for autoblocks,
1189 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1190 * in this situation.
1191 * @return array( User|String, Block::TYPE_ constant )
1192 * FIXME: this should be an integral part of the Block member variables
1194 public function getTargetAndType() {
1195 return array( $this->getTarget(), $this->getType() );
1199 * Get the target for this particular Block. Note that for autoblocks,
1200 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1201 * in this situation.
1202 * @return User|String
1204 public function getTarget() {
1205 return $this->target
;
1209 * Set the target for this block, and update $this->type accordingly
1210 * @param $target Mixed
1212 public function setTarget( $target ){
1213 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1215 $this->mAddress
= (string)$this->target
;
1216 if( $this->type
== self
::TYPE_USER
){
1217 if( $this->target
instanceof User
){
1219 $this->mUser
= $this->target
->getID();
1221 $this->mUser
= User
::idFromName( $this->target
);
1229 * Get the user who implemented this block
1232 public function getBlocker(){
1233 return $this->blocker
;
1237 * Set the user who implemented (or will implement) this block
1240 public function setBlocker( User
$user ){
1241 $this->blocker
= $user;
1243 $this->mBy
= $user->getID();
1244 $this->mByName
= $user->getName();