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;
37 // @var Integer Hack for foreign blocking (CentralAuth)
38 protected $forcedTargetID;
40 /// @var Block::TYPE_ constant. Can only be USER, IP or RANGE internally
47 protected $isHardblock = true;
50 protected $isAutoblocking = true;
61 * @todo FIXME: Don't know what the best format to have for this constructor is, but fourteen
62 * optional parameters certainly isn't it.
64 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
65 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
66 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byText = '' )
68 if( $timestamp === 0 ){
69 $timestamp = wfTimestampNow();
72 if( count( func_get_args() ) > 0 ){
74 # wfDeprecated( __METHOD__ . " with arguments" );
77 $this->setTarget( $address );
78 if ( $this->target
instanceof User
&& $user ) {
79 $this->forcedTargetID
= $user; // needed for foreign users
81 if ( $by ) { // local user
82 $this->setBlocker( User
::newFromID( $by ) );
83 } else { // foreign user
84 $this->setBlocker( $byText );
86 $this->mReason
= $reason;
87 $this->mTimestamp
= wfTimestamp( TS_MW
, $timestamp );
89 $this->isHardblock( !$anonOnly );
90 $this->prevents( 'createaccount', $createAccount );
91 if ( $expiry == 'infinity' ||
$expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
92 $this->mExpiry
= 'infinity';
94 $this->mExpiry
= wfTimestamp( TS_MW
, $expiry );
96 $this->isAutoblocking( $enableAutoblock );
97 $this->mHideName
= $hideName;
98 $this->prevents( 'sendemail', $blockEmail );
99 $this->prevents( 'editownusertalk', !$allowUsertalk );
101 $this->mFromMaster
= false;
105 * Load a block from the database, using either the IP address or
106 * user ID. Tries the user ID first, and if that doesn't work, tries
109 * @param $address String: IP address of user/anon
110 * @param $user Integer: user id of user
111 * @return Block Object
112 * @deprecated since 1.18
114 public static function newFromDB( $address, $user = 0 ) {
115 wfDeprecated( __METHOD__
, '1.18' );
116 return self
::newFromTarget( User
::whoIs( $user ), $address );
120 * Load a blocked user from their block id.
122 * @param $id Integer: Block id to search for
123 * @return Block object or null
125 public static function newFromID( $id ) {
126 $dbr = wfGetDB( DB_SLAVE
);
127 $res = $dbr->selectRow(
130 array( 'ipb_id' => $id ),
134 return Block
::newFromRow( $res );
141 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
142 * the blocking user or the block timestamp, only things which affect the blocked user *
144 * @param $block Block
148 public function equals( Block
$block ) {
150 (string)$this->target
== (string)$block->target
151 && $this->type
== $block->type
152 && $this->mAuto
== $block->mAuto
153 && $this->isHardblock() == $block->isHardblock()
154 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
155 && $this->mExpiry
== $block->mExpiry
156 && $this->isAutoblocking() == $block->isAutoblocking()
157 && $this->mHideName
== $block->mHideName
158 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
159 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
160 && $this->mReason
== $block->mReason
165 * Clear all member variables in the current object. Does not clear
166 * the block from the DB.
167 * @deprecated since 1.18
169 public function clear() {
170 wfDeprecated( __METHOD__
, '1.18' );
175 * Get a block from the DB, with either the given address or the given username
177 * @param $address string The IP address of the user, or blank to skip IP blocks
178 * @param $user int The user ID, or zero for anonymous users
179 * @return Boolean: the user is blocked from editing
180 * @deprecated since 1.18
182 public function load( $address = '', $user = 0 ) {
183 wfDeprecated( __METHOD__
, '1.18' );
185 $username = User
::whoIs( $user );
186 $block = self
::newFromTarget( $username, $address );
188 $block = self
::newFromTarget( null, $address );
191 if( $block instanceof Block
){
192 # This is mildly evil, but hey, it's B/C :D
193 foreach( $block as $variable => $value ){
194 $this->$variable = $value;
203 * Load a block from the database which affects the already-set $this->target:
204 * 1) A block directly on the given user or IP
205 * 2) A rangeblock encompasing the given IP (smallest first)
206 * 3) An autoblock on the given IP
207 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
208 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
209 * @return Bool whether a relevant block was found
211 protected function newLoad( $vagueTarget = null ) {
212 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
214 if( $this->type
!== null ){
216 'ipb_address' => array( (string)$this->target
),
219 $conds = array( 'ipb_address' => array() );
222 # Be aware that the != '' check is explicit, since empty values will be
223 # passed by some callers (bug 29116)
224 if( $vagueTarget != ''){
225 list( $target, $type ) = self
::parseTarget( $vagueTarget );
227 case self
::TYPE_USER
:
228 # Slightly wierd, but who are we to argue?
229 $conds['ipb_address'][] = (string)$target;
233 $conds['ipb_address'][] = (string)$target;
234 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
235 $conds = $db->makeList( $conds, LIST_OR
);
238 case self
::TYPE_RANGE
:
239 list( $start, $end ) = IP
::parseRange( $target );
240 $conds['ipb_address'][] = (string)$target;
241 $conds[] = self
::getRangeCond( $start, $end );
242 $conds = $db->makeList( $conds, LIST_OR
);
246 throw new MWException( "Tried to load block with invalid type" );
250 $res = $db->select( 'ipblocks', '*', $conds, __METHOD__
);
252 # This result could contain a block on the user, a block on the IP, and a russian-doll
253 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
256 # Lower will be better
257 $bestBlockScore = 100;
259 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
260 $bestBlockPreventsEdit = null;
262 foreach( $res as $row ){
263 $block = Block
::newFromRow( $row );
265 # Don't use expired blocks
266 if( $block->deleteIfExpired() ){
270 # Don't use anon only blocks on users
271 if( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ){
275 if( $block->getType() == self
::TYPE_RANGE
){
276 # This is the number of bits that are allowed to vary in the block, give
277 # or take some floating point errors
278 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
279 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
280 $size = log( $end - $start +
1, 2 );
282 # This has the nice property that a /32 block is ranked equally with a
283 # single-IP block, which is exactly what it is...
284 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
287 $score = $block->getType();
290 if( $score < $bestBlockScore ){
291 $bestBlockScore = $score;
293 $bestBlockPreventsEdit = $block->prevents( 'edit' );
297 if( $bestRow !== null ){
298 $this->initFromRow( $bestRow );
299 $this->prevents( 'edit', $bestBlockPreventsEdit );
307 * Get a set of SQL conditions which will select rangeblocks encompasing a given range
308 * @param $start String Hexadecimal IP representation
309 * @param $end String Hexadecimal IP represenation, or null to use $start = $end
312 public static function getRangeCond( $start, $end = null ) {
313 if ( $end === null ) {
316 # Per bug 14634, we want to include relevant active rangeblocks; for
317 # rangeblocks, we want to include larger ranges which enclose the given
318 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
319 # so we can improve performance by filtering on a LIKE clause
320 $chunk = self
::getIpFragment( $start );
321 $dbr = wfGetDB( DB_SLAVE
);
322 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
324 # Fairly hard to make a malicious SQL statement out of hex characters,
325 # but stranger things have happened...
326 $safeStart = $dbr->addQuotes( $start );
327 $safeEnd = $dbr->addQuotes( $end );
329 return $dbr->makeList(
331 "ipb_range_start $like",
332 "ipb_range_start <= $safeStart",
333 "ipb_range_end >= $safeEnd",
340 * Get the component of an IP address which is certain to be the same between an IP
341 * address and a rangeblock containing that IP address.
342 * @param $hex String Hexadecimal IP representation
345 protected static function getIpFragment( $hex ) {
346 global $wgBlockCIDRLimit;
347 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
348 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
350 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
355 * Given a database row from the ipblocks table, initialize
357 * @param $row ResultWrapper: a row from the ipblocks table
359 protected function initFromRow( $row ) {
360 $this->setTarget( $row->ipb_address
);
361 if ( $row->ipb_by
) { // local user
362 $this->setBlocker( User
::newFromID( $row->ipb_by
) );
363 } else { // foreign user
364 $this->setBlocker( $row->ipb_by_text
);
367 $this->mReason
= $row->ipb_reason
;
368 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
369 $this->mAuto
= $row->ipb_auto
;
370 $this->mHideName
= $row->ipb_deleted
;
371 $this->mId
= $row->ipb_id
;
372 $this->mParentBlockId
= $row->ipb_parent_block_id
;
374 // I wish I didn't have to do this
375 $db = wfGetDB( DB_SLAVE
);
376 if ( $row->ipb_expiry
== $db->getInfinity() ) {
377 $this->mExpiry
= 'infinity';
379 $this->mExpiry
= wfTimestamp( TS_MW
, $row->ipb_expiry
);
382 $this->isHardblock( !$row->ipb_anon_only
);
383 $this->isAutoblocking( $row->ipb_enable_autoblock
);
385 $this->prevents( 'createaccount', $row->ipb_create_account
);
386 $this->prevents( 'sendemail', $row->ipb_block_email
);
387 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
391 * Create a new Block object from a database row
392 * @param $row ResultWrapper row from the ipblocks table
395 public static function newFromRow( $row ){
397 $block->initFromRow( $row );
402 * Delete the row from the IP blocks table.
406 public function delete() {
407 if ( wfReadOnly() ) {
411 if ( !$this->getId() ) {
412 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
415 $dbw = wfGetDB( DB_MASTER
);
416 $dbw->delete( 'ipblocks', array( 'ipb_parent_block_id' => $this->getId() ), __METHOD__
);
417 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__
);
419 return $dbw->affectedRows() > 0;
423 * Insert a block into the block table. Will fail if there is a conflicting
424 * block (same name and options) already in the database.
426 * @param $dbw DatabaseBase if you have one available
427 * @return mixed: false on failure, assoc array on success:
428 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
430 public function insert( $dbw = null ) {
431 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
433 if ( $dbw === null ) {
434 $dbw = wfGetDB( DB_MASTER
);
437 # Don't collide with expired blocks
438 Block
::purgeExpired();
440 $row = $this->getDatabaseArray();
441 $row['ipb_id'] = $dbw->nextSequenceValue("ipblocks_ipb_id_seq");
449 $affected = $dbw->affectedRows();
450 $this->mId
= $dbw->insertId();
453 $auto_ipd_ids = $this->doRetroactiveAutoblock();
454 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
461 * Update a block in the DB with new parameters.
462 * The ID field needs to be loaded first.
464 * @return Int number of affected rows, which should probably be 1 or something's
467 public function update() {
468 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
469 $dbw = wfGetDB( DB_MASTER
);
473 $this->getDatabaseArray( $dbw ),
474 array( 'ipb_id' => $this->getId() ),
478 return $dbw->affectedRows();
482 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
483 * @param $db DatabaseBase
486 protected function getDatabaseArray( $db = null ){
488 $db = wfGetDB( DB_SLAVE
);
490 $expiry = $db->encodeExpiry( $this->mExpiry
);
492 if ( $this->forcedTargetID
) {
493 $uid = $this->forcedTargetID
;
495 $uid = $this->target
instanceof User ?
$this->target
->getID() : 0;
499 'ipb_address' => (string)$this->target
,
501 'ipb_by' => $this->getBy(),
502 'ipb_by_text' => $this->getByName(),
503 'ipb_reason' => $this->mReason
,
504 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
505 'ipb_auto' => $this->mAuto
,
506 'ipb_anon_only' => !$this->isHardblock(),
507 'ipb_create_account' => $this->prevents( 'createaccount' ),
508 'ipb_enable_autoblock' => $this->isAutoblocking(),
509 'ipb_expiry' => $expiry,
510 'ipb_range_start' => $this->getRangeStart(),
511 'ipb_range_end' => $this->getRangeEnd(),
512 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
513 'ipb_block_email' => $this->prevents( 'sendemail' ),
514 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
515 'ipb_parent_block_id' => $this->mParentBlockId
522 * Retroactively autoblocks the last IP used by the user (if it is a user)
523 * blocked by this Block.
525 * @return Array: block IDs of retroactive autoblocks made
527 protected function doRetroactiveAutoblock() {
529 # If autoblock is enabled, autoblock the LAST IP(s) used
530 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
531 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
533 $continue = wfRunHooks(
534 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
537 self
::defaultRetroactiveAutoblock( $this, $blockIds );
544 * Retroactively autoblocks the last IP used by the user (if it is a user)
545 * blocked by this Block. This will use the recentchanges table.
547 * @param Block $block
548 * @param Array &$blockIds
549 * @return Array: block IDs of retroactive autoblocks made
551 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
552 $dbr = wfGetDB( DB_SLAVE
);
554 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
555 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
557 // Just the last IP used.
558 $options['LIMIT'] = 1;
560 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
561 __METHOD__
, $options );
563 if ( !$dbr->numRows( $res ) ) {
564 # No results, don't autoblock anything
565 wfDebug( "No IP found to retroactively autoblock\n" );
567 foreach ( $res as $row ) {
569 $id = $block->doAutoblock( $row->rc_ip
);
570 if ( $id ) $blockIds[] = $id;
577 * Checks whether a given IP is on the autoblock whitelist.
578 * TODO: this probably belongs somewhere else, but not sure where...
580 * @param $ip String: The IP to check
583 public static function isWhitelistedFromAutoblocks( $ip ) {
586 // Try to get the autoblock_whitelist from the cache, as it's faster
587 // than getting the msg raw and explode()'ing it.
588 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
589 $lines = $wgMemc->get( $key );
591 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
592 $wgMemc->set( $key, $lines, 3600 * 24 );
595 wfDebug( "Checking the autoblock whitelist..\n" );
597 foreach ( $lines as $line ) {
599 if ( substr( $line, 0, 1 ) !== '*' ) {
603 $wlEntry = substr( $line, 1 );
604 $wlEntry = trim( $wlEntry );
606 wfDebug( "Checking $ip against $wlEntry..." );
608 # Is the IP in this range?
609 if ( IP
::isInRange( $ip, $wlEntry ) ) {
610 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
613 wfDebug( " No match\n" );
621 * Autoblocks the given IP, referring to this Block.
623 * @param $autoblockIP String: the IP to autoblock.
624 * @return mixed: block ID if an autoblock was inserted, false if not.
626 public function doAutoblock( $autoblockIP ) {
627 # If autoblocks are disabled, go away.
628 if ( !$this->isAutoblocking() ) {
632 # Check for presence on the autoblock whitelist.
633 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
637 # Allow hooks to cancel the autoblock.
638 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
639 wfDebug( "Autoblock aborted by hook.\n" );
643 # It's okay to autoblock. Go ahead and insert/update the block...
645 # Do not add a *new* block if the IP is already blocked.
646 $ipblock = Block
::newFromTarget( $autoblockIP );
648 # Check if the block is an autoblock and would exceed the user block
649 # if renewed. If so, do nothing, otherwise prolong the block time...
650 if ( $ipblock->mAuto
&& // @TODO: why not compare $ipblock->mExpiry?
651 $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
653 # Reset block timestamp to now and its expiry to
654 # $wgAutoblockExpiry in the future
655 $ipblock->updateTimestamp();
660 # Make a new block object with the desired properties.
661 $autoblock = new Block
;
662 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
663 $autoblock->setTarget( $autoblockIP );
664 $autoblock->setBlocker( $this->getBlocker() );
665 $autoblock->mReason
= wfMsgForContent( 'autoblocker', $this->getTarget(), $this->mReason
);
666 $timestamp = wfTimestampNow();
667 $autoblock->mTimestamp
= $timestamp;
668 $autoblock->mAuto
= 1;
669 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
670 # Continue suppressing the name if needed
671 $autoblock->mHideName
= $this->mHideName
;
672 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
673 $autoblock->mParentBlockId
= $this->mId
;
675 if ( $this->mExpiry
== 'infinity' ) {
676 # Original block was indefinite, start an autoblock now
677 $autoblock->mExpiry
= Block
::getAutoblockExpiry( $timestamp );
679 # If the user is already blocked with an expiry date, we don't
680 # want to pile on top of that.
681 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $timestamp ) );
684 # Insert the block...
685 $status = $autoblock->insert();
692 * Check if a block has expired. Delete it if it is.
695 public function deleteIfExpired() {
696 wfProfileIn( __METHOD__
);
698 if ( $this->isExpired() ) {
699 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
703 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
707 wfProfileOut( __METHOD__
);
712 * Has the block expired?
715 public function isExpired() {
716 $timestamp = wfTimestampNow();
717 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
719 if ( !$this->mExpiry
) {
722 return $timestamp > $this->mExpiry
;
727 * Is the block address valid (i.e. not a null string?)
730 public function isValid() {
731 return $this->getTarget() != null;
735 * Update the timestamp on autoblocks.
737 public function updateTimestamp() {
738 if ( $this->mAuto
) {
739 $this->mTimestamp
= wfTimestamp();
740 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
742 $dbw = wfGetDB( DB_MASTER
);
743 $dbw->update( 'ipblocks',
745 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
746 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
749 'ipb_address' => (string)$this->getTarget()
757 * Get the IP address at the start of the range in Hex form
758 * @return String IP in Hex form
760 public function getRangeStart() {
761 switch( $this->type
) {
762 case self
::TYPE_USER
:
765 return IP
::toHex( $this->target
);
766 case self
::TYPE_RANGE
:
767 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
769 default: throw new MWException( "Block with invalid type" );
774 * Get the IP address at the start of the range in Hex form
775 * @return String IP in Hex form
777 public function getRangeEnd() {
778 switch( $this->type
) {
779 case self
::TYPE_USER
:
782 return IP
::toHex( $this->target
);
783 case self
::TYPE_RANGE
:
784 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
786 default: throw new MWException( "Block with invalid type" );
791 * Get the user id of the blocking sysop
793 * @return Integer (0 for foreign users)
795 public function getBy() {
796 $blocker = $this->getBlocker();
797 return ( $blocker instanceof User
)
803 * Get the username of the blocking sysop
807 public function getByName() {
808 $blocker = $this->getBlocker();
809 return ( $blocker instanceof User
)
810 ?
$blocker->getName()
811 : (string)$blocker; // username
818 public function getId() {
823 * Get/set the SELECT ... FOR UPDATE flag
824 * @deprecated since 1.18
828 public function forUpdate( $x = null ) {
829 wfDeprecated( __METHOD__
, '1.18' );
834 * Get/set a flag determining whether the master is used for reads
839 public function fromMaster( $x = null ) {
840 return wfSetVar( $this->mFromMaster
, $x );
844 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
848 public function isHardblock( $x = null ) {
849 wfSetVar( $this->isHardblock
, $x );
851 # You can't *not* hardblock a user
852 return $this->getType() == self
::TYPE_USER
854 : $this->isHardblock
;
857 public function isAutoblocking( $x = null ) {
858 wfSetVar( $this->isAutoblocking
, $x );
860 # You can't put an autoblock on an IP or range as we don't have any history to
861 # look over to get more IPs from
862 return $this->getType() == self
::TYPE_USER
863 ?
$this->isAutoblocking
868 * Get/set whether the Block prevents a given action
869 * @param $action String
873 public function prevents( $action, $x = null ) {
876 # For now... <evil laugh>
879 case 'createaccount':
880 return wfSetVar( $this->mCreateAccount
, $x );
883 return wfSetVar( $this->mBlockEmail
, $x );
885 case 'editownusertalk':
886 return wfSetVar( $this->mDisableUsertalk
, $x );
894 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
895 * @return String, text is escaped
897 public function getRedactedName() {
898 if ( $this->mAuto
) {
899 return Html
::rawElement(
901 array( 'class' => 'mw-autoblockid' ),
902 wfMessage( 'autoblockid', $this->mId
)
905 return htmlspecialchars( $this->getTarget() );
910 * Encode expiry for DB
912 * @param $expiry String: timestamp for expiry, or
913 * @param $db DatabaseBase object
915 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
917 public static function encodeExpiry( $expiry, $db ) {
918 wfDeprecated( __METHOD__
, '1.18' );
919 return $db->encodeExpiry( $expiry );
923 * Decode expiry which has come from the DB
925 * @param $expiry String: Database expiry format
926 * @param $timestampType Int Requested timestamp format
928 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
930 public static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
931 wfDeprecated( __METHOD__
, '1.18' );
933 return $wgContLang->formatExpiry( $expiry, $timestampType );
937 * Get a timestamp of the expiry for autoblocks
939 * @param $timestamp String|Int
942 public static function getAutoblockExpiry( $timestamp ) {
943 global $wgAutoblockExpiry;
945 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
949 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
950 * For example, 127.111.113.151/24 -> 127.111.113.0/24
951 * @param $range String: IP address to normalize
953 * @deprecated since 1.18, call IP::sanitizeRange() directly
955 public static function normaliseRange( $range ) {
956 wfDeprecated( __METHOD__
, '1.18' );
957 return IP
::sanitizeRange( $range );
961 * Purge expired blocks from the ipblocks table
963 public static function purgeExpired() {
964 $dbw = wfGetDB( DB_MASTER
);
965 $dbw->delete( 'ipblocks',
966 array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
970 * Get a value to insert into expiry field of the database when infinite expiry
972 * @deprecated since 1.18, call $dbr->getInfinity() directly
975 public static function infinity() {
976 wfDeprecated( __METHOD__
, '1.18' );
977 return wfGetDB( DB_SLAVE
)->getInfinity();
981 * Convert a DB-encoded expiry into a real string that humans can read.
983 * @param $encoded_expiry String: Database encoded expiry time
984 * @return Html-escaped String
985 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
987 public static function formatExpiry( $encoded_expiry ) {
988 wfDeprecated( __METHOD__
, '1.18' );
993 if ( is_null( $msg ) ) {
995 $keys = array( 'infiniteblock', 'expiringblock' );
997 foreach ( $keys as $key ) {
998 $msg[$key] = wfMsgHtml( $key );
1002 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW
);
1003 if ( $expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
1004 $expirystr = $msg['infiniteblock'];
1007 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
1008 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
1009 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
1016 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1017 * ("24 May 2034"), into an absolute timestamp we can put into the database.
1018 * @param $expiry String: whatever was typed into the form
1019 * @return String: timestamp or "infinity" string for th DB implementation
1020 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
1022 public static function parseExpiryInput( $expiry ) {
1023 wfDeprecated( __METHOD__
, '1.18' );
1024 return SpecialBlock
::parseExpiryInput( $expiry );
1028 * Given a target and the target's type, get an existing Block object if possible.
1029 * @param $specificTarget String|User|Int a block target, which may be one of several types:
1030 * * A user to block, in which case $target will be a User
1031 * * An IP to block, in which case $target will be a User generated by using
1032 * User::newFromName( $ip, false ) to turn off name validation
1033 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1034 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1036 * Calling this with a user, IP address or range will not select autoblocks, and will
1037 * only select a block where the targets match exactly (so looking for blocks on
1038 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1039 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
1040 * affects that target (so for an IP address, get ranges containing that IP; and also
1041 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1042 * @param $fromMaster Bool whether to use the DB_MASTER database
1043 * @return Block|null (null if no relevant block could be found). The target and type
1044 * of the returned Block will refer to the actual block which was found, which might
1045 * not be the same as the target you gave if you used $vagueTarget!
1047 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1049 list( $target, $type ) = self
::parseTarget( $specificTarget );
1050 if( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
){
1051 return Block
::newFromID( $target );
1053 } elseif( $target === null && $vagueTarget == '' ){
1054 # We're not going to find anything useful here
1055 # Be aware that the == '' check is explicit, since empty values will be
1056 # passed by some callers (bug 29116)
1059 } elseif( in_array( $type, array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
) ) ) {
1060 $block = new Block();
1061 $block->fromMaster( $fromMaster );
1063 if( $type !== null ){
1064 $block->setTarget( $target );
1067 if( $block->newLoad( $vagueTarget ) ){
1075 * From an existing Block, get the target and the type of target. Note that it is
1076 * always safe to treat the target as a string; for User objects this will return
1077 * User::__toString() which in turn gives User::getName().
1079 * @param $target String|Int|User
1080 * @return array( User|String, Block::TYPE_ constant )
1082 public static function parseTarget( $target ) {
1083 # We may have been through this before
1084 if( $target instanceof User
){
1085 if( IP
::isValid( $target->getName() ) ){
1086 return array( $target, self
::TYPE_IP
);
1088 return array( $target, self
::TYPE_USER
);
1090 } elseif( $target === null ){
1091 return array( null, null );
1094 $target = trim( $target );
1096 if ( IP
::isValid( $target ) ) {
1097 # We can still create a User if it's an IP address, but we need to turn
1098 # off validation checking (which would exclude IP addresses)
1100 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1104 } elseif ( IP
::isValidBlock( $target ) ) {
1105 # Can't create a User from an IP range
1106 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1109 # Consider the possibility that this is not a username at all
1110 # but actually an old subpage (bug #29797)
1111 if( strpos( $target, '/' ) !== false ){
1112 # An old subpage, drill down to the user behind it
1113 $parts = explode( '/', $target );
1114 $target = $parts[0];
1117 $userObj = User
::newFromName( $target );
1118 if ( $userObj instanceof User
) {
1119 # Note that since numbers are valid usernames, a $target of "12345" will be
1120 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1121 # since hash characters are not valid in usernames or titles generally.
1122 return array( $userObj, Block
::TYPE_USER
);
1124 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1125 # Autoblock reference in the form "#12345"
1126 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1130 return array( null, null );
1135 * Get the type of target for this particular block
1136 * @return Block::TYPE_ constant, will never be TYPE_ID
1138 public function getType() {
1145 * Get the target and target type for this particular Block. Note that for autoblocks,
1146 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1147 * in this situation.
1148 * @return array( User|String, Block::TYPE_ constant )
1149 * @todo FIXME: This should be an integral part of the Block member variables
1151 public function getTargetAndType() {
1152 return array( $this->getTarget(), $this->getType() );
1156 * Get the target for this particular Block. Note that for autoblocks,
1157 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1158 * in this situation.
1159 * @return User|String
1161 public function getTarget() {
1162 return $this->target
;
1168 * @return Mixed|string
1170 public function getExpiry() {
1171 return $this->mExpiry
;
1175 * Set the target for this block, and update $this->type accordingly
1176 * @param $target Mixed
1178 public function setTarget( $target ){
1179 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1183 * Get the user who implemented this block
1184 * @return User|string Local User object or string for a foreign user
1186 public function getBlocker(){
1187 return $this->blocker
;
1191 * Set the user who implemented (or will implement) this block
1192 * @param $user User|string Local User object or username string for foriegn users
1194 public function setBlocker( $user ){
1195 $this->blocker
= $user;