a112be0f92c74e9bfc649350cdda1bbb9c87a863
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, 'autoId' => autoblock ID or false)
493 public function insert( $dbw = null ) {
494 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
497 $dbw = wfGetDB( DB_MASTER
);
499 $this->validateBlockParams();
500 $this->initialiseRange();
502 # Don't collide with expired blocks
503 Block
::purgeExpired();
505 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
510 'ipb_address' => $this->mAddress
,
511 'ipb_user' => $this->mUser
,
512 'ipb_by' => $this->mBy
,
513 'ipb_by_text' => $this->mByName
,
514 'ipb_reason' => $this->mReason
,
515 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
516 'ipb_auto' => $this->mAuto
,
517 'ipb_anon_only' => $this->mAnonOnly
,
518 'ipb_create_account' => $this->mCreateAccount
,
519 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
520 'ipb_expiry' => $dbw->encodeExpiry( $this->mExpiry
),
521 'ipb_range_start' => $this->mRangeStart
,
522 'ipb_range_end' => $this->mRangeEnd
,
523 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
524 'ipb_block_email' => $this->mBlockEmail
,
525 'ipb_allow_usertalk' => $this->mAllowUsertalk
530 $affected = $dbw->affectedRows();
533 $auto_ipd_id = $this->doRetroactiveAutoblock();
534 return array( 'id' => $ipb_id, 'autoId' => $auto_ipd_id );
541 * Update a block in the DB with new parameters.
542 * The ID field needs to be loaded first.
544 public function update() {
545 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
546 $dbw = wfGetDB( DB_MASTER
);
548 $this->validateBlockParams();
553 'ipb_user' => $this->mUser
,
554 'ipb_by' => $this->mBy
,
555 'ipb_by_text' => $this->mByName
,
556 'ipb_reason' => $this->mReason
,
557 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
558 'ipb_auto' => $this->mAuto
,
559 'ipb_anon_only' => $this->mAnonOnly
,
560 'ipb_create_account' => $this->mCreateAccount
,
561 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
562 'ipb_expiry' => $dbw->encodeExpiry( $this->mExpiry
),
563 'ipb_range_start' => $this->mRangeStart
,
564 'ipb_range_end' => $this->mRangeEnd
,
565 'ipb_deleted' => $this->mHideName
,
566 'ipb_block_email' => $this->mBlockEmail
,
567 'ipb_allow_usertalk' => $this->mAllowUsertalk
569 array( 'ipb_id' => $this->mId
),
573 return $dbw->affectedRows();
577 * Make sure all the proper members are set to sane values
578 * before adding/updating a block
580 protected function validateBlockParams() {
581 # Unset ipb_anon_only for user blocks, makes no sense
582 if ( $this->mUser
) {
583 $this->mAnonOnly
= 0;
586 # Unset ipb_enable_autoblock for IP blocks, makes no sense
587 if ( !$this->mUser
) {
588 $this->mEnableAutoblock
= 0;
591 # bug 18860: non-anon-only IP blocks should be allowed to block email
592 if ( !$this->mUser
&& $this->mAnonOnly
) {
593 $this->mBlockEmail
= 0;
596 if ( !$this->mByName
) {
598 $this->mByName
= User
::whoIs( $this->mBy
);
601 $this->mByName
= $wgUser->getName();
607 * Retroactively autoblocks the last IP used by the user (if it is a user)
608 * blocked by this Block.
610 * @return mixed: block ID if a retroactive autoblock was made, false if not.
612 protected function doRetroactiveAutoblock() {
613 $dbr = wfGetDB( DB_SLAVE
);
614 # If autoblock is enabled, autoblock the LAST IP used
615 # - stolen shamelessly from CheckUser_body.php
617 if ( $this->mEnableAutoblock
&& $this->mUser
) {
618 wfDebug( "Doing retroactive autoblocks for " . $this->mAddress
. "\n" );
620 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
621 $conds = array( 'rc_user_text' => $this->mAddress
);
623 if ( $this->mAngryAutoblock
) {
624 // Block any IP used in the last 7 days. Up to five IPs.
625 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
626 $options['LIMIT'] = 5;
628 // Just the last IP used.
629 $options['LIMIT'] = 1;
632 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
633 __METHOD__
, $options );
635 if ( !$dbr->numRows( $res ) ) {
636 # No results, don't autoblock anything
637 wfDebug( "No IP found to retroactively autoblock\n" );
639 foreach ( $res as $row ) {
641 return $this->doAutoblock( $row->rc_ip
);
650 * Checks whether a given IP is on the autoblock whitelist.
652 * @param $ip String: The IP to check
655 public static function isWhitelistedFromAutoblocks( $ip ) {
658 // Try to get the autoblock_whitelist from the cache, as it's faster
659 // than getting the msg raw and explode()'ing it.
660 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
661 $lines = $wgMemc->get( $key );
663 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
664 $wgMemc->set( $key, $lines, 3600 * 24 );
667 wfDebug( "Checking the autoblock whitelist..\n" );
669 foreach ( $lines as $line ) {
671 if ( substr( $line, 0, 1 ) !== '*' ) {
675 $wlEntry = substr( $line, 1 );
676 $wlEntry = trim( $wlEntry );
678 wfDebug( "Checking $ip against $wlEntry..." );
680 # Is the IP in this range?
681 if ( IP
::isInRange( $ip, $wlEntry ) ) {
682 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
685 wfDebug( " No match\n" );
693 * Autoblocks the given IP, referring to this Block.
695 * @param $autoblockIP String: the IP to autoblock.
696 * @param $justInserted Boolean: the main block was just inserted.
697 * @return mixed: block ID if an autoblock was inserted, false if not.
699 public function doAutoblock( $autoblockIP, $justInserted = false ) {
700 # If autoblocks are disabled, go away.
701 if ( !$this->mEnableAutoblock
) {
705 # Check for presence on the autoblock whitelist
706 if ( Block
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
710 # # Allow hooks to cancel the autoblock.
711 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
712 wfDebug( "Autoblock aborted by hook.\n" );
716 # It's okay to autoblock. Go ahead and create/insert the block.
718 $ipblock = Block
::newFromTarget( $autoblockIP );
720 # If the user is already blocked. Then check if the autoblock would
721 # exceed the user block. If it would exceed, then do nothing, else
723 if ( $this->mExpiry
&&
724 ( $this->mExpiry
< Block
::getAutoblockExpiry( $ipblock->mTimestamp
) )
729 # Just update the timestamp
730 if ( !$justInserted ) {
731 $ipblock->updateTimestamp();
736 $ipblock = new Block
;
739 # Make a new block object with the desired properties
740 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockIP . "\n" );
741 $ipblock->mAddress
= $autoblockIP;
743 $ipblock->mBy
= $this->mBy
;
744 $ipblock->mByName
= $this->mByName
;
745 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
746 $ipblock->mTimestamp
= wfTimestampNow();
748 $ipblock->mCreateAccount
= $this->mCreateAccount
;
749 # Continue suppressing the name if needed
750 $ipblock->mHideName
= $this->mHideName
;
751 $ipblock->mAllowUsertalk
= $this->mAllowUsertalk
;
753 # If the user is already blocked with an expiry date, we don't
754 # want to pile on top of that!
755 if ( $this->mExpiry
) {
756 $ipblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
) );
758 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
762 $status = $ipblock->insert();
763 return $status ?
$status['id'] : false;
767 * Check if a block has expired. Delete it if it is.
770 public function deleteIfExpired() {
771 wfProfileIn( __METHOD__
);
773 if ( $this->isExpired() ) {
774 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
778 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
782 wfProfileOut( __METHOD__
);
787 * Has the block expired?
790 public function isExpired() {
791 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
793 if ( !$this->mExpiry
) {
796 return wfTimestampNow() > $this->mExpiry
;
801 * Is the block address valid (i.e. not a null string?)
804 public function isValid() {
805 return $this->mAddress
!= '';
809 * Update the timestamp on autoblocks.
811 public function updateTimestamp() {
812 if ( $this->mAuto
) {
813 $this->mTimestamp
= wfTimestamp();
814 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
816 $dbw = wfGetDB( DB_MASTER
);
817 $dbw->update( 'ipblocks',
819 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
820 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
821 ), array( /* WHERE */
822 'ipb_address' => $this->mAddress
823 ), 'Block::updateTimestamp'
829 * Get the IP address at the start of the range in Hex form
830 * @return String IP in Hex form
832 public function getRangeStart() {
833 switch( $this->type
) {
834 case self
::TYPE_USER
:
837 return IP
::toHex( $this->target
);
838 case self
::TYPE_RANGE
:
839 return $this->mRangeStart
;
840 default: throw new MWException( "Block with invalid type" );
845 * Get the IP address at the start of the range in Hex form
846 * @return String IP in Hex form
848 public function getRangeEnd() {
849 switch( $this->type
) {
850 case self
::TYPE_USER
:
853 return IP
::toHex( $this->target
);
854 case self
::TYPE_RANGE
:
855 return $this->mRangeEnd
;
856 default: throw new MWException( "Block with invalid type" );
861 * Get the user id of the blocking sysop
865 public function getBy() {
870 * Get the username of the blocking sysop
874 public function getByName() {
875 return $this->mByName
;
882 public function getId() {
887 * Get/set the SELECT ... FOR UPDATE flag
888 * @deprecated since 1.18
890 public function forUpdate( $x = null ) {
895 * Get/set a flag determining whether the master is used for reads
897 public function fromMaster( $x = null ) {
898 return wfSetVar( $this->mFromMaster
, $x );
902 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
906 public function isHardblock( $x = null ) {
907 $y = $this->mAnonOnly
;
909 $this->mAnonOnly
= !$x;
914 public function isAutoblocking( $x = null ) {
915 return wfSetVar( $this->mEnableAutoblock
, $x );
919 * Get/set whether the Block prevents a given action
920 * @param $action String
924 public function prevents( $action, $x = null ) {
927 # For now... <evil laugh>
930 case 'createaccount':
931 return wfSetVar( $this->mCreateAccount
, $x );
934 return wfSetVar( $this->mBlockEmail
, $x );
936 case 'editownusertalk':
937 $y = $this->mAllowUsertalk
;
939 $this->mAllowUsertalk
= !$x;
949 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
950 * @return String, text is escaped
952 public function getRedactedName() {
953 if ( $this->mAuto
) {
954 return HTML
::rawElement(
956 array( 'class' => 'mw-autoblockid' ),
957 wfMessage( 'autoblockid', $this->mId
)
960 return htmlspecialchars( $this->mAddress
);
965 * Encode expiry for DB
967 * @param $expiry String: timestamp for expiry, or
968 * @param $db Database object
970 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
972 public static function encodeExpiry( $expiry, $db ) {
973 return $db->encodeExpiry( $expiry );
977 * Decode expiry which has come from the DB
979 * @param $expiry String: Database expiry format
980 * @param $timestampType Requested timestamp format
982 * @deprecated since 1.18; use $wgLang->decodeExpiry() instead
984 public static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
986 return $wgContLang->formatExpiry( $expiry, $timestampType );
990 * Get a timestamp of the expiry for autoblocks
994 public static function getAutoblockExpiry( $timestamp ) {
995 global $wgAutoblockExpiry;
997 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1001 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
1002 * For example, 127.111.113.151/24 -> 127.111.113.0/24
1003 * @param $range String: IP address to normalize
1005 * @deprecated since 1.18, call IP::sanitizeRange() directly
1007 public static function normaliseRange( $range ) {
1008 return IP
::sanitizeRange( $range );
1012 * Purge expired blocks from the ipblocks table
1014 public static function purgeExpired() {
1015 $dbw = wfGetDB( DB_MASTER
);
1016 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
1020 * Get a value to insert into expiry field of the database when infinite expiry
1022 * @deprecated since 1.18, call $dbr->getInfinity() directly
1025 public static function infinity() {
1026 return wfGetDB( DB_SLAVE
)->getInfinity();
1030 * Convert a DB-encoded expiry into a real string that humans can read.
1032 * @param $encoded_expiry String: Database encoded expiry time
1033 * @return Html-escaped String
1034 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
1036 public static function formatExpiry( $encoded_expiry ) {
1040 if ( is_null( $msg ) ) {
1042 $keys = array( 'infiniteblock', 'expiringblock' );
1044 foreach ( $keys as $key ) {
1045 $msg[$key] = wfMsgHtml( $key );
1049 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW
);
1050 if ( $expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
1051 $expirystr = $msg['infiniteblock'];
1054 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
1055 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
1056 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
1062 # FIXME: everything above here is a mess, needs much cleaning up
1065 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1066 * ("24 May 2034"), into an absolute timestamp we can put into the database.
1067 * @param $expiry String: whatever was typed into the form
1068 * @return String: timestamp or "infinity" string for th DB implementation
1069 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
1071 public static function parseExpiryInput( $expiry ) {
1072 wfDeprecated( __METHOD__
);
1073 return SpecialBlock
::parseExpiryInput( $expiry );
1077 * Given a target and the target's type, get an existing Block object if possible.
1078 * @param $specificTarget String|User|Int a block target, which may be one of several types:
1079 * * A user to block, in which case $target will be a User
1080 * * An IP to block, in which case $target will be a User generated by using
1081 * User::newFromName( $ip, false ) to turn off name validation
1082 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1083 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1085 * Calling this with a user, IP address or range will not select autoblocks, and will
1086 * only select a block where the targets match exactly (so looking for blocks on
1087 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1088 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
1089 * affects that target (so for an IP address, get ranges containing that IP; and also
1090 * get any relevant autoblocks)
1091 * @param $fromMaster Bool whether to use the DB_MASTER database
1092 * @return Block|null (null if no relevant block could be found). The target and type
1093 * of the returned Block will refer to the actual block which was found, which might
1094 * not be the same as the target you gave if you used $vagueTarget!
1096 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1097 list( $target, $type ) = self
::parseTarget( $specificTarget );
1098 if( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
){
1099 return Block
::newFromID( $target );
1101 } elseif( in_array( $type, array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) ) ) {
1102 $block = new Block();
1103 $block->fromMaster( $fromMaster );
1105 if( $type !== null ){
1106 $block->setTarget( $target );
1109 if( $block->newLoad( $vagueTarget ) ){
1120 * From an existing Block, get the target and the type of target. Note that it is
1121 * always safe to treat the target as a string; for User objects this will return
1122 * User::__toString() which in turn gives User::getName().
1123 * @return array( User|String, Block::TYPE_ constant )
1125 public static function parseTarget( $target ) {
1126 $target = trim( $target );
1128 # We may have been through this before
1129 if( $target instanceof User
){
1130 if( IP
::isValid( $target->getName() ) ){
1131 return self
::TYPE_IP
;
1133 return self
::TYPE_USER
;
1135 } elseif( $target === null ){
1136 return array( null, null );
1139 $userObj = User
::newFromName( $target );
1140 if ( $userObj instanceof User
) {
1141 # Note that since numbers are valid usernames, a $target of "12345" will be
1142 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1143 # since hash characters are not valid in usernames or titles generally.
1144 return array( $userObj, Block
::TYPE_USER
);
1146 } elseif ( IP
::isValid( $target ) ) {
1147 # We can still create a User if it's an IP address, but we need to turn
1148 # off validation checking (which would exclude IP addresses)
1150 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1154 } elseif ( IP
::isValidBlock( $target ) ) {
1155 # Can't create a User from an IP range
1156 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1158 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1159 # Autoblock reference in the form "#12345"
1160 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1164 return array( null, null );
1169 * Get the type of target for this particular block
1170 * @return Block::TYPE_ constant, will never be TYPE_ID
1172 public function getType() {
1179 * Get the target and target type for this particular Block. Note that for autoblocks,
1180 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1181 * in this situation.
1182 * @return array( User|String, Block::TYPE_ constant )
1183 * FIXME: this should be an integral part of the Block member variables
1185 public function getTargetAndType() {
1186 return array( $this->getTarget(), $this->getType() );
1190 * Get the target for this particular Block. Note that for autoblocks,
1191 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1192 * in this situation.
1193 * @return User|String
1195 public function getTarget() {
1196 return $this->target
;
1200 * Set the target for this block, and update $this->type accordingly
1201 * @param $target Mixed
1203 public function setTarget( $target ){
1204 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1206 $this->mAddress
= (string)$this->target
;
1207 if( $this->type
== self
::TYPE_USER
){
1208 if( $this->target
instanceof User
){
1210 $this->mUser
= $this->target
->getID();
1212 $this->mUser
= User
::idFromName( $this->target
);
1220 * Get the user who implemented this block
1223 public function getBlocker(){
1224 return $this->blocker
;
1228 * Set the user who implemented (or will implement) this block
1231 public function setBlocker( User
$user ){
1232 $this->blocker
= $user;
1234 $this->mBy
= $user->getID();
1235 $this->mByName
= $user->getName();