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, $mAngryAutoblock;
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 $this->mExpiry
= $expiry;
81 $this->isAutoblocking( $enableAutoblock );
82 $this->mHideName
= $hideName;
83 $this->prevents( 'sendemail', $blockEmail );
84 $this->prevents( 'editownusertalk', !$allowUsertalk );
86 $this->mFromMaster
= false;
87 $this->mAngryAutoblock
= false;
91 * Load a block from the database, using either the IP address or
92 * user ID. Tries the user ID first, and if that doesn't work, tries
95 * @param $address String: IP address of user/anon
96 * @param $user Integer: user id of user
97 * @return Block Object
98 * @deprecated since 1.18
100 public static function newFromDB( $address, $user = 0 ) {
101 return self
::newFromTarget( User
::whoIs( $user ), $address );
105 * Load a blocked user from their block id.
107 * @param $id Integer: Block id to search for
108 * @return Block object or null
110 public static function newFromID( $id ) {
111 $dbr = wfGetDB( DB_SLAVE
);
112 $res = $dbr->selectRow(
115 array( 'ipb_id' => $id ),
119 return Block
::newFromRow( $res );
126 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
127 * the blocking user or the block timestamp, only things which affect the blocked user *
129 * @param $block Block
133 public function equals( Block
$block ) {
135 (string)$this->target
== (string)$block->target
136 && $this->type
== $block->type
137 && $this->mAuto
== $block->mAuto
138 && $this->isHardblock() == $block->isHardblock()
139 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
140 && $this->mExpiry
== $block->mExpiry
141 && $this->isAutoblocking() == $block->isAutoblocking()
142 && $this->mHideName
== $block->mHideName
143 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
144 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
145 && $this->mReason
== $block->mReason
150 * Clear all member variables in the current object. Does not clear
151 * the block from the DB.
152 * @deprecated since 1.18
154 public function clear() {
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 * @return Boolean: the user is blocked from editing
164 * @deprecated since 1.18
166 public function load( $address = '', $user = 0 ) {
167 wfDeprecated( __METHOD__
);
169 $username = User
::whoIs( $user );
170 $block = self
::newFromTarget( $username, $address );
172 $block = self
::newFromTarget( null, $address );
175 if( $block instanceof Block
){
176 # This is mildly evil, but hey, it's B/C :D
177 foreach( $block as $variable => $value ){
178 $this->$variable = $value;
187 * Load a block from the database which affects the already-set $this->target:
188 * 1) A block directly on the given user or IP
189 * 2) A rangeblock encompasing the given IP (smallest first)
190 * 3) An autoblock on the given IP
191 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
192 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
193 * @return Bool whether a relevant block was found
195 protected function newLoad( $vagueTarget = null ) {
196 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
198 if( $this->type
!== null ){
200 'ipb_address' => array( (string)$this->target
),
203 $conds = array( 'ipb_address' => array() );
206 # Be aware that the != '' check is explicit, since empty values will be
207 # passed by some callers (bug 29116)
208 if( $vagueTarget != ''){
209 list( $target, $type ) = self
::parseTarget( $vagueTarget );
211 case self
::TYPE_USER
:
212 # Slightly wierd, but who are we to argue?
213 $conds['ipb_address'][] = (string)$target;
217 $conds['ipb_address'][] = (string)$target;
218 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
219 $conds = $db->makeList( $conds, LIST_OR
);
222 case self
::TYPE_RANGE
:
223 list( $start, $end ) = IP
::parseRange( $target );
224 $conds['ipb_address'][] = (string)$target;
225 $conds[] = self
::getRangeCond( $start, $end );
226 $conds = $db->makeList( $conds, LIST_OR
);
230 throw new MWException( "Tried to load block with invalid type" );
234 $res = $db->select( 'ipblocks', '*', $conds, __METHOD__
);
236 # This result could contain a block on the user, a block on the IP, and a russian-doll
237 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
240 # Lower will be better
241 $bestBlockScore = 100;
243 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
244 $bestBlockPreventsEdit = null;
246 foreach( $res as $row ){
247 $block = Block
::newFromRow( $row );
249 # Don't use expired blocks
250 if( $block->deleteIfExpired() ){
254 # Don't use anon only blocks on users
255 if( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ){
259 if( $block->getType() == self
::TYPE_RANGE
){
260 # This is the number of bits that are allowed to vary in the block, give
261 # or take some floating point errors
262 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
263 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
264 $size = log( $end - $start +
1, 2 );
266 # This has the nice property that a /32 block is ranked equally with a
267 # single-IP block, which is exactly what it is...
268 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
271 $score = $block->getType();
274 if( $score < $bestBlockScore ){
275 $bestBlockScore = $score;
277 $bestBlockPreventsEdit = $block->prevents( 'edit' );
281 if( $bestRow !== null ){
282 $this->initFromRow( $bestRow );
283 $this->prevents( 'edit', $bestBlockPreventsEdit );
291 * Get a set of SQL conditions which will select rangeblocks encompasing a given range
292 * @param $start String Hexadecimal IP representation
293 * @param $end String Hexadecimal IP represenation, or null to use $start = $end
296 public static function getRangeCond( $start, $end = null ) {
297 if ( $end === null ) {
300 # Per bug 14634, we want to include relevant active rangeblocks; for
301 # rangeblocks, we want to include larger ranges which enclose the given
302 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
303 # so we can improve performance by filtering on a LIKE clause
304 $chunk = self
::getIpFragment( $start );
305 $dbr = wfGetDB( DB_SLAVE
);
306 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
308 # Fairly hard to make a malicious SQL statement out of hex characters,
309 # but stranger things have happened...
310 $safeStart = $dbr->addQuotes( $start );
311 $safeEnd = $dbr->addQuotes( $end );
313 return $dbr->makeList(
315 "ipb_range_start $like",
316 "ipb_range_start <= $safeStart",
317 "ipb_range_end >= $safeEnd",
324 * Get the component of an IP address which is certain to be the same between an IP
325 * address and a rangeblock containing that IP address.
326 * @param $hex String Hexadecimal IP representation
329 protected static function getIpFragment( $hex ) {
330 global $wgBlockCIDRLimit;
331 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
332 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
334 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
339 * Given a database row from the ipblocks table, initialize
341 * @param $row ResultWrapper: a row from the ipblocks table
343 protected function initFromRow( $row ) {
344 $this->setTarget( $row->ipb_address
);
345 $this->setBlocker( User
::newFromId( $row->ipb_by
) );
347 $this->mReason
= $row->ipb_reason
;
348 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
349 $this->mAuto
= $row->ipb_auto
;
350 $this->mHideName
= $row->ipb_deleted
;
351 $this->mId
= $row->ipb_id
;
352 $this->mExpiry
= $row->ipb_expiry
;
354 $this->isHardblock( !$row->ipb_anon_only
);
355 $this->isAutoblocking( $row->ipb_enable_autoblock
);
357 $this->prevents( 'createaccount', $row->ipb_create_account
);
358 $this->prevents( 'sendemail', $row->ipb_block_email
);
359 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
363 * Create a new Block object from a database row
364 * @param $row ResultWrapper row from the ipblocks table
367 public static function newFromRow( $row ){
369 $block->initFromRow( $row );
374 * Delete the row from the IP blocks table.
378 public function delete() {
379 if ( wfReadOnly() ) {
383 if ( !$this->getId() ) {
384 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
387 $dbw = wfGetDB( DB_MASTER
);
388 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__
);
390 return $dbw->affectedRows() > 0;
394 * Insert a block into the block table. Will fail if there is a conflicting
395 * block (same name and options) already in the database.
397 * @param $dbw DatabaseBase if you have one available
398 * @return mixed: false on failure, assoc array on success:
399 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
401 public function insert( $dbw = null ) {
402 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
404 if ( $dbw === null ) {
405 $dbw = wfGetDB( DB_MASTER
);
408 # Don't collide with expired blocks
409 Block
::purgeExpired();
411 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
414 $this->getDatabaseArray(),
418 $affected = $dbw->affectedRows();
419 $this->mId
= $dbw->insertId();
422 $auto_ipd_ids = $this->doRetroactiveAutoblock();
423 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
430 * Update a block in the DB with new parameters.
431 * The ID field needs to be loaded first.
433 * @return Int number of affected rows, which should probably be 1 or something's
436 public function update() {
437 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
438 $dbw = wfGetDB( DB_MASTER
);
442 $this->getDatabaseArray( $dbw ),
443 array( 'ipb_id' => $this->getId() ),
447 return $dbw->affectedRows();
451 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
452 * @param $db DatabaseBase
455 protected function getDatabaseArray( $db = null ){
457 $db = wfGetDB( DB_SLAVE
);
459 $this->mExpiry
= $db->encodeExpiry( $this->mExpiry
);
462 'ipb_address' => (string)$this->target
,
463 'ipb_user' => $this->target
instanceof User ?
$this->target
->getID() : 0,
464 'ipb_by' => $this->getBlocker()->getId(),
465 'ipb_by_text' => $this->getBlocker()->getName(),
466 'ipb_reason' => $this->mReason
,
467 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
468 'ipb_auto' => $this->mAuto
,
469 'ipb_anon_only' => !$this->isHardblock(),
470 'ipb_create_account' => $this->prevents( 'createaccount' ),
471 'ipb_enable_autoblock' => $this->isAutoblocking(),
472 'ipb_expiry' => $this->mExpiry
,
473 'ipb_range_start' => $this->getRangeStart(),
474 'ipb_range_end' => $this->getRangeEnd(),
475 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
476 'ipb_block_email' => $this->prevents( 'sendemail' ),
477 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' )
484 * Retroactively autoblocks the last IP used by the user (if it is a user)
485 * blocked by this Block.
487 * @return Array: block IDs of retroactive autoblocks made
489 protected function doRetroactiveAutoblock() {
492 $dbr = wfGetDB( DB_SLAVE
);
493 # If autoblock is enabled, autoblock the LAST IP used
494 # - stolen shamelessly from CheckUser_body.php
496 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
497 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
499 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
500 $conds = array( 'rc_user_text' => (string)$this->getTarget() );
502 if ( $this->mAngryAutoblock
) {
503 // Block any IP used in the last 7 days. Up to five IPs.
504 $conds[] = 'rc_timestamp < ' .
505 $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
506 $options['LIMIT'] = 5;
508 // Just the last IP used.
509 $options['LIMIT'] = 1;
512 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
513 __METHOD__
, $options );
515 if ( !$dbr->numRows( $res ) ) {
516 # No results, don't autoblock anything
517 wfDebug( "No IP found to retroactively autoblock\n" );
519 foreach ( $res as $row ) {
521 $id = $this->doAutoblock( $row->rc_ip
);
522 if ( $id ) $blockIds[] = $id;
531 * Checks whether a given IP is on the autoblock whitelist.
532 * TODO: this probably belongs somewhere else, but not sure where...
534 * @param $ip String: The IP to check
537 public static function isWhitelistedFromAutoblocks( $ip ) {
540 // Try to get the autoblock_whitelist from the cache, as it's faster
541 // than getting the msg raw and explode()'ing it.
542 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
543 $lines = $wgMemc->get( $key );
545 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
546 $wgMemc->set( $key, $lines, 3600 * 24 );
549 wfDebug( "Checking the autoblock whitelist..\n" );
551 foreach ( $lines as $line ) {
553 if ( substr( $line, 0, 1 ) !== '*' ) {
557 $wlEntry = substr( $line, 1 );
558 $wlEntry = trim( $wlEntry );
560 wfDebug( "Checking $ip against $wlEntry..." );
562 # Is the IP in this range?
563 if ( IP
::isInRange( $ip, $wlEntry ) ) {
564 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
567 wfDebug( " No match\n" );
575 * Autoblocks the given IP, referring to this Block.
577 * @param $autoblockIP String: the IP to autoblock.
578 * @return mixed: block ID if an autoblock was inserted, false if not.
580 public function doAutoblock( $autoblockIP ) {
581 # If autoblocks are disabled, go away.
582 if ( !$this->isAutoblocking() ) {
586 # Check for presence on the autoblock whitelist.
587 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
591 # Allow hooks to cancel the autoblock.
592 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
593 wfDebug( "Autoblock aborted by hook.\n" );
597 # It's okay to autoblock. Go ahead and insert/update the block...
599 # Do not add a *new* block if the IP is already blocked.
600 $ipblock = Block
::newFromTarget( $autoblockIP );
602 # Check if the block is an autoblock and would exceed the user block
603 # if renewed. If so, do nothing, otherwise prolong the block time...
604 if ( $ipblock->mAuto
&& // @TODO: why not compare $ipblock->mExpiry?
605 $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
607 # Reset block timestamp to now and its expiry to
608 # $wgAutoblockExpiry in the future
609 $ipblock->updateTimestamp();
614 # Make a new block object with the desired properties.
615 $autoblock = new Block
;
616 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
617 $autoblock->setTarget( $autoblockIP );
618 $autoblock->setBlocker( $this->getBlocker() );
619 $autoblock->mReason
= wfMsgForContent( 'autoblocker', $this->getTarget(), $this->mReason
);
620 $timestamp = wfTimestampNow();
621 $autoblock->mTimestamp
= $timestamp;
622 $autoblock->mAuto
= 1;
623 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
624 # Continue suppressing the name if needed
625 $autoblock->mHideName
= $this->mHideName
;
626 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
628 $dbr = wfGetDB( DB_SLAVE
);
629 if ( $this->mExpiry
== $dbr->getInfinity() ) {
630 # Original block was indefinite, start an autoblock now
631 $autoblock->mExpiry
= Block
::getAutoblockExpiry( $timestamp );
633 # If the user is already blocked with an expiry date, we don't
634 # want to pile on top of that.
635 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $timestamp ) );
638 # Insert the block...
639 $status = $autoblock->insert();
646 * Check if a block has expired. Delete it if it is.
649 public function deleteIfExpired() {
650 wfProfileIn( __METHOD__
);
652 if ( $this->isExpired() ) {
653 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
657 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
661 wfProfileOut( __METHOD__
);
666 * Has the block expired?
669 public function isExpired() {
670 $timestamp = wfTimestampNow();
671 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
673 if ( !$this->mExpiry
) {
676 return $timestamp > $this->mExpiry
;
681 * Is the block address valid (i.e. not a null string?)
684 public function isValid() {
685 return $this->getTarget() != null;
689 * Update the timestamp on autoblocks.
691 public function updateTimestamp() {
692 if ( $this->mAuto
) {
693 $this->mTimestamp
= wfTimestamp();
694 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
696 $dbw = wfGetDB( DB_MASTER
);
697 $dbw->update( 'ipblocks',
699 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
700 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
703 'ipb_address' => (string)$this->getTarget()
711 * Get the IP address at the start of the range in Hex form
712 * @return String IP in Hex form
714 public function getRangeStart() {
715 switch( $this->type
) {
716 case self
::TYPE_USER
:
719 return IP
::toHex( $this->target
);
720 case self
::TYPE_RANGE
:
721 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
723 default: throw new MWException( "Block with invalid type" );
728 * Get the IP address at the start of the range in Hex form
729 * @return String IP in Hex form
731 public function getRangeEnd() {
732 switch( $this->type
) {
733 case self
::TYPE_USER
:
736 return IP
::toHex( $this->target
);
737 case self
::TYPE_RANGE
:
738 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
740 default: throw new MWException( "Block with invalid type" );
745 * Get the user id of the blocking sysop
749 public function getBy() {
750 return $this->getBlocker() instanceof User
751 ?
$this->getBlocker()->getId()
756 * Get the username of the blocking sysop
760 public function getByName() {
761 return $this->getBlocker() instanceof User
762 ?
$this->getBlocker()->getName()
770 public function getId() {
775 * Get/set the SELECT ... FOR UPDATE flag
776 * @deprecated since 1.18
780 public function forUpdate( $x = null ) {
785 * Get/set a flag determining whether the master is used for reads
790 public function fromMaster( $x = null ) {
791 return wfSetVar( $this->mFromMaster
, $x );
795 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
799 public function isHardblock( $x = null ) {
800 wfSetVar( $this->isHardblock
, $x );
802 # You can't *not* hardblock a user
803 return $this->getType() == self
::TYPE_USER
805 : $this->isHardblock
;
808 public function isAutoblocking( $x = null ) {
809 wfSetVar( $this->isAutoblocking
, $x );
811 # You can't put an autoblock on an IP or range as we don't have any history to
812 # look over to get more IPs from
813 return $this->getType() == self
::TYPE_USER
814 ?
$this->isAutoblocking
819 * Get/set whether the Block prevents a given action
820 * @param $action String
824 public function prevents( $action, $x = null ) {
827 # For now... <evil laugh>
830 case 'createaccount':
831 return wfSetVar( $this->mCreateAccount
, $x );
834 return wfSetVar( $this->mBlockEmail
, $x );
836 case 'editownusertalk':
837 return wfSetVar( $this->mDisableUsertalk
, $x );
845 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
846 * @return String, text is escaped
848 public function getRedactedName() {
849 if ( $this->mAuto
) {
850 return Html
::rawElement(
852 array( 'class' => 'mw-autoblockid' ),
853 wfMessage( 'autoblockid', $this->mId
)
856 return htmlspecialchars( $this->getTarget() );
861 * Encode expiry for DB
863 * @param $expiry String: timestamp for expiry, or
864 * @param $db Database object
866 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
868 public static function encodeExpiry( $expiry, $db ) {
869 return $db->encodeExpiry( $expiry );
873 * Decode expiry which has come from the DB
875 * @param $expiry String: Database expiry format
876 * @param $timestampType Int Requested timestamp format
878 * @deprecated since 1.18; use $wgLang->decodeExpiry() instead
880 public static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
882 return $wgContLang->formatExpiry( $expiry, $timestampType );
886 * Get a timestamp of the expiry for autoblocks
888 * @param $timestamp String|Int
891 public static function getAutoblockExpiry( $timestamp ) {
892 global $wgAutoblockExpiry;
894 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
898 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
899 * For example, 127.111.113.151/24 -> 127.111.113.0/24
900 * @param $range String: IP address to normalize
902 * @deprecated since 1.18, call IP::sanitizeRange() directly
904 public static function normaliseRange( $range ) {
905 return IP
::sanitizeRange( $range );
909 * Purge expired blocks from the ipblocks table
911 public static function purgeExpired() {
912 $dbw = wfGetDB( DB_MASTER
);
913 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
917 * Get a value to insert into expiry field of the database when infinite expiry
919 * @deprecated since 1.18, call $dbr->getInfinity() directly
922 public static function infinity() {
923 return wfGetDB( DB_SLAVE
)->getInfinity();
927 * Convert a DB-encoded expiry into a real string that humans can read.
929 * @param $encoded_expiry String: Database encoded expiry time
930 * @return Html-escaped String
931 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
933 public static function formatExpiry( $encoded_expiry ) {
937 if ( is_null( $msg ) ) {
939 $keys = array( 'infiniteblock', 'expiringblock' );
941 foreach ( $keys as $key ) {
942 $msg[$key] = wfMsgHtml( $key );
946 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW
);
947 if ( $expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
948 $expirystr = $msg['infiniteblock'];
951 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
952 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
953 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
960 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
961 * ("24 May 2034"), into an absolute timestamp we can put into the database.
962 * @param $expiry String: whatever was typed into the form
963 * @return String: timestamp or "infinity" string for th DB implementation
964 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
966 public static function parseExpiryInput( $expiry ) {
967 wfDeprecated( __METHOD__
);
968 return SpecialBlock
::parseExpiryInput( $expiry );
972 * Given a target and the target's type, get an existing Block object if possible.
973 * @param $specificTarget String|User|Int a block target, which may be one of several types:
974 * * A user to block, in which case $target will be a User
975 * * An IP to block, in which case $target will be a User generated by using
976 * User::newFromName( $ip, false ) to turn off name validation
977 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
978 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
980 * Calling this with a user, IP address or range will not select autoblocks, and will
981 * only select a block where the targets match exactly (so looking for blocks on
982 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
983 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
984 * affects that target (so for an IP address, get ranges containing that IP; and also
985 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
986 * @param $fromMaster Bool whether to use the DB_MASTER database
987 * @return Block|null (null if no relevant block could be found). The target and type
988 * of the returned Block will refer to the actual block which was found, which might
989 * not be the same as the target you gave if you used $vagueTarget!
991 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
993 list( $target, $type ) = self
::parseTarget( $specificTarget );
994 if( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
){
995 return Block
::newFromID( $target );
997 } elseif( $target === null && $vagueTarget == '' ){
998 # We're not going to find anything useful here
999 # Be aware that the == '' check is explicit, since empty values will be
1000 # passed by some callers (bug 29116)
1003 } elseif( in_array( $type, array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) ) ) {
1004 $block = new Block();
1005 $block->fromMaster( $fromMaster );
1007 if( $type !== null ){
1008 $block->setTarget( $target );
1011 if( $block->newLoad( $vagueTarget ) ){
1022 * From an existing Block, get the target and the type of target. Note that it is
1023 * always safe to treat the target as a string; for User objects this will return
1024 * User::__toString() which in turn gives User::getName().
1026 * @param $target String|Int|User
1027 * @return array( User|String, Block::TYPE_ constant )
1029 public static function parseTarget( $target ) {
1030 $target = trim( $target );
1032 # We may have been through this before
1033 if( $target instanceof User
){
1034 if( IP
::isValid( $target->getName() ) ){
1035 return array( $target, self
::TYPE_IP
);
1037 return array( $target, self
::TYPE_USER
);
1039 } elseif( $target === null ){
1040 return array( null, null );
1043 # Consider the possibility that this is not a username at all
1044 # but actually an old subpage (bug #29797)
1045 if( strpos( $target, '/' ) !== false ){
1046 # An old subpage, drill down to the user behind it
1047 $parts = explode( '/', $target );
1048 $target = $parts[0];
1051 $userObj = User
::newFromName( $target );
1052 if ( $userObj instanceof User
) {
1053 # Note that since numbers are valid usernames, a $target of "12345" will be
1054 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1055 # since hash characters are not valid in usernames or titles generally.
1056 return array( $userObj, Block
::TYPE_USER
);
1058 } elseif ( IP
::isValid( $target ) ) {
1059 # We can still create a User if it's an IP address, but we need to turn
1060 # off validation checking (which would exclude IP addresses)
1062 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1066 } elseif ( IP
::isValidBlock( $target ) ) {
1067 # Can't create a User from an IP range
1068 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1070 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1071 # Autoblock reference in the form "#12345"
1072 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1076 return array( null, null );
1081 * Get the type of target for this particular block
1082 * @return Block::TYPE_ constant, will never be TYPE_ID
1084 public function getType() {
1091 * Get the target and target type for this particular Block. Note that for autoblocks,
1092 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1093 * in this situation.
1094 * @return array( User|String, Block::TYPE_ constant )
1095 * @todo FIXME: This should be an integral part of the Block member variables
1097 public function getTargetAndType() {
1098 return array( $this->getTarget(), $this->getType() );
1102 * Get the target for this particular Block. Note that for autoblocks,
1103 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1104 * in this situation.
1105 * @return User|String
1107 public function getTarget() {
1108 return $this->target
;
1112 * Set the target for this block, and update $this->type accordingly
1113 * @param $target Mixed
1115 public function setTarget( $target ){
1116 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1120 * Get the user who implemented this block
1123 public function getBlocker(){
1124 return $this->blocker
;
1128 * Set the user who implemented (or will implement) this block
1131 public function setBlocker( User
$user ){
1132 $this->blocker
= $user;