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
26 /** @var bool|string */
32 /** @var bool|string */
38 public $mParentBlockId;
44 protected $mFromMaster;
47 protected $mBlockEmail;
50 protected $mDisableUsertalk;
53 protected $mCreateAccount;
55 /** @var User|string */
58 /** @var int Hack for foreign blocking (CentralAuth) */
59 protected $forcedTargetID;
61 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
68 protected $isHardblock = true;
71 protected $isAutoblocking = true;
81 * @todo FIXME: Don't know what the best format to have for this constructor
82 * is, but fourteen optional parameters certainly isn't it.
83 * @param string $address
86 * @param string $reason
87 * @param mixed $timestamp
89 * @param string $expiry
90 * @param int $anonOnly
91 * @param int $createAccount
92 * @param int $enableAutoblock
93 * @param int $hideName
94 * @param int $blockEmail
95 * @param int $allowUsertalk
96 * @param string $byText
98 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
99 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
100 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byText = ''
102 if ( $timestamp === 0 ) {
103 $timestamp = wfTimestampNow();
106 if ( count( func_get_args() ) > 0 ) {
108 # wfDeprecated( __METHOD__ . " with arguments" );
111 $this->setTarget( $address );
112 if ( $this->target
instanceof User
&& $user ) {
113 $this->forcedTargetID
= $user; // needed for foreign users
115 if ( $by ) { // local user
116 $this->setBlocker( User
::newFromId( $by ) );
117 } else { // foreign user
118 $this->setBlocker( $byText );
120 $this->mReason
= $reason;
121 $this->mTimestamp
= wfTimestamp( TS_MW
, $timestamp );
122 $this->mAuto
= $auto;
123 $this->isHardblock( !$anonOnly );
124 $this->prevents( 'createaccount', $createAccount );
125 $this->mExpiry
= wfGetDB( DB_SLAVE
)->decodeExpiry( $expiry );
126 $this->isAutoblocking( $enableAutoblock );
127 $this->mHideName
= $hideName;
128 $this->prevents( 'sendemail', $blockEmail );
129 $this->prevents( 'editownusertalk', !$allowUsertalk );
131 $this->mFromMaster
= false;
135 * Load a blocked user from their block id.
137 * @param int $id Block id to search for
140 public static function newFromID( $id ) {
141 $dbr = wfGetDB( DB_SLAVE
);
142 $res = $dbr->selectRow(
144 self
::selectFields(),
145 array( 'ipb_id' => $id ),
149 return self
::newFromRow( $res );
156 * Return the list of ipblocks fields that should be selected to create
160 public static function selectFields() {
170 'ipb_create_account',
171 'ipb_enable_autoblock',
175 'ipb_allow_usertalk',
176 'ipb_parent_block_id',
181 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
182 * the blocking user or the block timestamp, only things which affect the blocked user
184 * @param Block $block
188 public function equals( Block
$block ) {
190 (string)$this->target
== (string)$block->target
191 && $this->type
== $block->type
192 && $this->mAuto
== $block->mAuto
193 && $this->isHardblock() == $block->isHardblock()
194 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
195 && $this->mExpiry
== $block->mExpiry
196 && $this->isAutoblocking() == $block->isAutoblocking()
197 && $this->mHideName
== $block->mHideName
198 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
199 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
200 && $this->mReason
== $block->mReason
205 * Load a block from the database which affects the already-set $this->target:
206 * 1) A block directly on the given user or IP
207 * 2) A rangeblock encompassing the given IP (smallest first)
208 * 3) An autoblock on the given IP
209 * @param User|string $vagueTarget Also search for blocks affecting this target. Doesn't
210 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
211 * @throws MWException
212 * @return bool Whether a relevant block was found
214 protected function newLoad( $vagueTarget = null ) {
215 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
217 if ( $this->type
!== null ) {
219 'ipb_address' => array( (string)$this->target
),
222 $conds = array( 'ipb_address' => array() );
225 # Be aware that the != '' check is explicit, since empty values will be
226 # passed by some callers (bug 29116)
227 if ( $vagueTarget != '' ) {
228 list( $target, $type ) = self
::parseTarget( $vagueTarget );
230 case self
::TYPE_USER
:
231 # Slightly weird, but who are we to argue?
232 $conds['ipb_address'][] = (string)$target;
236 $conds['ipb_address'][] = (string)$target;
237 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
238 $conds = $db->makeList( $conds, LIST_OR
);
241 case self
::TYPE_RANGE
:
242 list( $start, $end ) = IP
::parseRange( $target );
243 $conds['ipb_address'][] = (string)$target;
244 $conds[] = self
::getRangeCond( $start, $end );
245 $conds = $db->makeList( $conds, LIST_OR
);
249 throw new MWException( "Tried to load block with invalid type" );
253 $res = $db->select( 'ipblocks', self
::selectFields(), $conds, __METHOD__
);
255 # This result could contain a block on the user, a block on the IP, and a russian-doll
256 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
259 # Lower will be better
260 $bestBlockScore = 100;
262 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
263 $bestBlockPreventsEdit = null;
265 foreach ( $res as $row ) {
266 $block = self
::newFromRow( $row );
268 # Don't use expired blocks
269 if ( $block->deleteIfExpired() ) {
273 # Don't use anon only blocks on users
274 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
278 if ( $block->getType() == self
::TYPE_RANGE
) {
279 # This is the number of bits that are allowed to vary in the block, give
280 # or take some floating point errors
281 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
282 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
283 $size = log( $end - $start +
1, 2 );
285 # This has the nice property that a /32 block is ranked equally with a
286 # single-IP block, which is exactly what it is...
287 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
290 $score = $block->getType();
293 if ( $score < $bestBlockScore ) {
294 $bestBlockScore = $score;
296 $bestBlockPreventsEdit = $block->prevents( 'edit' );
300 if ( $bestRow !== null ) {
301 $this->initFromRow( $bestRow );
302 $this->prevents( 'edit', $bestBlockPreventsEdit );
310 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
311 * @param string $start Hexadecimal IP representation
312 * @param string $end Hexadecimal IP representation, or null to use $start = $end
315 public static function getRangeCond( $start, $end = null ) {
316 if ( $end === null ) {
319 # Per bug 14634, we want to include relevant active rangeblocks; for
320 # rangeblocks, we want to include larger ranges which enclose the given
321 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
322 # so we can improve performance by filtering on a LIKE clause
323 $chunk = self
::getIpFragment( $start );
324 $dbr = wfGetDB( DB_SLAVE
);
325 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
327 # Fairly hard to make a malicious SQL statement out of hex characters,
328 # but stranger things have happened...
329 $safeStart = $dbr->addQuotes( $start );
330 $safeEnd = $dbr->addQuotes( $end );
332 return $dbr->makeList(
334 "ipb_range_start $like",
335 "ipb_range_start <= $safeStart",
336 "ipb_range_end >= $safeEnd",
343 * Get the component of an IP address which is certain to be the same between an IP
344 * address and a rangeblock containing that IP address.
345 * @param string $hex Hexadecimal IP representation
348 protected static function getIpFragment( $hex ) {
349 global $wgBlockCIDRLimit;
350 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
351 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
353 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
358 * Given a database row from the ipblocks table, initialize
360 * @param stdClass $row A row from the ipblocks table
362 protected function initFromRow( $row ) {
363 $this->setTarget( $row->ipb_address
);
364 if ( $row->ipb_by
) { // local user
365 $this->setBlocker( User
::newFromId( $row->ipb_by
) );
366 } else { // foreign user
367 $this->setBlocker( $row->ipb_by_text
);
370 $this->mReason
= $row->ipb_reason
;
371 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
372 $this->mAuto
= $row->ipb_auto
;
373 $this->mHideName
= $row->ipb_deleted
;
374 $this->mId
= $row->ipb_id
;
375 $this->mParentBlockId
= $row->ipb_parent_block_id
;
377 // I wish I didn't have to do this
378 $this->mExpiry
= wfGetDB( DB_SLAVE
)->decodeExpiry( $row->ipb_expiry
);
380 $this->isHardblock( !$row->ipb_anon_only
);
381 $this->isAutoblocking( $row->ipb_enable_autoblock
);
383 $this->prevents( 'createaccount', $row->ipb_create_account
);
384 $this->prevents( 'sendemail', $row->ipb_block_email
);
385 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
389 * Create a new Block object from a database row
390 * @param stdClass $row Row from the ipblocks table
393 public static function newFromRow( $row ) {
395 $block->initFromRow( $row );
400 * Delete the row from the IP blocks table.
402 * @throws MWException
405 public function delete() {
406 if ( wfReadOnly() ) {
410 if ( !$this->getId() ) {
411 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
414 $dbw = wfGetDB( DB_MASTER
);
415 $dbw->delete( 'ipblocks', array( 'ipb_parent_block_id' => $this->getId() ), __METHOD__
);
416 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__
);
418 return $dbw->affectedRows() > 0;
422 * Insert a block into the block table. Will fail if there is a conflicting
423 * block (same name and options) already in the database.
425 * @param DatabaseBase $dbw If you have one available
426 * @return bool|array False on failure, assoc array on success:
427 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
429 public function insert( $dbw = null ) {
430 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
432 if ( $dbw === null ) {
433 $dbw = wfGetDB( DB_MASTER
);
436 # Periodic purge via commit hooks
437 if ( mt_rand( 0, 9 ) == 0 ) {
438 Block
::purgeExpired();
441 $row = $this->getDatabaseArray();
442 $row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );
444 $dbw->insert( 'ipblocks', $row, __METHOD__
, array( 'IGNORE' ) );
445 $affected = $dbw->affectedRows();
446 $this->mId
= $dbw->insertId();
448 # Don't collide with expired blocks.
449 # Do this after trying to insert to avoid locking.
451 # T96428: The ipb_address index uses a prefix on a field, so
452 # use a standard SELECT + DELETE to avoid annoying gap locks.
453 $ids = $dbw->selectFieldValues( 'ipblocks',
456 'ipb_address' => $row['ipb_address'],
457 'ipb_user' => $row['ipb_user'],
458 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
463 $dbw->delete( 'ipblocks', array( 'ipb_id' => $ids ), __METHOD__
);
464 $dbw->insert( 'ipblocks', $row, __METHOD__
, array( 'IGNORE' ) );
465 $affected = $dbw->affectedRows();
466 $this->mId
= $dbw->insertId();
471 $auto_ipd_ids = $this->doRetroactiveAutoblock();
472 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
479 * Update a block in the DB with new parameters.
480 * The ID field needs to be loaded first.
482 * @return bool|array False on failure, array on success:
483 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
485 public function update() {
486 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
487 $dbw = wfGetDB( DB_MASTER
);
489 $dbw->startAtomic( __METHOD__
);
493 $this->getDatabaseArray( $dbw ),
494 array( 'ipb_id' => $this->getId() ),
498 $affected = $dbw->affectedRows();
500 if ( $this->isAutoblocking() ) {
501 // update corresponding autoblock(s) (bug 48813)
504 $this->getAutoblockUpdateArray(),
505 array( 'ipb_parent_block_id' => $this->getId() ),
509 // autoblock no longer required, delete corresponding autoblock(s)
512 array( 'ipb_parent_block_id' => $this->getId() ),
517 $dbw->endAtomic( __METHOD__
);
520 $auto_ipd_ids = $this->doRetroactiveAutoblock();
521 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
528 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
529 * @param DatabaseBase $db
532 protected function getDatabaseArray( $db = null ) {
534 $db = wfGetDB( DB_SLAVE
);
536 $expiry = $db->encodeExpiry( $this->mExpiry
);
538 if ( $this->forcedTargetID
) {
539 $uid = $this->forcedTargetID
;
541 $uid = $this->target
instanceof User ?
$this->target
->getID() : 0;
545 'ipb_address' => (string)$this->target
,
547 'ipb_by' => $this->getBy(),
548 'ipb_by_text' => $this->getByName(),
549 'ipb_reason' => $this->mReason
,
550 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
551 'ipb_auto' => $this->mAuto
,
552 'ipb_anon_only' => !$this->isHardblock(),
553 'ipb_create_account' => $this->prevents( 'createaccount' ),
554 'ipb_enable_autoblock' => $this->isAutoblocking(),
555 'ipb_expiry' => $expiry,
556 'ipb_range_start' => $this->getRangeStart(),
557 'ipb_range_end' => $this->getRangeEnd(),
558 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
559 'ipb_block_email' => $this->prevents( 'sendemail' ),
560 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
561 'ipb_parent_block_id' => $this->mParentBlockId
570 protected function getAutoblockUpdateArray() {
572 'ipb_by' => $this->getBy(),
573 'ipb_by_text' => $this->getByName(),
574 'ipb_reason' => $this->mReason
,
575 'ipb_create_account' => $this->prevents( 'createaccount' ),
576 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
577 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
582 * Retroactively autoblocks the last IP used by the user (if it is a user)
583 * blocked by this Block.
585 * @return array Block IDs of retroactive autoblocks made
587 protected function doRetroactiveAutoblock() {
589 # If autoblock is enabled, autoblock the LAST IP(s) used
590 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
591 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
593 $continue = Hooks
::run(
594 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
597 self
::defaultRetroactiveAutoblock( $this, $blockIds );
604 * Retroactively autoblocks the last IP used by the user (if it is a user)
605 * blocked by this Block. This will use the recentchanges table.
607 * @param Block $block
608 * @param array &$blockIds
610 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
613 // No IPs are in recentchanges table, so nothing to select
614 if ( !$wgPutIPinRC ) {
618 $dbr = wfGetDB( DB_SLAVE
);
620 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
621 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
623 // Just the last IP used.
624 $options['LIMIT'] = 1;
626 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
627 __METHOD__
, $options );
629 if ( !$res->numRows() ) {
630 # No results, don't autoblock anything
631 wfDebug( "No IP found to retroactively autoblock\n" );
633 foreach ( $res as $row ) {
635 $id = $block->doAutoblock( $row->rc_ip
);
645 * Checks whether a given IP is on the autoblock whitelist.
646 * TODO: this probably belongs somewhere else, but not sure where...
648 * @param string $ip The IP to check
651 public static function isWhitelistedFromAutoblocks( $ip ) {
654 // Try to get the autoblock_whitelist from the cache, as it's faster
655 // than getting the msg raw and explode()'ing it.
656 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
657 $lines = $wgMemc->get( $key );
659 $lines = explode( "\n", wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
660 $wgMemc->set( $key, $lines, 3600 * 24 );
663 wfDebug( "Checking the autoblock whitelist..\n" );
665 foreach ( $lines as $line ) {
667 if ( substr( $line, 0, 1 ) !== '*' ) {
671 $wlEntry = substr( $line, 1 );
672 $wlEntry = trim( $wlEntry );
674 wfDebug( "Checking $ip against $wlEntry..." );
676 # Is the IP in this range?
677 if ( IP
::isInRange( $ip, $wlEntry ) ) {
678 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
681 wfDebug( " No match\n" );
689 * Autoblocks the given IP, referring to this Block.
691 * @param string $autoblockIP The IP to autoblock.
692 * @return int|bool Block ID if an autoblock was inserted, false if not.
694 public function doAutoblock( $autoblockIP ) {
695 # If autoblocks are disabled, go away.
696 if ( !$this->isAutoblocking() ) {
700 # Check for presence on the autoblock whitelist.
701 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
705 # Allow hooks to cancel the autoblock.
706 if ( !Hooks
::run( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
707 wfDebug( "Autoblock aborted by hook.\n" );
711 # It's okay to autoblock. Go ahead and insert/update the block...
713 # Do not add a *new* block if the IP is already blocked.
714 $ipblock = Block
::newFromTarget( $autoblockIP );
716 # Check if the block is an autoblock and would exceed the user block
717 # if renewed. If so, do nothing, otherwise prolong the block time...
718 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
719 $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
721 # Reset block timestamp to now and its expiry to
722 # $wgAutoblockExpiry in the future
723 $ipblock->updateTimestamp();
728 # Make a new block object with the desired properties.
729 $autoblock = new Block
;
730 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
731 $autoblock->setTarget( $autoblockIP );
732 $autoblock->setBlocker( $this->getBlocker() );
733 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
734 ->inContentLanguage()->plain();
735 $timestamp = wfTimestampNow();
736 $autoblock->mTimestamp
= $timestamp;
737 $autoblock->mAuto
= 1;
738 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
739 # Continue suppressing the name if needed
740 $autoblock->mHideName
= $this->mHideName
;
741 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
742 $autoblock->mParentBlockId
= $this->mId
;
744 if ( $this->mExpiry
== 'infinity' ) {
745 # Original block was indefinite, start an autoblock now
746 $autoblock->mExpiry
= Block
::getAutoblockExpiry( $timestamp );
748 # If the user is already blocked with an expiry date, we don't
749 # want to pile on top of that.
750 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $timestamp ) );
753 # Insert the block...
754 $status = $autoblock->insert();
761 * Check if a block has expired. Delete it if it is.
764 public function deleteIfExpired() {
766 if ( $this->isExpired() ) {
767 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
771 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
779 * Has the block expired?
782 public function isExpired() {
783 $timestamp = wfTimestampNow();
784 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
786 if ( !$this->mExpiry
) {
789 return $timestamp > $this->mExpiry
;
794 * Is the block address valid (i.e. not a null string?)
797 public function isValid() {
798 return $this->getTarget() != null;
802 * Update the timestamp on autoblocks.
804 public function updateTimestamp() {
805 if ( $this->mAuto
) {
806 $this->mTimestamp
= wfTimestamp();
807 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
809 $dbw = wfGetDB( DB_MASTER
);
810 $dbw->update( 'ipblocks',
812 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
813 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
816 'ipb_address' => (string)$this->getTarget()
824 * Get the IP address at the start of the range in Hex form
825 * @throws MWException
826 * @return string IP in Hex form
828 public function getRangeStart() {
829 switch ( $this->type
) {
830 case self
::TYPE_USER
:
833 return IP
::toHex( $this->target
);
834 case self
::TYPE_RANGE
:
835 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
838 throw new MWException( "Block with invalid type" );
843 * Get the IP address at the end of the range in Hex form
844 * @throws MWException
845 * @return string IP in Hex form
847 public function getRangeEnd() {
848 switch ( $this->type
) {
849 case self
::TYPE_USER
:
852 return IP
::toHex( $this->target
);
853 case self
::TYPE_RANGE
:
854 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
857 throw new MWException( "Block with invalid type" );
862 * Get the user id of the blocking sysop
864 * @return int (0 for foreign users)
866 public function getBy() {
867 $blocker = $this->getBlocker();
868 return ( $blocker instanceof User
)
874 * Get the username of the blocking sysop
878 public function getByName() {
879 $blocker = $this->getBlocker();
880 return ( $blocker instanceof User
)
881 ?
$blocker->getName()
882 : (string)$blocker; // username
889 public function getId() {
894 * Get/set a flag determining whether the master is used for reads
896 * @param bool|null $x
899 public function fromMaster( $x = null ) {
900 return wfSetVar( $this->mFromMaster
, $x );
904 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
905 * @param bool|null $x
908 public function isHardblock( $x = null ) {
909 wfSetVar( $this->isHardblock
, $x );
911 # You can't *not* hardblock a user
912 return $this->getType() == self
::TYPE_USER
914 : $this->isHardblock
;
918 * @param null|bool $x
921 public function isAutoblocking( $x = null ) {
922 wfSetVar( $this->isAutoblocking
, $x );
924 # You can't put an autoblock on an IP or range as we don't have any history to
925 # look over to get more IPs from
926 return $this->getType() == self
::TYPE_USER
927 ?
$this->isAutoblocking
932 * Get/set whether the Block prevents a given action
933 * @param string $action
934 * @param bool|null $x
937 public function prevents( $action, $x = null ) {
940 # For now... <evil laugh>
943 case 'createaccount':
944 return wfSetVar( $this->mCreateAccount
, $x );
947 return wfSetVar( $this->mBlockEmail
, $x );
949 case 'editownusertalk':
950 return wfSetVar( $this->mDisableUsertalk
, $x );
958 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
959 * @return string Text is escaped
961 public function getRedactedName() {
962 if ( $this->mAuto
) {
963 return Html
::rawElement(
965 array( 'class' => 'mw-autoblockid' ),
966 wfMessage( 'autoblockid', $this->mId
)
969 return htmlspecialchars( $this->getTarget() );
974 * Get a timestamp of the expiry for autoblocks
976 * @param string|int $timestamp
979 public static function getAutoblockExpiry( $timestamp ) {
980 global $wgAutoblockExpiry;
982 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
986 * Purge expired blocks from the ipblocks table
988 public static function purgeExpired() {
989 if ( wfReadOnly() ) {
993 $method = __METHOD__
;
994 $dbw = wfGetDB( DB_MASTER
);
995 $dbw->onTransactionIdle( function () use ( $dbw, $method ) {
996 $dbw->delete( 'ipblocks',
997 array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), $method );
1002 * Given a target and the target's type, get an existing Block object if possible.
1003 * @param string|User|int $specificTarget A block target, which may be one of several types:
1004 * * A user to block, in which case $target will be a User
1005 * * An IP to block, in which case $target will be a User generated by using
1006 * User::newFromName( $ip, false ) to turn off name validation
1007 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1008 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1010 * Calling this with a user, IP address or range will not select autoblocks, and will
1011 * only select a block where the targets match exactly (so looking for blocks on
1012 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1013 * @param string|User|int $vagueTarget As above, but we will search for *any* block which
1014 * affects that target (so for an IP address, get ranges containing that IP; and also
1015 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1016 * @param bool $fromMaster Whether to use the DB_MASTER database
1017 * @return Block|null (null if no relevant block could be found). The target and type
1018 * of the returned Block will refer to the actual block which was found, which might
1019 * not be the same as the target you gave if you used $vagueTarget!
1021 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1023 list( $target, $type ) = self
::parseTarget( $specificTarget );
1024 if ( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
) {
1025 return Block
::newFromID( $target );
1027 } elseif ( $target === null && $vagueTarget == '' ) {
1028 # We're not going to find anything useful here
1029 # Be aware that the == '' check is explicit, since empty values will be
1030 # passed by some callers (bug 29116)
1033 } elseif ( in_array(
1035 array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) )
1037 $block = new Block();
1038 $block->fromMaster( $fromMaster );
1040 if ( $type !== null ) {
1041 $block->setTarget( $target );
1044 if ( $block->newLoad( $vagueTarget ) ) {
1052 * Get all blocks that match any IP from an array of IP addresses
1054 * @param array $ipChain List of IPs (strings), usually retrieved from the
1055 * X-Forwarded-For header of the request
1056 * @param bool $isAnon Exclude anonymous-only blocks if false
1057 * @param bool $fromMaster Whether to query the master or slave database
1058 * @return array Array of Blocks
1061 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1062 if ( !count( $ipChain ) ) {
1067 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1068 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1069 # necessarily trust the header given to us, make sure that we are only
1070 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1071 # Do not treat private IP spaces as special as it may be desirable for wikis
1072 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1073 if ( !IP
::isValid( $ipaddr ) ) {
1076 # Don't check trusted IPs (includes local squids which will be in every request)
1077 if ( IP
::isTrustedProxy( $ipaddr ) ) {
1080 # Check both the original IP (to check against single blocks), as well as build
1081 # the clause to check for rangeblocks for the given IP.
1082 $conds['ipb_address'][] = $ipaddr;
1083 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1086 if ( !count( $conds ) ) {
1090 if ( $fromMaster ) {
1091 $db = wfGetDB( DB_MASTER
);
1093 $db = wfGetDB( DB_SLAVE
);
1095 $conds = $db->makeList( $conds, LIST_OR
);
1097 $conds = array( $conds, 'ipb_anon_only' => 0 );
1099 $selectFields = array_merge(
1100 array( 'ipb_range_start', 'ipb_range_end' ),
1101 Block
::selectFields()
1103 $rows = $db->select( 'ipblocks',
1110 foreach ( $rows as $row ) {
1111 $block = self
::newFromRow( $row );
1112 if ( !$block->deleteIfExpired() ) {
1121 * From a list of multiple blocks, find the most exact and strongest Block.
1123 * The logic for finding the "best" block is:
1124 * - Blocks that match the block's target IP are preferred over ones in a range
1125 * - Hardblocks are chosen over softblocks that prevent account creation
1126 * - Softblocks that prevent account creation are chosen over other softblocks
1127 * - Other softblocks are chosen over autoblocks
1128 * - If there are multiple exact or range blocks at the same level, the one chosen
1130 * This should be used when $blocks where retrieved from the user's IP address
1131 * and $ipChain is populated from the same IP address information.
1133 * @param array $blocks Array of Block objects
1134 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1135 * a block is to the server, and if a block matches exactly, or is in a range.
1136 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1138 * @throws MWException
1139 * @return Block|null The "best" block from the list
1141 public static function chooseBlock( array $blocks, array $ipChain ) {
1142 if ( !count( $blocks ) ) {
1144 } elseif ( count( $blocks ) == 1 ) {
1148 // Sort hard blocks before soft ones and secondarily sort blocks
1149 // that disable account creation before those that don't.
1150 usort( $blocks, function ( Block
$a, Block
$b ) {
1151 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1152 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1153 return strcmp( $bWeight, $aWeight ); // highest weight first
1156 $blocksListExact = array(
1158 'disable_create' => false,
1162 $blocksListRange = array(
1164 'disable_create' => false,
1168 $ipChain = array_reverse( $ipChain );
1170 /** @var Block $block */
1171 foreach ( $blocks as $block ) {
1172 // Stop searching if we have already have a "better" block. This
1173 // is why the order of the blocks matters
1174 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1176 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1180 foreach ( $ipChain as $checkip ) {
1181 $checkipHex = IP
::toHex( $checkip );
1182 if ( (string)$block->getTarget() === $checkip ) {
1183 if ( $block->isHardblock() ) {
1184 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1185 } elseif ( $block->prevents( 'createaccount' ) ) {
1186 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1187 } elseif ( $block->mAuto
) {
1188 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1190 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1192 // We found closest exact match in the ip list, so go to the next Block
1194 } elseif ( array_filter( $blocksListExact ) == array()
1195 && $block->getRangeStart() <= $checkipHex
1196 && $block->getRangeEnd() >= $checkipHex
1198 if ( $block->isHardblock() ) {
1199 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1200 } elseif ( $block->prevents( 'createaccount' ) ) {
1201 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1202 } elseif ( $block->mAuto
) {
1203 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1205 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1212 if ( array_filter( $blocksListExact ) == array() ) {
1213 $blocksList = &$blocksListRange;
1215 $blocksList = &$blocksListExact;
1218 $chosenBlock = null;
1219 if ( $blocksList['hard'] ) {
1220 $chosenBlock = $blocksList['hard'];
1221 } elseif ( $blocksList['disable_create'] ) {
1222 $chosenBlock = $blocksList['disable_create'];
1223 } elseif ( $blocksList['other'] ) {
1224 $chosenBlock = $blocksList['other'];
1225 } elseif ( $blocksList['auto'] ) {
1226 $chosenBlock = $blocksList['auto'];
1228 throw new MWException( "Proxy block found, but couldn't be classified." );
1231 return $chosenBlock;
1235 * From an existing Block, get the target and the type of target.
1236 * Note that, except for null, it is always safe to treat the target
1237 * as a string; for User objects this will return User::__toString()
1238 * which in turn gives User::getName().
1240 * @param string|int|User|null $target
1241 * @return array( User|String|null, Block::TYPE_ constant|null )
1243 public static function parseTarget( $target ) {
1244 # We may have been through this before
1245 if ( $target instanceof User
) {
1246 if ( IP
::isValid( $target->getName() ) ) {
1247 return array( $target, self
::TYPE_IP
);
1249 return array( $target, self
::TYPE_USER
);
1251 } elseif ( $target === null ) {
1252 return array( null, null );
1255 $target = trim( $target );
1257 if ( IP
::isValid( $target ) ) {
1258 # We can still create a User if it's an IP address, but we need to turn
1259 # off validation checking (which would exclude IP addresses)
1261 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1265 } elseif ( IP
::isValidBlock( $target ) ) {
1266 # Can't create a User from an IP range
1267 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1270 # Consider the possibility that this is not a username at all
1271 # but actually an old subpage (bug #29797)
1272 if ( strpos( $target, '/' ) !== false ) {
1273 # An old subpage, drill down to the user behind it
1274 $parts = explode( '/', $target );
1275 $target = $parts[0];
1278 $userObj = User
::newFromName( $target );
1279 if ( $userObj instanceof User
) {
1280 # Note that since numbers are valid usernames, a $target of "12345" will be
1281 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1282 # since hash characters are not valid in usernames or titles generally.
1283 return array( $userObj, Block
::TYPE_USER
);
1285 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1286 # Autoblock reference in the form "#12345"
1287 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1291 return array( null, null );
1296 * Get the type of target for this particular block
1297 * @return int Block::TYPE_ constant, will never be TYPE_ID
1299 public function getType() {
1306 * Get the target and target type for this particular Block. Note that for autoblocks,
1307 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1308 * in this situation.
1309 * @return array( User|String, Block::TYPE_ constant )
1310 * @todo FIXME: This should be an integral part of the Block member variables
1312 public function getTargetAndType() {
1313 return array( $this->getTarget(), $this->getType() );
1317 * Get the target for this particular Block. Note that for autoblocks,
1318 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1319 * in this situation.
1320 * @return User|string
1322 public function getTarget() {
1323 return $this->target
;
1329 * @return mixed|string
1331 public function getExpiry() {
1332 return $this->mExpiry
;
1336 * Set the target for this block, and update $this->type accordingly
1337 * @param mixed $target
1339 public function setTarget( $target ) {
1340 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1344 * Get the user who implemented this block
1345 * @return User|string Local User object or string for a foreign user
1347 public function getBlocker() {
1348 return $this->blocker
;
1352 * Set the user who implemented (or will implement) this block
1353 * @param User|string $user Local User object or username string for foreign users
1355 public function setBlocker( $user ) {
1356 $this->blocker
= $user;
1360 * Get the key and parameters for the corresponding error message.
1363 * @param IContextSource $context
1366 public function getPermissionsError( IContextSource
$context ) {
1367 $blocker = $this->getBlocker();
1368 if ( $blocker instanceof User
) { // local user
1369 $blockerUserpage = $blocker->getUserPage();
1370 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1371 } else { // foreign user
1375 $reason = $this->mReason
;
1376 if ( $reason == '' ) {
1377 $reason = $context->msg( 'blockednoreason' )->text();
1380 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1381 * This could be a username, an IP range, or a single IP. */
1382 $intended = $this->getTarget();
1384 $lang = $context->getLanguage();
1386 $this->mAuto ?
'autoblockedtext' : 'blockedtext',
1389 $context->getRequest()->getIP(),
1392 $lang->formatExpiry( $this->mExpiry
),
1394 $lang->userTimeAndDate( $this->mTimestamp
, $context->getUser() ),