3 * Blocks and bans object
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 /* public*/ var $mReason, $mTimestamp, $mAuto, $mExpiry, $mHideName;
36 /// @var Block::TYPE_ constant. Can only be USER, IP or RANGE internally
43 protected $isHardblock = true;
46 protected $isAutoblocking = true;
57 * @todo FIXME: Don't know what the best format to have for this constructor is, but fourteen
58 * optional parameters certainly isn't it.
60 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
61 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
62 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0 )
64 if( $timestamp === 0 ){
65 $timestamp = wfTimestampNow();
68 if( count( func_get_args() ) > 0 ){
70 # wfDeprecated( __METHOD__ . " with arguments" );
73 $this->setTarget( $address );
74 $this->setBlocker( User
::newFromID( $by ) );
75 $this->mReason
= $reason;
76 $this->mTimestamp
= wfTimestamp( TS_MW
, $timestamp );
78 $this->isHardblock( !$anonOnly );
79 $this->prevents( 'createaccount', $createAccount );
80 if ( $expiry == 'infinity' ||
$expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
81 $this->mExpiry
= 'infinity';
83 $this->mExpiry
= wfTimestamp( TS_MW
, $expiry );
85 $this->isAutoblocking( $enableAutoblock );
86 $this->mHideName
= $hideName;
87 $this->prevents( 'sendemail', $blockEmail );
88 $this->prevents( 'editownusertalk', !$allowUsertalk );
90 $this->mFromMaster
= false;
94 * Load a block from the database, using either the IP address or
95 * user ID. Tries the user ID first, and if that doesn't work, tries
98 * @param $address String: IP address of user/anon
99 * @param $user Integer: user id of user
100 * @return Block Object
101 * @deprecated since 1.18
103 public static function newFromDB( $address, $user = 0 ) {
104 return self
::newFromTarget( User
::whoIs( $user ), $address );
108 * Load a blocked user from their block id.
110 * @param $id Integer: Block id to search for
111 * @return Block object or null
113 public static function newFromID( $id ) {
114 $dbr = wfGetDB( DB_SLAVE
);
115 $res = $dbr->selectRow(
118 array( 'ipb_id' => $id ),
122 return Block
::newFromRow( $res );
129 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
130 * the blocking user or the block timestamp, only things which affect the blocked user *
132 * @param $block Block
136 public function equals( Block
$block ) {
138 (string)$this->target
== (string)$block->target
139 && $this->type
== $block->type
140 && $this->mAuto
== $block->mAuto
141 && $this->isHardblock() == $block->isHardblock()
142 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
143 && $this->mExpiry
== $block->mExpiry
144 && $this->isAutoblocking() == $block->isAutoblocking()
145 && $this->mHideName
== $block->mHideName
146 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
147 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
148 && $this->mReason
== $block->mReason
153 * Clear all member variables in the current object. Does not clear
154 * the block from the DB.
155 * @deprecated since 1.18
157 public function clear() {
162 * Get a block from the DB, with either the given address or the given username
164 * @param $address string The IP address of the user, or blank to skip IP blocks
165 * @param $user int The user ID, or zero for anonymous users
166 * @return Boolean: the user is blocked from editing
167 * @deprecated since 1.18
169 public function load( $address = '', $user = 0 ) {
170 wfDeprecated( __METHOD__
);
172 $username = User
::whoIs( $user );
173 $block = self
::newFromTarget( $username, $address );
175 $block = self
::newFromTarget( null, $address );
178 if( $block instanceof Block
){
179 # This is mildly evil, but hey, it's B/C :D
180 foreach( $block as $variable => $value ){
181 $this->$variable = $value;
190 * Load a block from the database which affects the already-set $this->target:
191 * 1) A block directly on the given user or IP
192 * 2) A rangeblock encompasing the given IP (smallest first)
193 * 3) An autoblock on the given IP
194 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
195 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
196 * @return Bool whether a relevant block was found
198 protected function newLoad( $vagueTarget = null ) {
199 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
201 if( $this->type
!== null ){
203 'ipb_address' => array( (string)$this->target
),
206 $conds = array( 'ipb_address' => array() );
209 # Be aware that the != '' check is explicit, since empty values will be
210 # passed by some callers (bug 29116)
211 if( $vagueTarget != ''){
212 list( $target, $type ) = self
::parseTarget( $vagueTarget );
214 case self
::TYPE_USER
:
215 # Slightly wierd, but who are we to argue?
216 $conds['ipb_address'][] = (string)$target;
220 $conds['ipb_address'][] = (string)$target;
221 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
222 $conds = $db->makeList( $conds, LIST_OR
);
225 case self
::TYPE_RANGE
:
226 list( $start, $end ) = IP
::parseRange( $target );
227 $conds['ipb_address'][] = (string)$target;
228 $conds[] = self
::getRangeCond( $start, $end );
229 $conds = $db->makeList( $conds, LIST_OR
);
233 throw new MWException( "Tried to load block with invalid type" );
237 $res = $db->select( 'ipblocks', '*', $conds, __METHOD__
);
239 # This result could contain a block on the user, a block on the IP, and a russian-doll
240 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
243 # Lower will be better
244 $bestBlockScore = 100;
246 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
247 $bestBlockPreventsEdit = null;
249 foreach( $res as $row ){
250 $block = Block
::newFromRow( $row );
252 # Don't use expired blocks
253 if( $block->deleteIfExpired() ){
257 # Don't use anon only blocks on users
258 if( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ){
262 if( $block->getType() == self
::TYPE_RANGE
){
263 # This is the number of bits that are allowed to vary in the block, give
264 # or take some floating point errors
265 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
266 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
267 $size = log( $end - $start +
1, 2 );
269 # This has the nice property that a /32 block is ranked equally with a
270 # single-IP block, which is exactly what it is...
271 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
274 $score = $block->getType();
277 if( $score < $bestBlockScore ){
278 $bestBlockScore = $score;
280 $bestBlockPreventsEdit = $block->prevents( 'edit' );
284 if( $bestRow !== null ){
285 $this->initFromRow( $bestRow );
286 $this->prevents( 'edit', $bestBlockPreventsEdit );
294 * Get a set of SQL conditions which will select rangeblocks encompasing a given range
295 * @param $start String Hexadecimal IP representation
296 * @param $end String Hexadecimal IP represenation, or null to use $start = $end
299 public static function getRangeCond( $start, $end = null ) {
300 if ( $end === null ) {
303 # Per bug 14634, we want to include relevant active rangeblocks; for
304 # rangeblocks, we want to include larger ranges which enclose the given
305 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
306 # so we can improve performance by filtering on a LIKE clause
307 $chunk = self
::getIpFragment( $start );
308 $dbr = wfGetDB( DB_SLAVE
);
309 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
311 # Fairly hard to make a malicious SQL statement out of hex characters,
312 # but stranger things have happened...
313 $safeStart = $dbr->addQuotes( $start );
314 $safeEnd = $dbr->addQuotes( $end );
316 return $dbr->makeList(
318 "ipb_range_start $like",
319 "ipb_range_start <= $safeStart",
320 "ipb_range_end >= $safeEnd",
327 * Get the component of an IP address which is certain to be the same between an IP
328 * address and a rangeblock containing that IP address.
329 * @param $hex String Hexadecimal IP representation
332 protected static function getIpFragment( $hex ) {
333 global $wgBlockCIDRLimit;
334 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
335 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
337 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
342 * Given a database row from the ipblocks table, initialize
344 * @param $row ResultWrapper: a row from the ipblocks table
346 protected function initFromRow( $row ) {
347 $this->setTarget( $row->ipb_address
);
348 $this->setBlocker( User
::newFromId( $row->ipb_by
) );
350 $this->mReason
= $row->ipb_reason
;
351 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
352 $this->mAuto
= $row->ipb_auto
;
353 $this->mHideName
= $row->ipb_deleted
;
354 $this->mId
= $row->ipb_id
;
356 // I wish I didn't have to do this
357 $db = wfGetDB( DB_SLAVE
);
358 if ( $row->ipb_expiry
== $db->getInfinity() ) {
359 $this->mExpiry
= 'infinity';
361 $this->mExpiry
= wfTimestamp( TS_MW
, $row->ipb_expiry
);
364 $this->isHardblock( !$row->ipb_anon_only
);
365 $this->isAutoblocking( $row->ipb_enable_autoblock
);
367 $this->prevents( 'createaccount', $row->ipb_create_account
);
368 $this->prevents( 'sendemail', $row->ipb_block_email
);
369 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
373 * Create a new Block object from a database row
374 * @param $row ResultWrapper row from the ipblocks table
377 public static function newFromRow( $row ){
379 $block->initFromRow( $row );
384 * Delete the row from the IP blocks table.
388 public function delete() {
389 if ( wfReadOnly() ) {
393 if ( !$this->getId() ) {
394 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
397 $dbw = wfGetDB( DB_MASTER
);
398 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__
);
400 return $dbw->affectedRows() > 0;
404 * Insert a block into the block table. Will fail if there is a conflicting
405 * block (same name and options) already in the database.
407 * @param $dbw DatabaseBase if you have one available
408 * @return mixed: false on failure, assoc array on success:
409 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
411 public function insert( $dbw = null ) {
412 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
414 if ( $dbw === null ) {
415 $dbw = wfGetDB( DB_MASTER
);
418 # Don't collide with expired blocks
419 Block
::purgeExpired();
421 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
424 $this->getDatabaseArray(),
428 $affected = $dbw->affectedRows();
429 $this->mId
= $dbw->insertId();
432 $auto_ipd_ids = $this->doRetroactiveAutoblock();
433 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
440 * Update a block in the DB with new parameters.
441 * The ID field needs to be loaded first.
443 * @return Int number of affected rows, which should probably be 1 or something's
446 public function update() {
447 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
448 $dbw = wfGetDB( DB_MASTER
);
452 $this->getDatabaseArray( $dbw ),
453 array( 'ipb_id' => $this->getId() ),
457 return $dbw->affectedRows();
461 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
462 * @param $db DatabaseBase
465 protected function getDatabaseArray( $db = null ){
467 $db = wfGetDB( DB_SLAVE
);
469 $expiry = $db->encodeExpiry( $this->mExpiry
);
472 'ipb_address' => (string)$this->target
,
473 'ipb_user' => $this->target
instanceof User ?
$this->target
->getID() : 0,
474 'ipb_by' => $this->getBlocker()->getId(),
475 'ipb_by_text' => $this->getBlocker()->getName(),
476 'ipb_reason' => $this->mReason
,
477 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
478 'ipb_auto' => $this->mAuto
,
479 'ipb_anon_only' => !$this->isHardblock(),
480 'ipb_create_account' => $this->prevents( 'createaccount' ),
481 'ipb_enable_autoblock' => $this->isAutoblocking(),
482 'ipb_expiry' => $expiry,
483 'ipb_range_start' => $this->getRangeStart(),
484 'ipb_range_end' => $this->getRangeEnd(),
485 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
486 'ipb_block_email' => $this->prevents( 'sendemail' ),
487 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' )
494 * Retroactively autoblocks the last IP used by the user (if it is a user)
495 * blocked by this Block.
497 * @return Array: block IDs of retroactive autoblocks made
499 protected function doRetroactiveAutoblock() {
501 # If autoblock is enabled, autoblock the LAST IP(s) used
502 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
503 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
505 $continue = wfRunHooks(
506 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
509 self
::defaultRetroactiveAutoblock( $this, $blockIds );
516 * Retroactively autoblocks the last IP used by the user (if it is a user)
517 * blocked by this Block. This will use the recentchanges table.
519 * @param Block $block
520 * @param Array &$blockIds
521 * @return Array: block IDs of retroactive autoblocks made
523 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
524 $dbr = wfGetDB( DB_SLAVE
);
526 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
527 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
529 // Just the last IP used.
530 $options['LIMIT'] = 1;
532 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
533 __METHOD__
, $options );
535 if ( !$dbr->numRows( $res ) ) {
536 # No results, don't autoblock anything
537 wfDebug( "No IP found to retroactively autoblock\n" );
539 foreach ( $res as $row ) {
541 $id = $block->doAutoblock( $row->rc_ip
);
542 if ( $id ) $blockIds[] = $id;
549 * Checks whether a given IP is on the autoblock whitelist.
550 * TODO: this probably belongs somewhere else, but not sure where...
552 * @param $ip String: The IP to check
555 public static function isWhitelistedFromAutoblocks( $ip ) {
558 // Try to get the autoblock_whitelist from the cache, as it's faster
559 // than getting the msg raw and explode()'ing it.
560 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
561 $lines = $wgMemc->get( $key );
563 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
564 $wgMemc->set( $key, $lines, 3600 * 24 );
567 wfDebug( "Checking the autoblock whitelist..\n" );
569 foreach ( $lines as $line ) {
571 if ( substr( $line, 0, 1 ) !== '*' ) {
575 $wlEntry = substr( $line, 1 );
576 $wlEntry = trim( $wlEntry );
578 wfDebug( "Checking $ip against $wlEntry..." );
580 # Is the IP in this range?
581 if ( IP
::isInRange( $ip, $wlEntry ) ) {
582 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
585 wfDebug( " No match\n" );
593 * Autoblocks the given IP, referring to this Block.
595 * @param $autoblockIP String: the IP to autoblock.
596 * @return mixed: block ID if an autoblock was inserted, false if not.
598 public function doAutoblock( $autoblockIP ) {
599 # If autoblocks are disabled, go away.
600 if ( !$this->isAutoblocking() ) {
604 # Check for presence on the autoblock whitelist.
605 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
609 # Allow hooks to cancel the autoblock.
610 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
611 wfDebug( "Autoblock aborted by hook.\n" );
615 # It's okay to autoblock. Go ahead and insert/update the block...
617 # Do not add a *new* block if the IP is already blocked.
618 $ipblock = Block
::newFromTarget( $autoblockIP );
620 # Check if the block is an autoblock and would exceed the user block
621 # if renewed. If so, do nothing, otherwise prolong the block time...
622 if ( $ipblock->mAuto
&& // @TODO: why not compare $ipblock->mExpiry?
623 $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
625 # Reset block timestamp to now and its expiry to
626 # $wgAutoblockExpiry in the future
627 $ipblock->updateTimestamp();
632 # Make a new block object with the desired properties.
633 $autoblock = new Block
;
634 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
635 $autoblock->setTarget( $autoblockIP );
636 $autoblock->setBlocker( $this->getBlocker() );
637 $autoblock->mReason
= wfMsgForContent( 'autoblocker', $this->getTarget(), $this->mReason
);
638 $timestamp = wfTimestampNow();
639 $autoblock->mTimestamp
= $timestamp;
640 $autoblock->mAuto
= 1;
641 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
642 # Continue suppressing the name if needed
643 $autoblock->mHideName
= $this->mHideName
;
644 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
646 if ( $this->mExpiry
== 'infinity' ) {
647 # Original block was indefinite, start an autoblock now
648 $autoblock->mExpiry
= Block
::getAutoblockExpiry( $timestamp );
650 # If the user is already blocked with an expiry date, we don't
651 # want to pile on top of that.
652 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $timestamp ) );
655 # Insert the block...
656 $status = $autoblock->insert();
663 * Check if a block has expired. Delete it if it is.
666 public function deleteIfExpired() {
667 wfProfileIn( __METHOD__
);
669 if ( $this->isExpired() ) {
670 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
674 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
678 wfProfileOut( __METHOD__
);
683 * Has the block expired?
686 public function isExpired() {
687 $timestamp = wfTimestampNow();
688 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
690 if ( !$this->mExpiry
) {
693 return $timestamp > $this->mExpiry
;
698 * Is the block address valid (i.e. not a null string?)
701 public function isValid() {
702 return $this->getTarget() != null;
706 * Update the timestamp on autoblocks.
708 public function updateTimestamp() {
709 if ( $this->mAuto
) {
710 $this->mTimestamp
= wfTimestamp();
711 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
713 $dbw = wfGetDB( DB_MASTER
);
714 $dbw->update( 'ipblocks',
716 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
717 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
720 'ipb_address' => (string)$this->getTarget()
728 * Get the IP address at the start of the range in Hex form
729 * @return String IP in Hex form
731 public function getRangeStart() {
732 switch( $this->type
) {
733 case self
::TYPE_USER
:
736 return IP
::toHex( $this->target
);
737 case self
::TYPE_RANGE
:
738 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
740 default: throw new MWException( "Block with invalid type" );
745 * Get the IP address at the start of the range in Hex form
746 * @return String IP in Hex form
748 public function getRangeEnd() {
749 switch( $this->type
) {
750 case self
::TYPE_USER
:
753 return IP
::toHex( $this->target
);
754 case self
::TYPE_RANGE
:
755 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
757 default: throw new MWException( "Block with invalid type" );
762 * Get the user id of the blocking sysop
766 public function getBy() {
767 return $this->getBlocker() instanceof User
768 ?
$this->getBlocker()->getId()
773 * Get the username of the blocking sysop
777 public function getByName() {
778 return $this->getBlocker() instanceof User
779 ?
$this->getBlocker()->getName()
787 public function getId() {
792 * Get/set the SELECT ... FOR UPDATE flag
793 * @deprecated since 1.18
797 public function forUpdate( $x = null ) {
802 * Get/set a flag determining whether the master is used for reads
807 public function fromMaster( $x = null ) {
808 return wfSetVar( $this->mFromMaster
, $x );
812 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
816 public function isHardblock( $x = null ) {
817 wfSetVar( $this->isHardblock
, $x );
819 # You can't *not* hardblock a user
820 return $this->getType() == self
::TYPE_USER
822 : $this->isHardblock
;
825 public function isAutoblocking( $x = null ) {
826 wfSetVar( $this->isAutoblocking
, $x );
828 # You can't put an autoblock on an IP or range as we don't have any history to
829 # look over to get more IPs from
830 return $this->getType() == self
::TYPE_USER
831 ?
$this->isAutoblocking
836 * Get/set whether the Block prevents a given action
837 * @param $action String
841 public function prevents( $action, $x = null ) {
844 # For now... <evil laugh>
847 case 'createaccount':
848 return wfSetVar( $this->mCreateAccount
, $x );
851 return wfSetVar( $this->mBlockEmail
, $x );
853 case 'editownusertalk':
854 return wfSetVar( $this->mDisableUsertalk
, $x );
862 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
863 * @return String, text is escaped
865 public function getRedactedName() {
866 if ( $this->mAuto
) {
867 return Html
::rawElement(
869 array( 'class' => 'mw-autoblockid' ),
870 wfMessage( 'autoblockid', $this->mId
)
873 return htmlspecialchars( $this->getTarget() );
878 * Encode expiry for DB
880 * @param $expiry String: timestamp for expiry, or
881 * @param $db Database object
883 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
885 public static function encodeExpiry( $expiry, $db ) {
886 return $db->encodeExpiry( $expiry );
890 * Decode expiry which has come from the DB
892 * @param $expiry String: Database expiry format
893 * @param $timestampType Int Requested timestamp format
895 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
897 public static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
899 return $wgContLang->formatExpiry( $expiry, $timestampType );
903 * Get a timestamp of the expiry for autoblocks
905 * @param $timestamp String|Int
908 public static function getAutoblockExpiry( $timestamp ) {
909 global $wgAutoblockExpiry;
911 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
915 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
916 * For example, 127.111.113.151/24 -> 127.111.113.0/24
917 * @param $range String: IP address to normalize
919 * @deprecated since 1.18, call IP::sanitizeRange() directly
921 public static function normaliseRange( $range ) {
922 return IP
::sanitizeRange( $range );
926 * Purge expired blocks from the ipblocks table
928 public static function purgeExpired() {
929 $dbw = wfGetDB( DB_MASTER
);
930 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
934 * Get a value to insert into expiry field of the database when infinite expiry
936 * @deprecated since 1.18, call $dbr->getInfinity() directly
939 public static function infinity() {
940 return wfGetDB( DB_SLAVE
)->getInfinity();
944 * Convert a DB-encoded expiry into a real string that humans can read.
946 * @param $encoded_expiry String: Database encoded expiry time
947 * @return Html-escaped String
948 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
950 public static function formatExpiry( $encoded_expiry ) {
954 if ( is_null( $msg ) ) {
956 $keys = array( 'infiniteblock', 'expiringblock' );
958 foreach ( $keys as $key ) {
959 $msg[$key] = wfMsgHtml( $key );
963 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW
);
964 if ( $expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
965 $expirystr = $msg['infiniteblock'];
968 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
969 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
970 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
977 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
978 * ("24 May 2034"), into an absolute timestamp we can put into the database.
979 * @param $expiry String: whatever was typed into the form
980 * @return String: timestamp or "infinity" string for th DB implementation
981 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
983 public static function parseExpiryInput( $expiry ) {
984 wfDeprecated( __METHOD__
);
985 return SpecialBlock
::parseExpiryInput( $expiry );
989 * Given a target and the target's type, get an existing Block object if possible.
990 * @param $specificTarget String|User|Int a block target, which may be one of several types:
991 * * A user to block, in which case $target will be a User
992 * * An IP to block, in which case $target will be a User generated by using
993 * User::newFromName( $ip, false ) to turn off name validation
994 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
995 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
997 * Calling this with a user, IP address or range will not select autoblocks, and will
998 * only select a block where the targets match exactly (so looking for blocks on
999 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1000 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
1001 * affects that target (so for an IP address, get ranges containing that IP; and also
1002 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1003 * @param $fromMaster Bool whether to use the DB_MASTER database
1004 * @return Block|null (null if no relevant block could be found). The target and type
1005 * of the returned Block will refer to the actual block which was found, which might
1006 * not be the same as the target you gave if you used $vagueTarget!
1008 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1010 list( $target, $type ) = self
::parseTarget( $specificTarget );
1011 if( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
){
1012 return Block
::newFromID( $target );
1014 } elseif( $target === null && $vagueTarget == '' ){
1015 # We're not going to find anything useful here
1016 # Be aware that the == '' check is explicit, since empty values will be
1017 # passed by some callers (bug 29116)
1020 } elseif( in_array( $type, array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) ) ) {
1021 $block = new Block();
1022 $block->fromMaster( $fromMaster );
1024 if( $type !== null ){
1025 $block->setTarget( $target );
1028 if( $block->newLoad( $vagueTarget ) ){
1039 * From an existing Block, get the target and the type of target. Note that it is
1040 * always safe to treat the target as a string; for User objects this will return
1041 * User::__toString() which in turn gives User::getName().
1043 * @param $target String|Int|User
1044 * @return array( User|String, Block::TYPE_ constant )
1046 public static function parseTarget( $target ) {
1047 $target = trim( $target );
1049 # We may have been through this before
1050 if( $target instanceof User
){
1051 if( IP
::isValid( $target->getName() ) ){
1052 return array( $target, self
::TYPE_IP
);
1054 return array( $target, self
::TYPE_USER
);
1056 } elseif( $target === null ){
1057 return array( null, null );
1060 if ( IP
::isValid( $target ) ) {
1061 # We can still create a User if it's an IP address, but we need to turn
1062 # off validation checking (which would exclude IP addresses)
1064 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1068 } elseif ( IP
::isValidBlock( $target ) ) {
1069 # Can't create a User from an IP range
1070 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1073 # Consider the possibility that this is not a username at all
1074 # but actually an old subpage (bug #29797)
1075 if( strpos( $target, '/' ) !== false ){
1076 # An old subpage, drill down to the user behind it
1077 $parts = explode( '/', $target );
1078 $target = $parts[0];
1081 $userObj = User
::newFromName( $target );
1082 if ( $userObj instanceof User
) {
1083 # Note that since numbers are valid usernames, a $target of "12345" will be
1084 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1085 # since hash characters are not valid in usernames or titles generally.
1086 return array( $userObj, Block
::TYPE_USER
);
1088 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1089 # Autoblock reference in the form "#12345"
1090 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1094 return array( null, null );
1099 * Get the type of target for this particular block
1100 * @return Block::TYPE_ constant, will never be TYPE_ID
1102 public function getType() {
1109 * Get the target and target type for this particular Block. Note that for autoblocks,
1110 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1111 * in this situation.
1112 * @return array( User|String, Block::TYPE_ constant )
1113 * @todo FIXME: This should be an integral part of the Block member variables
1115 public function getTargetAndType() {
1116 return array( $this->getTarget(), $this->getType() );
1120 * Get the target for this particular Block. Note that for autoblocks,
1121 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1122 * in this situation.
1123 * @return User|String
1125 public function getTarget() {
1126 return $this->target
;
1130 * Set the target for this block, and update $this->type accordingly
1131 * @param $target Mixed
1133 public function setTarget( $target ){
1134 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1138 * Get the user who implemented this block
1141 public function getBlocker(){
1142 return $this->blocker
;
1146 * Set the user who implemented (or will implement) this block
1149 public function setBlocker( User
$user ){
1150 $this->blocker
= $user;