3 * Class for blocks stored in the database.
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 namespace MediaWiki\Block
;
27 use BadMethodCallException
;
34 use MediaWiki\Block\Restriction\NamespaceRestriction
;
35 use MediaWiki\Block\Restriction\PageRestriction
;
36 use MediaWiki\Block\Restriction\Restriction
;
37 use MediaWiki\MediaWikiServices
;
44 use Wikimedia\Rdbms\Database
;
45 use Wikimedia\Rdbms\IDatabase
;
48 * A DatabaseBlock (unlike a SystemBlock) is stored in the database, may
49 * give rise to autoblocks and may be tracked with cookies. Such blocks
50 * are more customizable than system blocks: they may be hardblocks, and
51 * they may be sitewide or partial.
53 * @since 1.34 Renamed from Block.
55 class DatabaseBlock
extends AbstractBlock
{
57 * @deprecated since 1.34. Use getType to check whether a block is autoblocking.
63 * @deprecated since 1.34. Use getParentBlockId instead.
66 public $mParentBlockId;
74 /** @var int Hack for foreign blocking (CentralAuth) */
75 private $forcedTargetID;
81 private $isAutoblocking;
83 /** @var Restriction[] */
84 private $restrictions;
87 * Create a new block with specified option parameters on a user, IP or IP range.
89 * @param array $options Parameters of the block, with options supported by
90 * `AbstractBlock::__construct`, and also:
91 * - user: (int) Override target user ID (for foreign users)
92 * - auto: (bool) Is this an automatic block?
93 * - expiry: (string) Timestamp of expiration of the block or 'infinity'
94 * - anonOnly: (bool) Only disallow anonymous actions
95 * - createAccount: (bool) Disallow creation of new accounts
96 * - enableAutoblock: (bool) Enable automatic blocking
97 * - blockEmail: (bool) Disallow sending emails
98 * - allowUsertalk: (bool) Allow the target to edit its own talk page
99 * - sitewide: (bool) Disallow editing all pages and all contribution actions,
100 * except those specifically allowed by other block flags
102 * @since 1.26 $options array
104 public function __construct( array $options = [] ) {
105 parent
::__construct( $options );
112 'createAccount' => false,
113 'enableAutoblock' => false,
114 'blockEmail' => false,
115 'allowUsertalk' => false,
119 $options +
= $defaults;
121 if ( $this->target
instanceof User
&& $options['user'] ) {
122 # Needed for foreign users
123 $this->forcedTargetID
= $options['user'];
126 $this->setExpiry( wfGetDB( DB_REPLICA
)->decodeExpiry( $options['expiry'] ) );
129 $this->mAuto
= (bool)$options['auto'];
130 $this->isHardblock( !$options['anonOnly'] );
131 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
132 $this->isSitewide( (bool)$options['sitewide'] );
133 $this->isEmailBlocked( (bool)$options['blockEmail'] );
134 $this->isCreateAccountBlocked( (bool)$options['createAccount'] );
135 $this->isUsertalkEditAllowed( (bool)$options['allowUsertalk'] );
137 $this->mFromMaster
= false;
141 * Load a block from the block id.
143 * @param int $id id to search for
144 * @return DatabaseBlock|null
146 public static function newFromID( $id ) {
147 $dbr = wfGetDB( DB_REPLICA
);
148 $blockQuery = self
::getQueryInfo();
149 $res = $dbr->selectRow(
150 $blockQuery['tables'],
151 $blockQuery['fields'],
158 return self
::newFromRow( $res );
165 * Return the list of ipblocks fields that should be selected to create
167 * @deprecated since 1.31, use self::getQueryInfo() instead.
170 public static function selectFields() {
171 global $wgActorTableSchemaMigrationStage;
173 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
174 // If code is using this instead of self::getQueryInfo(), there's a
175 // decent chance it's going to try to directly access
176 // $row->ipb_by or $row->ipb_by_text and we can't give it
177 // useful values here once those aren't being used anymore.
178 throw new BadMethodCallException(
179 'Cannot use ' . __METHOD__
180 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
184 wfDeprecated( __METHOD__
, '1.31' );
190 'ipb_by_actor' => 'NULL',
194 'ipb_create_account',
195 'ipb_enable_autoblock',
199 'ipb_allow_usertalk',
200 'ipb_parent_block_id',
202 ] + CommentStore
::getStore()->getFields( 'ipb_reason' );
206 * Return the tables, fields, and join conditions to be selected to create
207 * a new block object.
209 * @return array With three keys:
210 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
211 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
212 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
214 public static function getQueryInfo() {
215 $commentQuery = CommentStore
::getStore()->getJoin( 'ipb_reason' );
216 $actorQuery = ActorMigration
::newMigration()->getJoin( 'ipb_by' );
218 'tables' => [ 'ipblocks' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
225 'ipb_create_account',
226 'ipb_enable_autoblock',
230 'ipb_allow_usertalk',
231 'ipb_parent_block_id',
233 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
234 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
239 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
240 * the blocking user or the block timestamp, only things which affect the blocked user
242 * @param DatabaseBlock $block
245 public function equals( DatabaseBlock
$block ) {
247 (string)$this->target
== (string)$block->target
248 && $this->type
== $block->type
249 && $this->mAuto
== $block->mAuto
250 && $this->isHardblock() == $block->isHardblock()
251 && $this->isCreateAccountBlocked() == $block->isCreateAccountBlocked()
252 && $this->getExpiry() == $block->getExpiry()
253 && $this->isAutoblocking() == $block->isAutoblocking()
254 && $this->getHideName() == $block->getHideName()
255 && $this->isEmailBlocked() == $block->isEmailBlocked()
256 && $this->isUsertalkEditAllowed() == $block->isUsertalkEditAllowed()
257 && $this->getReason() == $block->getReason()
258 && $this->isSitewide() == $block->isSitewide()
259 // DatabaseBlock::getRestrictions() may perform a database query, so
260 // keep it at the end.
261 && $this->getBlockRestrictionStore()->equals(
262 $this->getRestrictions(), $block->getRestrictions()
268 * Load blocks from the database which target the specific target exactly, or which cover the
271 * @param User|string|null $specificTarget
272 * @param int|null $specificType
273 * @param bool $fromMaster
274 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
275 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
276 * @throws MWException
277 * @return DatabaseBlock[] Any relevant blocks
279 protected static function newLoad(
285 $db = wfGetDB( $fromMaster ? DB_MASTER
: DB_REPLICA
);
287 if ( $specificType !== null ) {
289 'ipb_address' => [ (string)$specificTarget ],
292 $conds = [ 'ipb_address' => [] ];
295 # Be aware that the != '' check is explicit, since empty values will be
296 # passed by some callers (T31116)
297 if ( $vagueTarget != '' ) {
298 list( $target, $type ) = self
::parseTarget( $vagueTarget );
300 case self
::TYPE_USER
:
301 # Slightly weird, but who are we to argue?
302 $conds['ipb_address'][] = (string)$target;
306 $conds['ipb_address'][] = (string)$target;
307 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
308 $conds = $db->makeList( $conds, LIST_OR
);
311 case self
::TYPE_RANGE
:
312 list( $start, $end ) = IP
::parseRange( $target );
313 $conds['ipb_address'][] = (string)$target;
314 $conds[] = self
::getRangeCond( $start, $end );
315 $conds = $db->makeList( $conds, LIST_OR
);
319 throw new MWException( "Tried to load block with invalid type" );
323 $blockQuery = self
::getQueryInfo();
325 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
331 foreach ( $res as $row ) {
332 $block = self
::newFromRow( $row );
334 # Don't use expired blocks
335 if ( $block->isExpired() ) {
339 # Don't use anon only blocks on users
340 if ( $specificType == self
::TYPE_USER
&& !$block->isHardblock() ) {
344 // Check for duplicate autoblocks
345 if ( $block->getType() === self
::TYPE_AUTO
) {
346 $autoBlocks[] = $block;
349 $blockIds[] = $block->getId();
353 // Only add autoblocks that aren't duplicates
354 foreach ( $autoBlocks as $block ) {
355 if ( !in_array( $block->mParentBlockId
, $blockIds ) ) {
364 * Choose the most specific block from some combination of user, IP and IP range
365 * blocks. Decreasing order of specificity: user > IP > narrower IP range > wider IP
366 * range. A range that encompasses one IP address is ranked equally to a singe IP.
368 * Note that DatabaseBlock::chooseBlocks chooses blocks in a different way.
370 * This is refactored out from DatabaseBlock::newLoad.
372 * @param DatabaseBlock[] $blocks These should not include autoblocks or ID blocks
373 * @return DatabaseBlock|null The block with the most specific target
375 protected static function chooseMostSpecificBlock( array $blocks ) {
376 if ( count( $blocks ) === 1 ) {
380 # This result could contain a block on the user, a block on the IP, and a russian-doll
381 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
384 # Lower will be better
385 $bestBlockScore = 100;
386 foreach ( $blocks as $block ) {
387 if ( $block->getType() == self
::TYPE_RANGE
) {
388 # This is the number of bits that are allowed to vary in the block, give
389 # or take some floating point errors
390 $target = $block->getTarget();
391 $max = IP
::isIPv6( $target ) ?
128 : 32;
392 list( $network, $bits ) = IP
::parseCIDR( $target );
393 $size = $max - $bits;
395 # Rank a range block covering a single IP equally with a single-IP block
396 $score = self
::TYPE_RANGE
- 1 +
( $size / $max );
399 $score = $block->getType();
402 if ( $score < $bestBlockScore ) {
403 $bestBlockScore = $score;
412 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
413 * @param string $start Hexadecimal IP representation
414 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
417 public static function getRangeCond( $start, $end = null ) {
418 if ( $end === null ) {
421 # Per T16634, we want to include relevant active rangeblocks; for
422 # rangeblocks, we want to include larger ranges which enclose the given
423 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
424 # so we can improve performance by filtering on a LIKE clause
425 $chunk = self
::getIpFragment( $start );
426 $dbr = wfGetDB( DB_REPLICA
);
427 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
429 # Fairly hard to make a malicious SQL statement out of hex characters,
430 # but stranger things have happened...
431 $safeStart = $dbr->addQuotes( $start );
432 $safeEnd = $dbr->addQuotes( $end );
434 return $dbr->makeList(
436 "ipb_range_start $like",
437 "ipb_range_start <= $safeStart",
438 "ipb_range_end >= $safeEnd",
445 * Get the component of an IP address which is certain to be the same between an IP
446 * address and a rangeblock containing that IP address.
447 * @param string $hex Hexadecimal IP representation
450 protected static function getIpFragment( $hex ) {
451 global $wgBlockCIDRLimit;
452 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
453 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
455 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
460 * Given a database row from the ipblocks table, initialize
462 * @param stdClass $row A row from the ipblocks table
464 protected function initFromRow( $row ) {
465 $this->setTarget( $row->ipb_address
);
466 $this->setBlocker( User
::newFromAnyId(
467 $row->ipb_by
, $row->ipb_by_text
, $row->ipb_by_actor ??
null
470 $this->setTimestamp( wfTimestamp( TS_MW
, $row->ipb_timestamp
) );
471 $this->mAuto
= $row->ipb_auto
;
472 $this->setHideName( $row->ipb_deleted
);
473 $this->mId
= (int)$row->ipb_id
;
474 $this->mParentBlockId
= $row->ipb_parent_block_id
;
476 // I wish I didn't have to do this
477 $db = wfGetDB( DB_REPLICA
);
478 $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry
) );
480 CommentStore
::getStore()
481 // Legacy because $row may have come from self::selectFields()
482 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
485 $this->isHardblock( !$row->ipb_anon_only
);
486 $this->isAutoblocking( $row->ipb_enable_autoblock
);
487 $this->isSitewide( (bool)$row->ipb_sitewide
);
489 $this->isCreateAccountBlocked( $row->ipb_create_account
);
490 $this->isEmailBlocked( $row->ipb_block_email
);
491 $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk
);
495 * Create a new DatabaseBlock object from a database row
496 * @param stdClass $row Row from the ipblocks table
497 * @return DatabaseBlock
499 public static function newFromRow( $row ) {
500 $block = new DatabaseBlock
;
501 $block->initFromRow( $row );
506 * Delete the row from the IP blocks table.
508 * @throws MWException
511 public function delete() {
512 if ( wfReadOnly() ) {
516 if ( !$this->getId() ) {
517 throw new MWException(
518 __METHOD__
. " requires that the mId member be filled\n"
522 $dbw = wfGetDB( DB_MASTER
);
524 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
525 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
527 $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
528 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
530 return $dbw->affectedRows() > 0;
534 * Insert a block into the block table. Will fail if there is a conflicting
535 * block (same name and options) already in the database.
537 * @param IDatabase|null $dbw If you have one available
538 * @return bool|array False on failure, assoc array on success:
539 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
541 public function insert( IDatabase
$dbw = null ) {
542 global $wgBlockDisablesLogin;
544 if ( !$this->getBlocker() ||
$this->getBlocker()->getName() === '' ) {
545 throw new MWException( 'Cannot insert a block without a blocker set' );
548 wfDebug( __METHOD__
. "; timestamp {$this->mTimestamp}\n" );
550 if ( $dbw === null ) {
551 $dbw = wfGetDB( DB_MASTER
);
554 self
::purgeExpired();
556 $row = $this->getDatabaseArray( $dbw );
558 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
559 $affected = $dbw->affectedRows();
561 $this->setId( $dbw->insertId() );
562 if ( $this->restrictions
) {
563 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
567 # Don't collide with expired blocks.
568 # Do this after trying to insert to avoid locking.
570 # T96428: The ipb_address index uses a prefix on a field, so
571 # use a standard SELECT + DELETE to avoid annoying gap locks.
572 $ids = $dbw->selectFieldValues( 'ipblocks',
575 'ipb_address' => $row['ipb_address'],
576 'ipb_user' => $row['ipb_user'],
577 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
582 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
583 $this->getBlockRestrictionStore()->deleteByBlockId( $ids );
584 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
585 $affected = $dbw->affectedRows();
586 $this->setId( $dbw->insertId() );
587 if ( $this->restrictions
) {
588 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
594 $auto_ipd_ids = $this->doRetroactiveAutoblock();
596 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
597 // Change user login token to force them to be logged out.
598 $this->target
->setToken();
599 $this->target
->saveSettings();
602 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
609 * Update a block in the DB with new parameters.
610 * The ID field needs to be loaded first.
612 * @return bool|array False on failure, array on success:
613 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
615 public function update() {
616 wfDebug( __METHOD__
. "; timestamp {$this->mTimestamp}\n" );
617 $dbw = wfGetDB( DB_MASTER
);
619 $dbw->startAtomic( __METHOD__
);
621 $result = $dbw->update(
623 $this->getDatabaseArray( $dbw ),
624 [ 'ipb_id' => $this->getId() ],
628 // Only update the restrictions if they have been modified.
629 if ( $this->restrictions
!== null ) {
630 // An empty array should remove all of the restrictions.
631 if ( empty( $this->restrictions
) ) {
632 $success = $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
634 $success = $this->getBlockRestrictionStore()->update( $this->restrictions
);
636 // Update the result. The first false is the result, otherwise, true.
637 $result = $result && $success;
640 if ( $this->isAutoblocking() ) {
641 // update corresponding autoblock(s) (T50813)
644 $this->getAutoblockUpdateArray( $dbw ),
645 [ 'ipb_parent_block_id' => $this->getId() ],
649 // Only update the restrictions if they have been modified.
650 if ( $this->restrictions
!== null ) {
651 $this->getBlockRestrictionStore()->updateByParentBlockId( $this->getId(), $this->restrictions
);
654 // autoblock no longer required, delete corresponding autoblock(s)
655 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
658 [ 'ipb_parent_block_id' => $this->getId() ],
663 $dbw->endAtomic( __METHOD__
);
666 $auto_ipd_ids = $this->doRetroactiveAutoblock();
667 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
674 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
675 * @param IDatabase $dbw
678 protected function getDatabaseArray( IDatabase
$dbw ) {
679 $expiry = $dbw->encodeExpiry( $this->getExpiry() );
681 if ( $this->forcedTargetID
) {
682 $uid = $this->forcedTargetID
;
684 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
688 'ipb_address' => (string)$this->target
,
690 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
691 'ipb_auto' => $this->mAuto
,
692 'ipb_anon_only' => !$this->isHardblock(),
693 'ipb_create_account' => $this->isCreateAccountBlocked(),
694 'ipb_enable_autoblock' => $this->isAutoblocking(),
695 'ipb_expiry' => $expiry,
696 'ipb_range_start' => $this->getRangeStart(),
697 'ipb_range_end' => $this->getRangeEnd(),
698 'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
699 'ipb_block_email' => $this->isEmailBlocked(),
700 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
701 'ipb_parent_block_id' => $this->mParentBlockId
,
702 'ipb_sitewide' => $this->isSitewide(),
703 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
704 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
710 * @param IDatabase $dbw
713 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
715 'ipb_create_account' => $this->isCreateAccountBlocked(),
716 'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
717 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
718 'ipb_sitewide' => $this->isSitewide(),
719 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
720 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
724 * Retroactively autoblocks the last IP used by the user (if it is a user)
725 * blocked by this block.
727 * @return array IDs of retroactive autoblocks made
729 protected function doRetroactiveAutoblock() {
731 # If autoblock is enabled, autoblock the LAST IP(s) used
732 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
733 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
735 $continue = Hooks
::run(
736 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
739 self
::defaultRetroactiveAutoblock( $this, $blockIds );
746 * Retroactively autoblocks the last IP used by the user (if it is a user)
747 * blocked by this block. This will use the recentchanges table.
749 * @param DatabaseBlock $block
750 * @param array &$blockIds
752 protected static function defaultRetroactiveAutoblock( DatabaseBlock
$block, array &$blockIds ) {
755 // No IPs are in recentchanges table, so nothing to select
756 if ( !$wgPutIPinRC ) {
760 // Autoblocks only apply to TYPE_USER
761 if ( $block->getType() !== self
::TYPE_USER
) {
764 $target = $block->getTarget(); // TYPE_USER => always a User object
766 $dbr = wfGetDB( DB_REPLICA
);
767 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
769 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
771 // Just the last IP used.
772 $options['LIMIT'] = 1;
775 [ 'recentchanges' ] +
$rcQuery['tables'],
783 if ( !$res->numRows() ) {
784 # No results, don't autoblock anything
785 wfDebug( "No IP found to retroactively autoblock\n" );
787 foreach ( $res as $row ) {
789 $id = $block->doAutoblock( $row->rc_ip
);
799 * Checks whether a given IP is on the autoblock whitelist.
800 * TODO: this probably belongs somewhere else, but not sure where...
802 * @param string $ip The IP to check
805 public static function isWhitelistedFromAutoblocks( $ip ) {
806 // Try to get the autoblock_whitelist from the cache, as it's faster
807 // than getting the msg raw and explode()'ing it.
808 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
809 $lines = $cache->getWithSetCallback(
810 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
812 function ( $curValue, &$ttl, array &$setOpts ) {
813 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
815 return explode( "\n",
816 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
820 wfDebug( "Checking the autoblock whitelist..\n" );
822 foreach ( $lines as $line ) {
824 if ( substr( $line, 0, 1 ) !== '*' ) {
828 $wlEntry = substr( $line, 1 );
829 $wlEntry = trim( $wlEntry );
831 wfDebug( "Checking $ip against $wlEntry..." );
833 # Is the IP in this range?
834 if ( IP
::isInRange( $ip, $wlEntry ) ) {
835 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
838 wfDebug( " No match\n" );
846 * Autoblocks the given IP, referring to this block.
848 * @param string $autoblockIP The IP to autoblock.
849 * @return int|bool ID if an autoblock was inserted, false if not.
851 public function doAutoblock( $autoblockIP ) {
852 # If autoblocks are disabled, go away.
853 if ( !$this->isAutoblocking() ) {
857 # Check for presence on the autoblock whitelist.
858 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
862 // Avoid PHP 7.1 warning of passing $this by reference
864 # Allow hooks to cancel the autoblock.
865 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
866 wfDebug( "Autoblock aborted by hook.\n" );
870 # It's okay to autoblock. Go ahead and insert/update the block...
872 # Do not add a *new* block if the IP is already blocked.
873 $ipblock = self
::newFromTarget( $autoblockIP );
875 # Check if the block is an autoblock and would exceed the user block
876 # if renewed. If so, do nothing, otherwise prolong the block time...
877 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
878 $this->getExpiry() > self
::getAutoblockExpiry( $ipblock->getTimestamp() )
880 # Reset block timestamp to now and its expiry to
881 # $wgAutoblockExpiry in the future
882 $ipblock->updateTimestamp();
887 # Make a new block object with the desired properties.
888 $autoblock = new DatabaseBlock
;
889 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
890 $autoblock->setTarget( $autoblockIP );
891 $autoblock->setBlocker( $this->getBlocker() );
892 $autoblock->setReason(
893 wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
894 ->inContentLanguage()->plain()
896 $timestamp = wfTimestampNow();
897 $autoblock->setTimestamp( $timestamp );
898 $autoblock->mAuto
= 1;
899 $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
900 # Continue suppressing the name if needed
901 $autoblock->setHideName( $this->getHideName() );
902 $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
903 $autoblock->mParentBlockId
= $this->mId
;
904 $autoblock->isSitewide( $this->isSitewide() );
905 $autoblock->setRestrictions( $this->getRestrictions() );
907 if ( $this->getExpiry() == 'infinity' ) {
908 # Original block was indefinite, start an autoblock now
909 $autoblock->setExpiry( self
::getAutoblockExpiry( $timestamp ) );
911 # If the user is already blocked with an expiry date, we don't
912 # want to pile on top of that.
913 $autoblock->setExpiry( min( $this->getExpiry(), self
::getAutoblockExpiry( $timestamp ) ) );
916 # Insert the block...
917 $status = $autoblock->insert();
924 * Check if a block has expired. Delete it if it is.
927 public function deleteIfExpired() {
928 if ( $this->isExpired() ) {
929 wfDebug( __METHOD__
. " -- deleting\n" );
933 wfDebug( __METHOD__
. " -- not expired\n" );
941 * Has the block expired?
944 public function isExpired() {
945 $timestamp = wfTimestampNow();
946 wfDebug( __METHOD__
. " checking current " . $timestamp . " vs $this->mExpiry\n" );
948 if ( !$this->getExpiry() ) {
951 return $timestamp > $this->getExpiry();
956 * Is the block address valid (i.e. not a null string?)
958 * @deprecated since 1.33 No longer needed in core.
961 public function isValid() {
962 wfDeprecated( __METHOD__
, '1.33' );
963 return $this->getTarget() != null;
967 * Update the timestamp on autoblocks.
969 public function updateTimestamp() {
970 if ( $this->mAuto
) {
971 $this->setTimestamp( wfTimestamp() );
972 $this->setExpiry( self
::getAutoblockExpiry( $this->getTimestamp() ) );
974 $dbw = wfGetDB( DB_MASTER
);
975 $dbw->update( 'ipblocks',
977 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
978 'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
981 'ipb_id' => $this->getId(),
989 * Get the IP address at the start of the range in Hex form
990 * @throws MWException
991 * @return string IP in Hex form
993 public function getRangeStart() {
994 switch ( $this->type
) {
995 case self
::TYPE_USER
:
998 return IP
::toHex( $this->target
);
999 case self
::TYPE_RANGE
:
1000 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
1003 throw new MWException( "Block with invalid type" );
1008 * Get the IP address at the end of the range in Hex form
1009 * @throws MWException
1010 * @return string IP in Hex form
1012 public function getRangeEnd() {
1013 switch ( $this->type
) {
1014 case self
::TYPE_USER
:
1017 return IP
::toHex( $this->target
);
1018 case self
::TYPE_RANGE
:
1019 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
1022 throw new MWException( "Block with invalid type" );
1029 public function getId() {
1036 * @param int $blockId
1039 private function setId( $blockId ) {
1040 $this->mId
= (int)$blockId;
1042 if ( is_array( $this->restrictions
) ) {
1043 $this->restrictions
= $this->getBlockRestrictionStore()->setBlockId(
1044 $blockId, $this->restrictions
1053 * @return int|null If this is an autoblock, ID of the parent block; otherwise null
1055 public function getParentBlockId() {
1056 return $this->mParentBlockId
;
1060 * Get/set a flag determining whether the master is used for reads
1062 * @param bool|null $x
1065 public function fromMaster( $x = null ) {
1066 return wfSetVar( $this->mFromMaster
, $x );
1070 * Get/set whether the block is a hardblock (affects logged-in users on a given IP/range)
1071 * @param bool|null $x
1074 public function isHardblock( $x = null ) {
1075 wfSetVar( $this->isHardblock
, $x );
1077 # You can't *not* hardblock a user
1078 return $this->getType() == self
::TYPE_USER
1080 : $this->isHardblock
;
1084 * @param null|bool $x
1087 public function isAutoblocking( $x = null ) {
1088 wfSetVar( $this->isAutoblocking
, $x );
1090 # You can't put an autoblock on an IP or range as we don't have any history to
1091 # look over to get more IPs from
1092 return $this->getType() == self
::TYPE_USER
1093 ?
$this->isAutoblocking
1098 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1099 * @return string Text is escaped
1101 public function getRedactedName() {
1102 if ( $this->mAuto
) {
1103 return Html
::element(
1105 [ 'class' => 'mw-autoblockid' ],
1106 wfMessage( 'autoblockid', $this->mId
)->text()
1109 return htmlspecialchars( $this->getTarget() );
1114 * Get a timestamp of the expiry for autoblocks
1116 * @param string|int $timestamp
1119 public static function getAutoblockExpiry( $timestamp ) {
1120 global $wgAutoblockExpiry;
1122 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1126 * Purge expired blocks from the ipblocks table
1128 public static function purgeExpired() {
1129 if ( wfReadOnly() ) {
1133 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1134 wfGetDB( DB_MASTER
),
1136 function ( IDatabase
$dbw, $fname ) {
1137 $ids = $dbw->selectFieldValues( 'ipblocks',
1139 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1143 $blockRestrictionStore = MediaWikiServices
::getInstance()->getBlockRestrictionStore();
1144 $blockRestrictionStore->deleteByBlockId( $ids );
1146 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1153 * Given a target and the target's type, get an existing block object if possible.
1154 * @param string|User|int $specificTarget A block target, which may be one of several types:
1155 * * A user to block, in which case $target will be a User
1156 * * An IP to block, in which case $target will be a User generated by using
1157 * User::newFromName( $ip, false ) to turn off name validation
1158 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1159 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1161 * Calling this with a user, IP address or range will not select autoblocks, and will
1162 * only select a block where the targets match exactly (so looking for blocks on
1163 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1164 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1165 * affects that target (so for an IP address, get ranges containing that IP; and also
1166 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1167 * @param bool $fromMaster Whether to use the DB_MASTER database
1168 * @return DatabaseBlock|null (null if no relevant block could be found). The target and type
1169 * of the returned block will refer to the actual block which was found, which might
1170 * not be the same as the target you gave if you used $vagueTarget!
1172 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1173 $blocks = self
::newListFromTarget( $specificTarget, $vagueTarget, $fromMaster );
1174 return self
::chooseMostSpecificBlock( $blocks );
1178 * This is similar to DatabaseBlock::newFromTarget, but it returns all the relevant blocks.
1181 * @param string|User|int|null $specificTarget
1182 * @param string|User|int|null $vagueTarget
1183 * @param bool $fromMaster
1184 * @return DatabaseBlock[] Any relevant blocks
1186 public static function newListFromTarget(
1188 $vagueTarget = null,
1191 list( $target, $type ) = self
::parseTarget( $specificTarget );
1192 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1193 $block = self
::newFromID( $target );
1194 return $block ?
[ $block ] : [];
1195 } elseif ( $target === null && $vagueTarget == '' ) {
1196 # We're not going to find anything useful here
1197 # Be aware that the == '' check is explicit, since empty values will be
1198 # passed by some callers (T31116)
1200 } elseif ( in_array(
1202 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1204 return self
::newLoad( $target, $type, $fromMaster, $vagueTarget );
1210 * Get all blocks that match any IP from an array of IP addresses
1212 * @param array $ipChain List of IPs (strings), usually retrieved from the
1213 * X-Forwarded-For header of the request
1214 * @param bool $isAnon Exclude anonymous-only blocks if false
1215 * @param bool $fromMaster Whether to query the master or replica DB
1216 * @return array Array of Blocks
1219 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1220 if ( $ipChain === [] ) {
1225 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1226 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1227 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1228 # necessarily trust the header given to us, make sure that we are only
1229 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1230 # Do not treat private IP spaces as special as it may be desirable for wikis
1231 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1232 if ( !IP
::isValid( $ipaddr ) ) {
1235 # Don't check trusted IPs (includes local CDNs which will be in every request)
1236 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1239 # Check both the original IP (to check against single blocks), as well as build
1240 # the clause to check for rangeblocks for the given IP.
1241 $conds['ipb_address'][] = $ipaddr;
1242 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1245 if ( $conds === [] ) {
1249 if ( $fromMaster ) {
1250 $db = wfGetDB( DB_MASTER
);
1252 $db = wfGetDB( DB_REPLICA
);
1254 $conds = $db->makeList( $conds, LIST_OR
);
1256 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1258 $blockQuery = self
::getQueryInfo();
1259 $rows = $db->select(
1260 $blockQuery['tables'],
1261 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1265 $blockQuery['joins']
1269 foreach ( $rows as $row ) {
1270 $block = self
::newFromRow( $row );
1271 if ( !$block->isExpired() ) {
1280 * From a list of multiple blocks, find the most exact and strongest block.
1282 * The logic for finding the "best" block is:
1283 * - Blocks that match the block's target IP are preferred over ones in a range
1284 * - Hardblocks are chosen over softblocks that prevent account creation
1285 * - Softblocks that prevent account creation are chosen over other softblocks
1286 * - Other softblocks are chosen over autoblocks
1287 * - If there are multiple exact or range blocks at the same level, the one chosen
1289 * This should be used when $blocks were retrieved from the user's IP address
1290 * and $ipChain is populated from the same IP address information.
1292 * @param array $blocks Array of DatabaseBlock objects
1293 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1294 * a block is to the server, and if a block matches exactly, or is in a range.
1295 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1297 * @throws MWException
1298 * @return DatabaseBlock|null The "best" block from the list
1300 public static function chooseBlock( array $blocks, array $ipChain ) {
1301 if ( $blocks === [] ) {
1303 } elseif ( count( $blocks ) == 1 ) {
1307 // Sort hard blocks before soft ones and secondarily sort blocks
1308 // that disable account creation before those that don't.
1309 usort( $blocks, function ( DatabaseBlock
$a, DatabaseBlock
$b ) {
1310 $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1311 $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1312 return strcmp( $bWeight, $aWeight ); // highest weight first
1315 $blocksListExact = [
1317 'disable_create' => false,
1321 $blocksListRange = [
1323 'disable_create' => false,
1327 $ipChain = array_reverse( $ipChain );
1329 foreach ( $blocks as $block ) {
1330 // Stop searching if we have already have a "better" block. This
1331 // is why the order of the blocks matters
1332 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1334 } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1338 foreach ( $ipChain as $checkip ) {
1339 $checkipHex = IP
::toHex( $checkip );
1340 if ( (string)$block->getTarget() === $checkip ) {
1341 if ( $block->isHardblock() ) {
1342 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1343 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1344 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1345 } elseif ( $block->mAuto
) {
1346 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1348 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1350 // We found closest exact match in the ip list, so go to the next block
1352 } elseif ( array_filter( $blocksListExact ) == []
1353 && $block->getRangeStart() <= $checkipHex
1354 && $block->getRangeEnd() >= $checkipHex
1356 if ( $block->isHardblock() ) {
1357 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1358 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1359 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1360 } elseif ( $block->mAuto
) {
1361 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1363 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1370 if ( array_filter( $blocksListExact ) == [] ) {
1371 $blocksList = &$blocksListRange;
1373 $blocksList = &$blocksListExact;
1376 $chosenBlock = null;
1377 if ( $blocksList['hard'] ) {
1378 $chosenBlock = $blocksList['hard'];
1379 } elseif ( $blocksList['disable_create'] ) {
1380 $chosenBlock = $blocksList['disable_create'];
1381 } elseif ( $blocksList['other'] ) {
1382 $chosenBlock = $blocksList['other'];
1383 } elseif ( $blocksList['auto'] ) {
1384 $chosenBlock = $blocksList['auto'];
1386 throw new MWException( "Proxy block found, but couldn't be classified." );
1389 return $chosenBlock;
1395 * Autoblocks have whichever type corresponds to their target, so to detect if a block is an
1396 * autoblock, we have to check the mAuto property instead.
1398 public function getType() {
1401 : parent
::getType();
1405 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1406 * the same as the block's, to a maximum of 24 hours.
1409 * @deprecated since 1.34 Set a cookie via BlockManager::trackBlockWithCookie instead.
1410 * @param WebResponse $response The response on which to set the cookie.
1412 public function setCookie( WebResponse
$response ) {
1413 MediaWikiServices
::getInstance()->getBlockManager()->setBlockCookie( $this, $response );
1417 * Unset the 'BlockID' cookie.
1420 * @deprecated since 1.34 Use BlockManager::clearBlockCookie instead
1421 * @param WebResponse $response The response on which to unset the cookie.
1423 public static function clearCookie( WebResponse
$response ) {
1424 MediaWikiServices
::getInstance()->getBlockManager()->clearBlockCookie( $response );
1428 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1429 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1433 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead of calling this
1435 * @return string The block ID, probably concatenated with "!" and the HMAC.
1437 public function getCookieValue() {
1438 return MediaWikiServices
::getInstance()->getBlockManager()->getCookieValue( $this );
1442 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1443 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
1446 * @deprecated since 1.34 Use BlockManager::getUserBlock instead
1447 * @param string $cookieValue The string in which to find the ID.
1448 * @return int|null The block ID, or null if the HMAC is present and invalid.
1450 public static function getIdFromCookieValue( $cookieValue ) {
1451 return MediaWikiServices
::getInstance()->getBlockManager()->getIdFromCookieValue( $cookieValue );
1457 * Build different messages for autoblocks and partial blocks.
1459 public function getPermissionsError( IContextSource
$context ) {
1460 $params = $this->getBlockErrorParams( $context );
1462 $msg = 'blockedtext';
1463 if ( $this->mAuto
) {
1464 $msg = 'autoblockedtext';
1465 } elseif ( !$this->isSitewide() ) {
1466 $msg = 'blockedtext-partial';
1469 array_unshift( $params, $msg );
1477 * Getting the restrictions will perform a database query if the restrictions
1478 * are not already loaded.
1481 * @return Restriction[]
1483 public function getRestrictions() {
1484 if ( $this->restrictions
=== null ) {
1485 // If the block id has not been set, then do not attempt to load the
1487 if ( !$this->mId
) {
1490 $this->restrictions
= $this->getBlockRestrictionStore()->loadByBlockId( $this->mId
);
1493 return $this->restrictions
;
1500 * @param Restriction[] $restrictions
1503 public function setRestrictions( array $restrictions ) {
1504 $this->restrictions
= array_filter( $restrictions, function ( $restriction ) {
1505 return $restriction instanceof Restriction
;
1514 public function appliesToTitle( Title
$title ) {
1515 if ( $this->isSitewide() ) {
1519 $restrictions = $this->getRestrictions();
1520 foreach ( $restrictions as $restriction ) {
1521 if ( $restriction->matches( $title ) ) {
1532 public function appliesToNamespace( $ns ) {
1533 if ( $this->isSitewide() ) {
1537 // Blocks do not apply to virtual namespaces.
1542 $restriction = $this->findRestriction( NamespaceRestriction
::TYPE
, $ns );
1544 return (bool)$restriction;
1550 public function appliesToPage( $pageId ) {
1551 if ( $this->isSitewide() ) {
1555 // If the pageId is not over zero, the block cannot apply to it.
1556 if ( $pageId <= 0 ) {
1560 $restriction = $this->findRestriction( PageRestriction
::TYPE
, $pageId );
1562 return (bool)$restriction;
1566 * Find Restriction by type and value.
1568 * @param string $type
1570 * @return Restriction|null
1572 private function findRestriction( $type, $value ) {
1573 $restrictions = $this->getRestrictions();
1574 foreach ( $restrictions as $restriction ) {
1575 if ( $restriction->getType() !== $type ) {
1579 if ( $restriction->getValue() === $value ) {
1580 return $restriction;
1588 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead of calling this
1592 public function shouldTrackWithCookie( $isAnon ) {
1593 wfDeprecated( __METHOD__
, '1.34' );
1594 $config = RequestContext
::getMain()->getConfig();
1595 switch ( $this->getType() ) {
1597 case self
::TYPE_RANGE
:
1598 return $isAnon && $config->get( 'CookieSetOnIpBlock' );
1599 case self
::TYPE_USER
:
1600 return !$isAnon && $config->get( 'CookieSetOnAutoblock' ) && $this->isAutoblocking();
1607 * Get a BlockRestrictionStore instance
1609 * @return BlockRestrictionStore
1611 private function getBlockRestrictionStore() : BlockRestrictionStore
{
1612 return MediaWikiServices
::getInstance()->getBlockRestrictionStore();
1617 * @deprecated since 1.34
1619 class_alias( DatabaseBlock
::class, 'Block' );