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 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(
114 self
::selectFields(),
115 array( 'ipb_id' => $id ),
119 return self
::newFromRow( $res );
126 * Return the list of ipblocks fields that should be selected to create
130 public static function selectFields() {
140 'ipb_create_account',
141 'ipb_enable_autoblock',
145 'ipb_allow_usertalk',
146 'ipb_parent_block_id',
151 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
152 * the blocking user or the block timestamp, only things which affect the blocked user
154 * @param $block Block
158 public function equals( Block
$block ) {
160 (string)$this->target
== (string)$block->target
161 && $this->type
== $block->type
162 && $this->mAuto
== $block->mAuto
163 && $this->isHardblock() == $block->isHardblock()
164 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
165 && $this->mExpiry
== $block->mExpiry
166 && $this->isAutoblocking() == $block->isAutoblocking()
167 && $this->mHideName
== $block->mHideName
168 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
169 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
170 && $this->mReason
== $block->mReason
175 * Load a block from the database which affects the already-set $this->target:
176 * 1) A block directly on the given user or IP
177 * 2) A rangeblock encompassing the given IP (smallest first)
178 * 3) An autoblock on the given IP
179 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
180 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
181 * @throws MWException
182 * @return Bool whether a relevant block was found
184 protected function newLoad( $vagueTarget = null ) {
185 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
187 if ( $this->type
!== null ) {
189 'ipb_address' => array( (string)$this->target
),
192 $conds = array( 'ipb_address' => array() );
195 # Be aware that the != '' check is explicit, since empty values will be
196 # passed by some callers (bug 29116)
197 if ( $vagueTarget != '' ) {
198 list( $target, $type ) = self
::parseTarget( $vagueTarget );
200 case self
::TYPE_USER
:
201 # Slightly weird, but who are we to argue?
202 $conds['ipb_address'][] = (string)$target;
206 $conds['ipb_address'][] = (string)$target;
207 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
208 $conds = $db->makeList( $conds, LIST_OR
);
211 case self
::TYPE_RANGE
:
212 list( $start, $end ) = IP
::parseRange( $target );
213 $conds['ipb_address'][] = (string)$target;
214 $conds[] = self
::getRangeCond( $start, $end );
215 $conds = $db->makeList( $conds, LIST_OR
);
219 throw new MWException( "Tried to load block with invalid type" );
223 $res = $db->select( 'ipblocks', self
::selectFields(), $conds, __METHOD__
);
225 # This result could contain a block on the user, a block on the IP, and a russian-doll
226 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
229 # Lower will be better
230 $bestBlockScore = 100;
232 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
233 $bestBlockPreventsEdit = null;
235 foreach ( $res as $row ) {
236 $block = self
::newFromRow( $row );
238 # Don't use expired blocks
239 if ( $block->deleteIfExpired() ) {
243 # Don't use anon only blocks on users
244 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
248 if ( $block->getType() == self
::TYPE_RANGE
) {
249 # This is the number of bits that are allowed to vary in the block, give
250 # or take some floating point errors
251 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
252 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
253 $size = log( $end - $start +
1, 2 );
255 # This has the nice property that a /32 block is ranked equally with a
256 # single-IP block, which is exactly what it is...
257 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
260 $score = $block->getType();
263 if ( $score < $bestBlockScore ) {
264 $bestBlockScore = $score;
266 $bestBlockPreventsEdit = $block->prevents( 'edit' );
270 if ( $bestRow !== null ) {
271 $this->initFromRow( $bestRow );
272 $this->prevents( 'edit', $bestBlockPreventsEdit );
280 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
281 * @param string $start Hexadecimal IP representation
282 * @param string $end Hexadecimal IP representation, or null to use $start = $end
285 public static function getRangeCond( $start, $end = null ) {
286 if ( $end === null ) {
289 # Per bug 14634, we want to include relevant active rangeblocks; for
290 # rangeblocks, we want to include larger ranges which enclose the given
291 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
292 # so we can improve performance by filtering on a LIKE clause
293 $chunk = self
::getIpFragment( $start );
294 $dbr = wfGetDB( DB_SLAVE
);
295 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
297 # Fairly hard to make a malicious SQL statement out of hex characters,
298 # but stranger things have happened...
299 $safeStart = $dbr->addQuotes( $start );
300 $safeEnd = $dbr->addQuotes( $end );
302 return $dbr->makeList(
304 "ipb_range_start $like",
305 "ipb_range_start <= $safeStart",
306 "ipb_range_end >= $safeEnd",
313 * Get the component of an IP address which is certain to be the same between an IP
314 * address and a rangeblock containing that IP address.
315 * @param $hex String Hexadecimal IP representation
318 protected static function getIpFragment( $hex ) {
319 global $wgBlockCIDRLimit;
320 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
321 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
323 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
328 * Given a database row from the ipblocks table, initialize
330 * @param $row ResultWrapper: a row from the ipblocks table
332 protected function initFromRow( $row ) {
333 $this->setTarget( $row->ipb_address
);
334 if ( $row->ipb_by
) { // local user
335 $this->setBlocker( User
::newFromID( $row->ipb_by
) );
336 } else { // foreign user
337 $this->setBlocker( $row->ipb_by_text
);
340 $this->mReason
= $row->ipb_reason
;
341 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
342 $this->mAuto
= $row->ipb_auto
;
343 $this->mHideName
= $row->ipb_deleted
;
344 $this->mId
= $row->ipb_id
;
345 $this->mParentBlockId
= $row->ipb_parent_block_id
;
347 // I wish I didn't have to do this
348 $db = wfGetDB( DB_SLAVE
);
349 if ( $row->ipb_expiry
== $db->getInfinity() ) {
350 $this->mExpiry
= 'infinity';
352 $this->mExpiry
= wfTimestamp( TS_MW
, $row->ipb_expiry
);
355 $this->isHardblock( !$row->ipb_anon_only
);
356 $this->isAutoblocking( $row->ipb_enable_autoblock
);
358 $this->prevents( 'createaccount', $row->ipb_create_account
);
359 $this->prevents( 'sendemail', $row->ipb_block_email
);
360 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
364 * Create a new Block object from a database row
365 * @param $row ResultWrapper row from the ipblocks table
368 public static function newFromRow( $row ) {
370 $block->initFromRow( $row );
375 * Delete the row from the IP blocks table.
377 * @throws MWException
380 public function delete() {
381 if ( wfReadOnly() ) {
385 if ( !$this->getId() ) {
386 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
389 $dbw = wfGetDB( DB_MASTER
);
390 $dbw->delete( 'ipblocks', array( 'ipb_parent_block_id' => $this->getId() ), __METHOD__
);
391 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__
);
393 return $dbw->affectedRows() > 0;
397 * Insert a block into the block table. Will fail if there is a conflicting
398 * block (same name and options) already in the database.
400 * @param $dbw DatabaseBase if you have one available
401 * @return mixed: false on failure, assoc array on success:
402 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
404 public function insert( $dbw = null ) {
405 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
407 if ( $dbw === null ) {
408 $dbw = wfGetDB( DB_MASTER
);
411 # Don't collide with expired blocks
412 Block
::purgeExpired();
414 $row = $this->getDatabaseArray();
415 $row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );
423 $affected = $dbw->affectedRows();
424 $this->mId
= $dbw->insertId();
427 $auto_ipd_ids = $this->doRetroactiveAutoblock();
428 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
435 * Update a block in the DB with new parameters.
436 * The ID field needs to be loaded first.
438 * @return bool|array False on failure, array on success:
439 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
441 public function update() {
442 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
443 $dbw = wfGetDB( DB_MASTER
);
445 $dbw->startAtomic( __METHOD__
);
449 $this->getDatabaseArray( $dbw ),
450 array( 'ipb_id' => $this->getId() ),
454 $affected = $dbw->affectedRows();
458 $this->getAutoblockUpdateArray(),
459 array( 'ipb_parent_block_id' => $this->getId() ),
463 $dbw->endAtomic( __METHOD__
);
466 $auto_ipd_ids = $this->doRetroactiveAutoblock();
467 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
474 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
475 * @param $db DatabaseBase
478 protected function getDatabaseArray( $db = null ) {
480 $db = wfGetDB( DB_SLAVE
);
482 $expiry = $db->encodeExpiry( $this->mExpiry
);
484 if ( $this->forcedTargetID
) {
485 $uid = $this->forcedTargetID
;
487 $uid = $this->target
instanceof User ?
$this->target
->getID() : 0;
491 'ipb_address' => (string)$this->target
,
493 'ipb_by' => $this->getBy(),
494 'ipb_by_text' => $this->getByName(),
495 'ipb_reason' => $this->mReason
,
496 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
497 'ipb_auto' => $this->mAuto
,
498 'ipb_anon_only' => !$this->isHardblock(),
499 'ipb_create_account' => $this->prevents( 'createaccount' ),
500 'ipb_enable_autoblock' => $this->isAutoblocking(),
501 'ipb_expiry' => $expiry,
502 'ipb_range_start' => $this->getRangeStart(),
503 'ipb_range_end' => $this->getRangeEnd(),
504 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
505 'ipb_block_email' => $this->prevents( 'sendemail' ),
506 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
507 'ipb_parent_block_id' => $this->mParentBlockId
516 protected function getAutoblockUpdateArray() {
518 'ipb_by' => $this->getBy(),
519 'ipb_by_text' => $this->getByName(),
520 'ipb_reason' => $this->mReason
,
521 'ipb_create_account' => $this->prevents( 'createaccount' ),
522 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
523 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
528 * Retroactively autoblocks the last IP used by the user (if it is a user)
529 * blocked by this Block.
531 * @return Array: block IDs of retroactive autoblocks made
533 protected function doRetroactiveAutoblock() {
535 # If autoblock is enabled, autoblock the LAST IP(s) used
536 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
537 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
539 $continue = wfRunHooks(
540 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
543 self
::defaultRetroactiveAutoblock( $this, $blockIds );
550 * Retroactively autoblocks the last IP used by the user (if it is a user)
551 * blocked by this Block. This will use the recentchanges table.
553 * @param Block $block
554 * @param array &$blockIds
555 * @return Array: block IDs of retroactive autoblocks made
557 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
560 // No IPs are in recentchanges table, so nothing to select
561 if ( !$wgPutIPinRC ) {
565 $dbr = wfGetDB( DB_SLAVE
);
567 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
568 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
570 // Just the last IP used.
571 $options['LIMIT'] = 1;
573 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
574 __METHOD__
, $options );
576 if ( !$res->numRows() ) {
577 # No results, don't autoblock anything
578 wfDebug( "No IP found to retroactively autoblock\n" );
580 foreach ( $res as $row ) {
582 $id = $block->doAutoblock( $row->rc_ip
);
592 * Checks whether a given IP is on the autoblock whitelist.
593 * TODO: this probably belongs somewhere else, but not sure where...
595 * @param string $ip The IP to check
598 public static function isWhitelistedFromAutoblocks( $ip ) {
601 // Try to get the autoblock_whitelist from the cache, as it's faster
602 // than getting the msg raw and explode()'ing it.
603 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
604 $lines = $wgMemc->get( $key );
606 $lines = explode( "\n", wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
607 $wgMemc->set( $key, $lines, 3600 * 24 );
610 wfDebug( "Checking the autoblock whitelist..\n" );
612 foreach ( $lines as $line ) {
614 if ( substr( $line, 0, 1 ) !== '*' ) {
618 $wlEntry = substr( $line, 1 );
619 $wlEntry = trim( $wlEntry );
621 wfDebug( "Checking $ip against $wlEntry..." );
623 # Is the IP in this range?
624 if ( IP
::isInRange( $ip, $wlEntry ) ) {
625 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
628 wfDebug( " No match\n" );
636 * Autoblocks the given IP, referring to this Block.
638 * @param string $autoblockIP the IP to autoblock.
639 * @return mixed: block ID if an autoblock was inserted, false if not.
641 public function doAutoblock( $autoblockIP ) {
642 # If autoblocks are disabled, go away.
643 if ( !$this->isAutoblocking() ) {
647 # Check for presence on the autoblock whitelist.
648 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
652 # Allow hooks to cancel the autoblock.
653 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
654 wfDebug( "Autoblock aborted by hook.\n" );
658 # It's okay to autoblock. Go ahead and insert/update the block...
660 # Do not add a *new* block if the IP is already blocked.
661 $ipblock = Block
::newFromTarget( $autoblockIP );
663 # Check if the block is an autoblock and would exceed the user block
664 # if renewed. If so, do nothing, otherwise prolong the block time...
665 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
666 $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
668 # Reset block timestamp to now and its expiry to
669 # $wgAutoblockExpiry in the future
670 $ipblock->updateTimestamp();
675 # Make a new block object with the desired properties.
676 $autoblock = new Block
;
677 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
678 $autoblock->setTarget( $autoblockIP );
679 $autoblock->setBlocker( $this->getBlocker() );
680 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
681 ->inContentLanguage()->plain();
682 $timestamp = wfTimestampNow();
683 $autoblock->mTimestamp
= $timestamp;
684 $autoblock->mAuto
= 1;
685 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
686 # Continue suppressing the name if needed
687 $autoblock->mHideName
= $this->mHideName
;
688 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
689 $autoblock->mParentBlockId
= $this->mId
;
691 if ( $this->mExpiry
== 'infinity' ) {
692 # Original block was indefinite, start an autoblock now
693 $autoblock->mExpiry
= Block
::getAutoblockExpiry( $timestamp );
695 # If the user is already blocked with an expiry date, we don't
696 # want to pile on top of that.
697 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $timestamp ) );
700 # Insert the block...
701 $status = $autoblock->insert();
708 * Check if a block has expired. Delete it if it is.
711 public function deleteIfExpired() {
712 wfProfileIn( __METHOD__
);
714 if ( $this->isExpired() ) {
715 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
719 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
723 wfProfileOut( __METHOD__
);
728 * Has the block expired?
731 public function isExpired() {
732 $timestamp = wfTimestampNow();
733 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
735 if ( !$this->mExpiry
) {
738 return $timestamp > $this->mExpiry
;
743 * Is the block address valid (i.e. not a null string?)
746 public function isValid() {
747 return $this->getTarget() != null;
751 * Update the timestamp on autoblocks.
753 public function updateTimestamp() {
754 if ( $this->mAuto
) {
755 $this->mTimestamp
= wfTimestamp();
756 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
758 $dbw = wfGetDB( DB_MASTER
);
759 $dbw->update( 'ipblocks',
761 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
762 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
765 'ipb_address' => (string)$this->getTarget()
773 * Get the IP address at the start of the range in Hex form
774 * @throws MWException
775 * @return String IP in Hex form
777 public function getRangeStart() {
778 switch ( $this->type
) {
779 case self
::TYPE_USER
:
782 return IP
::toHex( $this->target
);
783 case self
::TYPE_RANGE
:
784 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
787 throw new MWException( "Block with invalid type" );
792 * Get the IP address at the end of the range in Hex form
793 * @throws MWException
794 * @return String IP in Hex form
796 public function getRangeEnd() {
797 switch ( $this->type
) {
798 case self
::TYPE_USER
:
801 return IP
::toHex( $this->target
);
802 case self
::TYPE_RANGE
:
803 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
806 throw new MWException( "Block with invalid type" );
811 * Get the user id of the blocking sysop
813 * @return Integer (0 for foreign users)
815 public function getBy() {
816 $blocker = $this->getBlocker();
817 return ( $blocker instanceof User
)
823 * Get the username of the blocking sysop
827 public function getByName() {
828 $blocker = $this->getBlocker();
829 return ( $blocker instanceof User
)
830 ?
$blocker->getName()
831 : (string)$blocker; // username
838 public function getId() {
843 * Get/set a flag determining whether the master is used for reads
848 public function fromMaster( $x = null ) {
849 return wfSetVar( $this->mFromMaster
, $x );
853 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
857 public function isHardblock( $x = null ) {
858 wfSetVar( $this->isHardblock
, $x );
860 # You can't *not* hardblock a user
861 return $this->getType() == self
::TYPE_USER
863 : $this->isHardblock
;
866 public function isAutoblocking( $x = null ) {
867 wfSetVar( $this->isAutoblocking
, $x );
869 # You can't put an autoblock on an IP or range as we don't have any history to
870 # look over to get more IPs from
871 return $this->getType() == self
::TYPE_USER
872 ?
$this->isAutoblocking
877 * Get/set whether the Block prevents a given action
878 * @param $action String
882 public function prevents( $action, $x = null ) {
885 # For now... <evil laugh>
888 case 'createaccount':
889 return wfSetVar( $this->mCreateAccount
, $x );
892 return wfSetVar( $this->mBlockEmail
, $x );
894 case 'editownusertalk':
895 return wfSetVar( $this->mDisableUsertalk
, $x );
903 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
904 * @return String, text is escaped
906 public function getRedactedName() {
907 if ( $this->mAuto
) {
908 return Html
::rawElement(
910 array( 'class' => 'mw-autoblockid' ),
911 wfMessage( 'autoblockid', $this->mId
)
914 return htmlspecialchars( $this->getTarget() );
919 * Get a timestamp of the expiry for autoblocks
921 * @param $timestamp String|Int
924 public static function getAutoblockExpiry( $timestamp ) {
925 global $wgAutoblockExpiry;
927 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
931 * Purge expired blocks from the ipblocks table
933 public static function purgeExpired() {
934 if ( wfReadOnly() ) {
938 $method = __METHOD__
;
939 $dbw = wfGetDB( DB_MASTER
);
940 $dbw->onTransactionIdle( function() use ( $dbw, $method ) {
941 $dbw->delete( 'ipblocks',
942 array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), $method );
947 * Given a target and the target's type, get an existing Block object if possible.
948 * @param $specificTarget String|User|Int a block target, which may be one of several types:
949 * * A user to block, in which case $target will be a User
950 * * An IP to block, in which case $target will be a User generated by using
951 * User::newFromName( $ip, false ) to turn off name validation
952 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
953 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
955 * Calling this with a user, IP address or range will not select autoblocks, and will
956 * only select a block where the targets match exactly (so looking for blocks on
957 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
958 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
959 * affects that target (so for an IP address, get ranges containing that IP; and also
960 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
961 * @param bool $fromMaster whether to use the DB_MASTER database
962 * @return Block|null (null if no relevant block could be found). The target and type
963 * of the returned Block will refer to the actual block which was found, which might
964 * not be the same as the target you gave if you used $vagueTarget!
966 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
968 list( $target, $type ) = self
::parseTarget( $specificTarget );
969 if ( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
) {
970 return Block
::newFromID( $target );
972 } elseif ( $target === null && $vagueTarget == '' ) {
973 # We're not going to find anything useful here
974 # Be aware that the == '' check is explicit, since empty values will be
975 # passed by some callers (bug 29116)
980 array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) )
982 $block = new Block();
983 $block->fromMaster( $fromMaster );
985 if ( $type !== null ) {
986 $block->setTarget( $target );
989 if ( $block->newLoad( $vagueTarget ) ) {
997 * Get all blocks that match any IP from an array of IP addresses
999 * @param Array $ipChain list of IPs (strings), usually retrieved from the
1000 * X-Forwarded-For header of the request
1001 * @param Bool $isAnon Exclude anonymous-only blocks if false
1002 * @param Bool $fromMaster Whether to query the master or slave database
1003 * @return Array of Blocks
1006 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1007 if ( !count( $ipChain ) ) {
1011 wfProfileIn( __METHOD__
);
1013 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1014 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1015 # necessarily trust the header given to us, make sure that we are only
1016 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1017 # Do not treat private IP spaces as special as it may be desirable for wikis
1018 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1019 if ( !IP
::isValid( $ipaddr ) ) {
1022 # Don't check trusted IPs (includes local squids which will be in every request)
1023 if ( wfIsTrustedProxy( $ipaddr ) ) {
1026 # Check both the original IP (to check against single blocks), as well as build
1027 # the clause to check for rangeblocks for the given IP.
1028 $conds['ipb_address'][] = $ipaddr;
1029 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1032 if ( !count( $conds ) ) {
1033 wfProfileOut( __METHOD__
);
1037 if ( $fromMaster ) {
1038 $db = wfGetDB( DB_MASTER
);
1040 $db = wfGetDB( DB_SLAVE
);
1042 $conds = $db->makeList( $conds, LIST_OR
);
1044 $conds = array( $conds, 'ipb_anon_only' => 0 );
1046 $selectFields = array_merge(
1047 array( 'ipb_range_start', 'ipb_range_end' ),
1048 Block
::selectFields()
1050 $rows = $db->select( 'ipblocks',
1057 foreach ( $rows as $row ) {
1058 $block = self
::newFromRow( $row );
1059 if ( !$block->deleteIfExpired() ) {
1064 wfProfileOut( __METHOD__
);
1069 * From a list of multiple blocks, find the most exact and strongest Block.
1070 * The logic for finding the "best" block is:
1071 * - Blocks that match the block's target IP are preferred over ones in a range
1072 * - Hardblocks are chosen over softblocks that prevent account creation
1073 * - Softblocks that prevent account creation are chosen over other softblocks
1074 * - Other softblocks are chosen over autoblocks
1075 * - If there are multiple exact or range blocks at the same level, the one chosen
1078 * @param Array $ipChain list of IPs (strings). This is used to determine how "close"
1079 * a block is to the server, and if a block matches exactly, or is in a range.
1080 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1082 * @param Array $block Array of blocks
1083 * @return Block|null the "best" block from the list
1085 public static function chooseBlock( array $blocks, array $ipChain ) {
1086 if ( !count( $blocks ) ) {
1088 } elseif ( count( $blocks ) == 1 ) {
1092 wfProfileIn( __METHOD__
);
1094 // Sort hard blocks before soft ones and secondarily sort blocks
1095 // that disable account creation before those that don't.
1096 usort( $blocks, function( Block
$a, Block
$b ) {
1097 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1098 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1099 return strcmp( $bWeight, $aWeight ); // highest weight first
1102 $blocksListExact = array(
1104 'disable_create' => false,
1108 $blocksListRange = array(
1110 'disable_create' => false,
1114 $ipChain = array_reverse( $ipChain );
1116 foreach ( $blocks as $block ) {
1117 // Stop searching if we have already have a "better" block. This
1118 // is why the order of the blocks matters
1119 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1121 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1125 foreach ( $ipChain as $checkip ) {
1126 $checkipHex = IP
::toHex( $checkip );
1127 if ( (string)$block->getTarget() === $checkip ) {
1128 if ( $block->isHardblock() ) {
1129 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1130 } elseif ( $block->prevents( 'createaccount' ) ) {
1131 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1132 } elseif ( $block->mAuto
) {
1133 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1135 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1137 // We found closest exact match in the ip list, so go to the next Block
1139 } elseif ( array_filter( $blocksListExact ) == array()
1140 && $block->getRangeStart() <= $checkipHex
1141 && $block->getRangeEnd() >= $checkipHex
1143 if ( $block->isHardblock() ) {
1144 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1145 } elseif ( $block->prevents( 'createaccount' ) ) {
1146 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1147 } elseif ( $block->mAuto
) {
1148 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1150 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1157 if ( array_filter( $blocksListExact ) == array() ) {
1158 $blocksList = &$blocksListRange;
1160 $blocksList = &$blocksListExact;
1163 $chosenBlock = null;
1164 if ( $blocksList['hard'] ) {
1165 $chosenBlock = $blocksList['hard'];
1166 } elseif ( $blocksList['disable_create'] ) {
1167 $chosenBlock = $blocksList['disable_create'];
1168 } elseif ( $blocksList['other'] ) {
1169 $chosenBlock = $blocksList['other'];
1170 } elseif ( $blocksList['auto'] ) {
1171 $chosenBlock = $blocksList['auto'];
1173 wfProfileOut( __METHOD__
);
1174 throw new MWException( "Proxy block found, but couldn't be classified." );
1177 wfProfileOut( __METHOD__
);
1178 return $chosenBlock;
1182 * From an existing Block, get the target and the type of target.
1183 * Note that, except for null, it is always safe to treat the target
1184 * as a string; for User objects this will return User::__toString()
1185 * which in turn gives User::getName().
1187 * @param $target String|Int|User|null
1188 * @return array( User|String|null, Block::TYPE_ constant|null )
1190 public static function parseTarget( $target ) {
1191 # We may have been through this before
1192 if ( $target instanceof User
) {
1193 if ( IP
::isValid( $target->getName() ) ) {
1194 return array( $target, self
::TYPE_IP
);
1196 return array( $target, self
::TYPE_USER
);
1198 } elseif ( $target === null ) {
1199 return array( null, null );
1202 $target = trim( $target );
1204 if ( IP
::isValid( $target ) ) {
1205 # We can still create a User if it's an IP address, but we need to turn
1206 # off validation checking (which would exclude IP addresses)
1208 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1212 } elseif ( IP
::isValidBlock( $target ) ) {
1213 # Can't create a User from an IP range
1214 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1217 # Consider the possibility that this is not a username at all
1218 # but actually an old subpage (bug #29797)
1219 if ( strpos( $target, '/' ) !== false ) {
1220 # An old subpage, drill down to the user behind it
1221 $parts = explode( '/', $target );
1222 $target = $parts[0];
1225 $userObj = User
::newFromName( $target );
1226 if ( $userObj instanceof User
) {
1227 # Note that since numbers are valid usernames, a $target of "12345" will be
1228 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1229 # since hash characters are not valid in usernames or titles generally.
1230 return array( $userObj, Block
::TYPE_USER
);
1232 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1233 # Autoblock reference in the form "#12345"
1234 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1238 return array( null, null );
1243 * Get the type of target for this particular block
1244 * @return Block::TYPE_ constant, will never be TYPE_ID
1246 public function getType() {
1253 * Get the target and target type for this particular Block. Note that for autoblocks,
1254 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1255 * in this situation.
1256 * @return array( User|String, Block::TYPE_ constant )
1257 * @todo FIXME: This should be an integral part of the Block member variables
1259 public function getTargetAndType() {
1260 return array( $this->getTarget(), $this->getType() );
1264 * Get the target for this particular Block. Note that for autoblocks,
1265 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1266 * in this situation.
1267 * @return User|String
1269 public function getTarget() {
1270 return $this->target
;
1276 * @return Mixed|string
1278 public function getExpiry() {
1279 return $this->mExpiry
;
1283 * Set the target for this block, and update $this->type accordingly
1284 * @param $target Mixed
1286 public function setTarget( $target ) {
1287 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1291 * Get the user who implemented this block
1292 * @return User|string Local User object or string for a foreign user
1294 public function getBlocker() {
1295 return $this->blocker
;
1299 * Set the user who implemented (or will implement) this block
1300 * @param $user User|string Local User object or username string for foreign users
1302 public function setBlocker( $user ) {
1303 $this->blocker
= $user;
1307 * Get the key and parameters for the corresponding error message.
1310 * @param IContextSource $context
1313 public function getPermissionsError( IContextSource
$context ) {
1314 $blocker = $this->getBlocker();
1315 if ( $blocker instanceof User
) { // local user
1316 $blockerUserpage = $blocker->getUserPage();
1317 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1318 } else { // foreign user
1322 $reason = $this->mReason
;
1323 if ( $reason == '' ) {
1324 $reason = $context->msg( 'blockednoreason' )->text();
1327 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1328 * This could be a username, an IP range, or a single IP. */
1329 $intended = $this->getTarget();
1331 $lang = $context->getLanguage();
1333 $this->mAuto ?
'autoblockedtext' : 'blockedtext',
1336 $context->getRequest()->getIP(),
1339 $lang->formatExpiry( $this->mExpiry
),
1341 $lang->timeanddate( wfTimestamp( TS_MW
, $this->mTimestamp
), true ),