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
;
33 use MediaWiki\Block\Restriction\NamespaceRestriction
;
34 use MediaWiki\Block\Restriction\PageRestriction
;
35 use MediaWiki\Block\Restriction\Restriction
;
36 use MediaWiki\MediaWikiServices
;
43 use Wikimedia\Rdbms\Database
;
44 use Wikimedia\Rdbms\IDatabase
;
47 * A DatabaseBlock (unlike a SystemBlock) is stored in the database, may
48 * give rise to autoblocks and may be tracked with cookies. Such blocks
49 * are more customizable than system blocks: they may be hardblocks, and
50 * they may be sitewide or partial.
52 * @since 1.34 Renamed from Block.
54 class DatabaseBlock
extends AbstractBlock
{
56 * @deprecated since 1.34. Use getType to check whether a block is autoblocking.
62 * @deprecated since 1.34. Use getParentBlockId instead.
65 public $mParentBlockId;
73 /** @var int Hack for foreign blocking (CentralAuth) */
74 private $forcedTargetID;
80 private $isAutoblocking;
82 /** @var Restriction[] */
83 private $restrictions;
86 * Create a new block with specified option parameters on a user, IP or IP range.
88 * @param array $options Parameters of the block, with options supported by
89 * `AbstractBlock::__construct`, and also:
90 * - user: (int) Override target user ID (for foreign users)
91 * - auto: (bool) Is this an automatic block?
92 * - expiry: (string) Timestamp of expiration of the block or 'infinity'
93 * - anonOnly: (bool) Only disallow anonymous actions
94 * - createAccount: (bool) Disallow creation of new accounts
95 * - enableAutoblock: (bool) Enable automatic blocking
96 * - blockEmail: (bool) Disallow sending emails
97 * - allowUsertalk: (bool) Allow the target to edit its own talk page
98 * - sitewide: (bool) Disallow editing all pages and all contribution actions,
99 * except those specifically allowed by other block flags
101 * @since 1.26 $options array
103 public function __construct( array $options = [] ) {
104 parent
::__construct( $options );
111 'createAccount' => false,
112 'enableAutoblock' => false,
113 'blockEmail' => false,
114 'allowUsertalk' => false,
118 $options +
= $defaults;
120 if ( $this->target
instanceof User
&& $options['user'] ) {
121 # Needed for foreign users
122 $this->forcedTargetID
= $options['user'];
125 $this->setExpiry( wfGetDB( DB_REPLICA
)->decodeExpiry( $options['expiry'] ) );
128 $this->mAuto
= (bool)$options['auto'];
129 $this->isHardblock( !$options['anonOnly'] );
130 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
131 $this->isSitewide( (bool)$options['sitewide'] );
132 $this->isEmailBlocked( (bool)$options['blockEmail'] );
133 $this->isCreateAccountBlocked( (bool)$options['createAccount'] );
134 $this->isUsertalkEditAllowed( (bool)$options['allowUsertalk'] );
136 $this->mFromMaster
= false;
140 * Load a block from the block id.
142 * @param int $id id to search for
143 * @return DatabaseBlock|null
145 public static function newFromID( $id ) {
146 $dbr = wfGetDB( DB_REPLICA
);
147 $blockQuery = self
::getQueryInfo();
148 $res = $dbr->selectRow(
149 $blockQuery['tables'],
150 $blockQuery['fields'],
157 return self
::newFromRow( $res );
164 * Return the tables, fields, and join conditions to be selected to create
165 * a new block object.
167 * @return array With three keys:
168 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
169 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
170 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
172 public static function getQueryInfo() {
173 $commentQuery = CommentStore
::getStore()->getJoin( 'ipb_reason' );
174 $actorQuery = ActorMigration
::newMigration()->getJoin( 'ipb_by' );
176 'tables' => [ 'ipblocks' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
183 'ipb_create_account',
184 'ipb_enable_autoblock',
188 'ipb_allow_usertalk',
189 'ipb_parent_block_id',
191 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
192 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
197 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
198 * the blocking user or the block timestamp, only things which affect the blocked user
200 * @param DatabaseBlock $block
203 public function equals( DatabaseBlock
$block ) {
205 (string)$this->target
== (string)$block->target
206 && $this->type
== $block->type
207 && $this->mAuto
== $block->mAuto
208 && $this->isHardblock() == $block->isHardblock()
209 && $this->isCreateAccountBlocked() == $block->isCreateAccountBlocked()
210 && $this->getExpiry() == $block->getExpiry()
211 && $this->isAutoblocking() == $block->isAutoblocking()
212 && $this->getHideName() == $block->getHideName()
213 && $this->isEmailBlocked() == $block->isEmailBlocked()
214 && $this->isUsertalkEditAllowed() == $block->isUsertalkEditAllowed()
215 && $this->getReason() == $block->getReason()
216 && $this->isSitewide() == $block->isSitewide()
217 // DatabaseBlock::getRestrictions() may perform a database query, so
218 // keep it at the end.
219 && $this->getBlockRestrictionStore()->equals(
220 $this->getRestrictions(), $block->getRestrictions()
226 * Load blocks from the database which target the specific target exactly, or which cover the
229 * @param User|string|null $specificTarget
230 * @param int|null $specificType
231 * @param bool $fromMaster
232 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
233 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
234 * @throws MWException
235 * @return DatabaseBlock[] Any relevant blocks
237 protected static function newLoad(
243 $db = wfGetDB( $fromMaster ? DB_MASTER
: DB_REPLICA
);
245 if ( $specificType !== null ) {
247 'ipb_address' => [ (string)$specificTarget ],
250 $conds = [ 'ipb_address' => [] ];
253 # Be aware that the != '' check is explicit, since empty values will be
254 # passed by some callers (T31116)
255 if ( $vagueTarget != '' ) {
256 list( $target, $type ) = self
::parseTarget( $vagueTarget );
258 case self
::TYPE_USER
:
259 # Slightly weird, but who are we to argue?
260 $conds['ipb_address'][] = (string)$target;
264 $conds['ipb_address'][] = (string)$target;
265 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
266 $conds = $db->makeList( $conds, LIST_OR
);
269 case self
::TYPE_RANGE
:
270 list( $start, $end ) = IP
::parseRange( $target );
271 $conds['ipb_address'][] = (string)$target;
272 $conds[] = self
::getRangeCond( $start, $end );
273 $conds = $db->makeList( $conds, LIST_OR
);
277 throw new MWException( "Tried to load block with invalid type" );
281 $blockQuery = self
::getQueryInfo();
283 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
289 foreach ( $res as $row ) {
290 $block = self
::newFromRow( $row );
292 # Don't use expired blocks
293 if ( $block->isExpired() ) {
297 # Don't use anon only blocks on users
298 if ( $specificType == self
::TYPE_USER
&& !$block->isHardblock() ) {
302 // Check for duplicate autoblocks
303 if ( $block->getType() === self
::TYPE_AUTO
) {
304 $autoBlocks[] = $block;
307 $blockIds[] = $block->getId();
311 // Only add autoblocks that aren't duplicates
312 foreach ( $autoBlocks as $block ) {
313 if ( !in_array( $block->mParentBlockId
, $blockIds ) ) {
322 * Choose the most specific block from some combination of user, IP and IP range
323 * blocks. Decreasing order of specificity: user > IP > narrower IP range > wider IP
324 * range. A range that encompasses one IP address is ranked equally to a singe IP.
326 * Note that DatabaseBlock::chooseBlocks chooses blocks in a different way.
328 * This is refactored out from DatabaseBlock::newLoad.
330 * @param DatabaseBlock[] $blocks These should not include autoblocks or ID blocks
331 * @return DatabaseBlock|null The block with the most specific target
333 protected static function chooseMostSpecificBlock( array $blocks ) {
334 if ( count( $blocks ) === 1 ) {
338 # This result could contain a block on the user, a block on the IP, and a russian-doll
339 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
342 # Lower will be better
343 $bestBlockScore = 100;
344 foreach ( $blocks as $block ) {
345 if ( $block->getType() == self
::TYPE_RANGE
) {
346 # This is the number of bits that are allowed to vary in the block, give
347 # or take some floating point errors
348 $target = $block->getTarget();
349 $max = IP
::isIPv6( $target ) ?
128 : 32;
350 list( $network, $bits ) = IP
::parseCIDR( $target );
351 $size = $max - $bits;
353 # Rank a range block covering a single IP equally with a single-IP block
354 $score = self
::TYPE_RANGE
- 1 +
( $size / $max );
357 $score = $block->getType();
360 if ( $score < $bestBlockScore ) {
361 $bestBlockScore = $score;
370 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
371 * @param string $start Hexadecimal IP representation
372 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
375 public static function getRangeCond( $start, $end = null ) {
376 if ( $end === null ) {
379 # Per T16634, we want to include relevant active rangeblocks; for
380 # rangeblocks, we want to include larger ranges which enclose the given
381 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
382 # so we can improve performance by filtering on a LIKE clause
383 $chunk = self
::getIpFragment( $start );
384 $dbr = wfGetDB( DB_REPLICA
);
385 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
387 # Fairly hard to make a malicious SQL statement out of hex characters,
388 # but stranger things have happened...
389 $safeStart = $dbr->addQuotes( $start );
390 $safeEnd = $dbr->addQuotes( $end );
392 return $dbr->makeList(
394 "ipb_range_start $like",
395 "ipb_range_start <= $safeStart",
396 "ipb_range_end >= $safeEnd",
403 * Get the component of an IP address which is certain to be the same between an IP
404 * address and a rangeblock containing that IP address.
405 * @param string $hex Hexadecimal IP representation
408 protected static function getIpFragment( $hex ) {
409 global $wgBlockCIDRLimit;
410 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
411 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
413 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
418 * Given a database row from the ipblocks table, initialize
420 * @param stdClass $row A row from the ipblocks table
422 protected function initFromRow( $row ) {
423 $this->setTarget( $row->ipb_address
);
424 $this->setBlocker( User
::newFromAnyId(
425 $row->ipb_by
, $row->ipb_by_text
, $row->ipb_by_actor ??
null
428 $this->setTimestamp( wfTimestamp( TS_MW
, $row->ipb_timestamp
) );
429 $this->mAuto
= $row->ipb_auto
;
430 $this->setHideName( $row->ipb_deleted
);
431 $this->mId
= (int)$row->ipb_id
;
432 $this->mParentBlockId
= $row->ipb_parent_block_id
;
434 // I wish I didn't have to do this
435 $db = wfGetDB( DB_REPLICA
);
436 $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry
) );
438 CommentStore
::getStore()
439 // Legacy because $row may have come from self::selectFields()
440 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
443 $this->isHardblock( !$row->ipb_anon_only
);
444 $this->isAutoblocking( $row->ipb_enable_autoblock
);
445 $this->isSitewide( (bool)$row->ipb_sitewide
);
447 $this->isCreateAccountBlocked( $row->ipb_create_account
);
448 $this->isEmailBlocked( $row->ipb_block_email
);
449 $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk
);
453 * Create a new DatabaseBlock object from a database row
454 * @param stdClass $row Row from the ipblocks table
455 * @return DatabaseBlock
457 public static function newFromRow( $row ) {
458 $block = new DatabaseBlock
;
459 $block->initFromRow( $row );
464 * Delete the row from the IP blocks table.
466 * @throws MWException
469 public function delete() {
470 if ( wfReadOnly() ) {
474 if ( !$this->getId() ) {
475 throw new MWException(
476 __METHOD__
. " requires that the mId member be filled\n"
480 $dbw = wfGetDB( DB_MASTER
);
482 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
483 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
485 $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
486 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
488 return $dbw->affectedRows() > 0;
492 * Insert a block into the block table. Will fail if there is a conflicting
493 * block (same name and options) already in the database.
495 * @param IDatabase|null $dbw If you have one available
496 * @return bool|array False on failure, assoc array on success:
497 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
499 public function insert( IDatabase
$dbw = null ) {
500 global $wgBlockDisablesLogin;
502 if ( !$this->getBlocker() ||
$this->getBlocker()->getName() === '' ) {
503 throw new MWException( 'Cannot insert a block without a blocker set' );
506 wfDebug( __METHOD__
. "; timestamp {$this->mTimestamp}\n" );
508 if ( $dbw === null ) {
509 $dbw = wfGetDB( DB_MASTER
);
512 self
::purgeExpired();
514 $row = $this->getDatabaseArray( $dbw );
516 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
517 $affected = $dbw->affectedRows();
519 $this->setId( $dbw->insertId() );
520 if ( $this->restrictions
) {
521 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
525 # Don't collide with expired blocks.
526 # Do this after trying to insert to avoid locking.
528 # T96428: The ipb_address index uses a prefix on a field, so
529 # use a standard SELECT + DELETE to avoid annoying gap locks.
530 $ids = $dbw->selectFieldValues( 'ipblocks',
533 'ipb_address' => $row['ipb_address'],
534 'ipb_user' => $row['ipb_user'],
535 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
540 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
541 $this->getBlockRestrictionStore()->deleteByBlockId( $ids );
542 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
543 $affected = $dbw->affectedRows();
544 $this->setId( $dbw->insertId() );
545 if ( $this->restrictions
) {
546 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
552 $auto_ipd_ids = $this->doRetroactiveAutoblock();
554 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
555 // Change user login token to force them to be logged out.
556 $this->target
->setToken();
557 $this->target
->saveSettings();
560 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
567 * Update a block in the DB with new parameters.
568 * The ID field needs to be loaded first.
570 * @return bool|array False on failure, array on success:
571 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
573 public function update() {
574 wfDebug( __METHOD__
. "; timestamp {$this->mTimestamp}\n" );
575 $dbw = wfGetDB( DB_MASTER
);
577 $dbw->startAtomic( __METHOD__
);
579 $result = $dbw->update(
581 $this->getDatabaseArray( $dbw ),
582 [ 'ipb_id' => $this->getId() ],
586 // Only update the restrictions if they have been modified.
587 if ( $this->restrictions
!== null ) {
588 // An empty array should remove all of the restrictions.
589 if ( empty( $this->restrictions
) ) {
590 $success = $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
592 $success = $this->getBlockRestrictionStore()->update( $this->restrictions
);
594 // Update the result. The first false is the result, otherwise, true.
595 $result = $result && $success;
598 if ( $this->isAutoblocking() ) {
599 // update corresponding autoblock(s) (T50813)
602 $this->getAutoblockUpdateArray( $dbw ),
603 [ 'ipb_parent_block_id' => $this->getId() ],
607 // Only update the restrictions if they have been modified.
608 if ( $this->restrictions
!== null ) {
609 $this->getBlockRestrictionStore()->updateByParentBlockId( $this->getId(), $this->restrictions
);
612 // autoblock no longer required, delete corresponding autoblock(s)
613 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
616 [ 'ipb_parent_block_id' => $this->getId() ],
621 $dbw->endAtomic( __METHOD__
);
624 $auto_ipd_ids = $this->doRetroactiveAutoblock();
625 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
632 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
633 * @param IDatabase $dbw
636 protected function getDatabaseArray( IDatabase
$dbw ) {
637 $expiry = $dbw->encodeExpiry( $this->getExpiry() );
639 if ( $this->forcedTargetID
) {
640 $uid = $this->forcedTargetID
;
642 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
646 'ipb_address' => (string)$this->target
,
648 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
649 'ipb_auto' => $this->mAuto
,
650 'ipb_anon_only' => !$this->isHardblock(),
651 'ipb_create_account' => $this->isCreateAccountBlocked(),
652 'ipb_enable_autoblock' => $this->isAutoblocking(),
653 'ipb_expiry' => $expiry,
654 'ipb_range_start' => $this->getRangeStart(),
655 'ipb_range_end' => $this->getRangeEnd(),
656 'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
657 'ipb_block_email' => $this->isEmailBlocked(),
658 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
659 'ipb_parent_block_id' => $this->mParentBlockId
,
660 'ipb_sitewide' => $this->isSitewide(),
661 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
662 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
668 * @param IDatabase $dbw
671 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
673 'ipb_create_account' => $this->isCreateAccountBlocked(),
674 'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
675 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
676 'ipb_sitewide' => $this->isSitewide(),
677 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
678 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
682 * Retroactively autoblocks the last IP used by the user (if it is a user)
683 * blocked by this block.
685 * @return array IDs of retroactive autoblocks made
687 protected function doRetroactiveAutoblock() {
689 # If autoblock is enabled, autoblock the LAST IP(s) used
690 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
691 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
693 $continue = Hooks
::run(
694 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
697 self
::defaultRetroactiveAutoblock( $this, $blockIds );
704 * Retroactively autoblocks the last IP used by the user (if it is a user)
705 * blocked by this block. This will use the recentchanges table.
707 * @param DatabaseBlock $block
708 * @param array &$blockIds
710 protected static function defaultRetroactiveAutoblock( DatabaseBlock
$block, array &$blockIds ) {
713 // No IPs are in recentchanges table, so nothing to select
714 if ( !$wgPutIPinRC ) {
718 // Autoblocks only apply to TYPE_USER
719 if ( $block->getType() !== self
::TYPE_USER
) {
722 $target = $block->getTarget(); // TYPE_USER => always a User object
724 $dbr = wfGetDB( DB_REPLICA
);
725 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
727 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
729 // Just the last IP used.
730 $options['LIMIT'] = 1;
733 [ 'recentchanges' ] +
$rcQuery['tables'],
741 if ( !$res->numRows() ) {
742 # No results, don't autoblock anything
743 wfDebug( "No IP found to retroactively autoblock\n" );
745 foreach ( $res as $row ) {
747 $id = $block->doAutoblock( $row->rc_ip
);
757 * Checks whether a given IP is on the autoblock whitelist.
758 * TODO: this probably belongs somewhere else, but not sure where...
760 * @param string $ip The IP to check
763 public static function isWhitelistedFromAutoblocks( $ip ) {
764 // Try to get the autoblock_whitelist from the cache, as it's faster
765 // than getting the msg raw and explode()'ing it.
766 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
767 $lines = $cache->getWithSetCallback(
768 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
770 function ( $curValue, &$ttl, array &$setOpts ) {
771 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
773 return explode( "\n",
774 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
778 wfDebug( "Checking the autoblock whitelist..\n" );
780 foreach ( $lines as $line ) {
782 if ( substr( $line, 0, 1 ) !== '*' ) {
786 $wlEntry = substr( $line, 1 );
787 $wlEntry = trim( $wlEntry );
789 wfDebug( "Checking $ip against $wlEntry..." );
791 # Is the IP in this range?
792 if ( IP
::isInRange( $ip, $wlEntry ) ) {
793 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
796 wfDebug( " No match\n" );
804 * Autoblocks the given IP, referring to this block.
806 * @param string $autoblockIP The IP to autoblock.
807 * @return int|bool ID if an autoblock was inserted, false if not.
809 public function doAutoblock( $autoblockIP ) {
810 # If autoblocks are disabled, go away.
811 if ( !$this->isAutoblocking() ) {
815 # Check for presence on the autoblock whitelist.
816 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
820 // Avoid PHP 7.1 warning of passing $this by reference
822 # Allow hooks to cancel the autoblock.
823 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
824 wfDebug( "Autoblock aborted by hook.\n" );
828 # It's okay to autoblock. Go ahead and insert/update the block...
830 # Do not add a *new* block if the IP is already blocked.
831 $ipblock = self
::newFromTarget( $autoblockIP );
833 # Check if the block is an autoblock and would exceed the user block
834 # if renewed. If so, do nothing, otherwise prolong the block time...
835 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
836 $this->getExpiry() > self
::getAutoblockExpiry( $ipblock->getTimestamp() )
838 # Reset block timestamp to now and its expiry to
839 # $wgAutoblockExpiry in the future
840 $ipblock->updateTimestamp();
845 # Make a new block object with the desired properties.
846 $autoblock = new DatabaseBlock
;
847 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
848 $autoblock->setTarget( $autoblockIP );
849 $autoblock->setBlocker( $this->getBlocker() );
850 $autoblock->setReason(
851 wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
852 ->inContentLanguage()->plain()
854 $timestamp = wfTimestampNow();
855 $autoblock->setTimestamp( $timestamp );
856 $autoblock->mAuto
= 1;
857 $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
858 # Continue suppressing the name if needed
859 $autoblock->setHideName( $this->getHideName() );
860 $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
861 $autoblock->mParentBlockId
= $this->mId
;
862 $autoblock->isSitewide( $this->isSitewide() );
863 $autoblock->setRestrictions( $this->getRestrictions() );
865 if ( $this->getExpiry() == 'infinity' ) {
866 # Original block was indefinite, start an autoblock now
867 $autoblock->setExpiry( self
::getAutoblockExpiry( $timestamp ) );
869 # If the user is already blocked with an expiry date, we don't
870 # want to pile on top of that.
871 $autoblock->setExpiry( min( $this->getExpiry(), self
::getAutoblockExpiry( $timestamp ) ) );
874 # Insert the block...
875 $status = $autoblock->insert();
882 * Check if a block has expired. Delete it if it is.
885 public function deleteIfExpired() {
886 if ( $this->isExpired() ) {
887 wfDebug( __METHOD__
. " -- deleting\n" );
891 wfDebug( __METHOD__
. " -- not expired\n" );
899 * Has the block expired?
902 public function isExpired() {
903 $timestamp = wfTimestampNow();
904 wfDebug( __METHOD__
. " checking current " . $timestamp . " vs $this->mExpiry\n" );
906 if ( !$this->getExpiry() ) {
909 return $timestamp > $this->getExpiry();
914 * Is the block address valid (i.e. not a null string?)
916 * @deprecated since 1.33 No longer needed in core.
919 public function isValid() {
920 wfDeprecated( __METHOD__
, '1.33' );
921 return $this->getTarget() != null;
925 * Update the timestamp on autoblocks.
927 public function updateTimestamp() {
928 if ( $this->mAuto
) {
929 $this->setTimestamp( wfTimestamp() );
930 $this->setExpiry( self
::getAutoblockExpiry( $this->getTimestamp() ) );
932 $dbw = wfGetDB( DB_MASTER
);
933 $dbw->update( 'ipblocks',
935 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
936 'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
939 'ipb_id' => $this->getId(),
947 * Get the IP address at the start of the range in Hex form
948 * @throws MWException
949 * @return string IP in Hex form
951 public function getRangeStart() {
952 switch ( $this->type
) {
953 case self
::TYPE_USER
:
956 return IP
::toHex( $this->target
);
957 case self
::TYPE_RANGE
:
958 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
961 throw new MWException( "Block with invalid type" );
966 * Get the IP address at the end of the range in Hex form
967 * @throws MWException
968 * @return string IP in Hex form
970 public function getRangeEnd() {
971 switch ( $this->type
) {
972 case self
::TYPE_USER
:
975 return IP
::toHex( $this->target
);
976 case self
::TYPE_RANGE
:
977 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
980 throw new MWException( "Block with invalid type" );
987 public function getId() {
994 * @param int $blockId
997 private function setId( $blockId ) {
998 $this->mId
= (int)$blockId;
1000 if ( is_array( $this->restrictions
) ) {
1001 $this->restrictions
= $this->getBlockRestrictionStore()->setBlockId(
1002 $blockId, $this->restrictions
1011 * @return int|null If this is an autoblock, ID of the parent block; otherwise null
1013 public function getParentBlockId() {
1014 return $this->mParentBlockId
;
1018 * Get/set a flag determining whether the master is used for reads
1020 * @param bool|null $x
1023 public function fromMaster( $x = null ) {
1024 return wfSetVar( $this->mFromMaster
, $x );
1028 * Get/set whether the block is a hardblock (affects logged-in users on a given IP/range)
1029 * @param bool|null $x
1032 public function isHardblock( $x = null ) {
1033 wfSetVar( $this->isHardblock
, $x );
1035 # You can't *not* hardblock a user
1036 return $this->getType() == self
::TYPE_USER
1038 : $this->isHardblock
;
1042 * @param null|bool $x
1045 public function isAutoblocking( $x = null ) {
1046 wfSetVar( $this->isAutoblocking
, $x );
1048 # You can't put an autoblock on an IP or range as we don't have any history to
1049 # look over to get more IPs from
1050 return $this->getType() == self
::TYPE_USER
1051 ?
$this->isAutoblocking
1056 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1057 * @return string Text is escaped
1059 public function getRedactedName() {
1060 if ( $this->mAuto
) {
1061 return Html
::element(
1063 [ 'class' => 'mw-autoblockid' ],
1064 wfMessage( 'autoblockid', $this->mId
)->text()
1067 return htmlspecialchars( $this->getTarget() );
1072 * Get a timestamp of the expiry for autoblocks
1074 * @param string|int $timestamp
1077 public static function getAutoblockExpiry( $timestamp ) {
1078 global $wgAutoblockExpiry;
1080 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1084 * Purge expired blocks from the ipblocks table
1086 public static function purgeExpired() {
1087 if ( wfReadOnly() ) {
1091 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1092 wfGetDB( DB_MASTER
),
1094 function ( IDatabase
$dbw, $fname ) {
1095 $ids = $dbw->selectFieldValues( 'ipblocks',
1097 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1101 $blockRestrictionStore = MediaWikiServices
::getInstance()->getBlockRestrictionStore();
1102 $blockRestrictionStore->deleteByBlockId( $ids );
1104 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1111 * Given a target and the target's type, get an existing block object if possible.
1112 * @param string|User|int $specificTarget A block target, which may be one of several types:
1113 * * A user to block, in which case $target will be a User
1114 * * An IP to block, in which case $target will be a User generated by using
1115 * User::newFromName( $ip, false ) to turn off name validation
1116 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1117 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1119 * Calling this with a user, IP address or range will not select autoblocks, and will
1120 * only select a block where the targets match exactly (so looking for blocks on
1121 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1122 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1123 * affects that target (so for an IP address, get ranges containing that IP; and also
1124 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1125 * @param bool $fromMaster Whether to use the DB_MASTER database
1126 * @return DatabaseBlock|null (null if no relevant block could be found). The target and type
1127 * of the returned block will refer to the actual block which was found, which might
1128 * not be the same as the target you gave if you used $vagueTarget!
1130 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1131 $blocks = self
::newListFromTarget( $specificTarget, $vagueTarget, $fromMaster );
1132 return self
::chooseMostSpecificBlock( $blocks );
1136 * This is similar to DatabaseBlock::newFromTarget, but it returns all the relevant blocks.
1139 * @param string|User|int|null $specificTarget
1140 * @param string|User|int|null $vagueTarget
1141 * @param bool $fromMaster
1142 * @return DatabaseBlock[] Any relevant blocks
1144 public static function newListFromTarget(
1146 $vagueTarget = null,
1149 list( $target, $type ) = self
::parseTarget( $specificTarget );
1150 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1151 $block = self
::newFromID( $target );
1152 return $block ?
[ $block ] : [];
1153 } elseif ( $target === null && $vagueTarget == '' ) {
1154 # We're not going to find anything useful here
1155 # Be aware that the == '' check is explicit, since empty values will be
1156 # passed by some callers (T31116)
1158 } elseif ( in_array(
1160 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1162 return self
::newLoad( $target, $type, $fromMaster, $vagueTarget );
1168 * Get all blocks that match any IP from an array of IP addresses
1170 * @param array $ipChain List of IPs (strings), usually retrieved from the
1171 * X-Forwarded-For header of the request
1172 * @param bool $isAnon Exclude anonymous-only blocks if false
1173 * @param bool $fromMaster Whether to query the master or replica DB
1174 * @return array Array of Blocks
1177 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1178 if ( $ipChain === [] ) {
1183 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1184 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1185 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1186 # necessarily trust the header given to us, make sure that we are only
1187 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1188 # Do not treat private IP spaces as special as it may be desirable for wikis
1189 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1190 if ( !IP
::isValid( $ipaddr ) ) {
1193 # Don't check trusted IPs (includes local CDNs which will be in every request)
1194 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1197 # Check both the original IP (to check against single blocks), as well as build
1198 # the clause to check for rangeblocks for the given IP.
1199 $conds['ipb_address'][] = $ipaddr;
1200 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1203 if ( $conds === [] ) {
1207 if ( $fromMaster ) {
1208 $db = wfGetDB( DB_MASTER
);
1210 $db = wfGetDB( DB_REPLICA
);
1212 $conds = $db->makeList( $conds, LIST_OR
);
1214 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1216 $blockQuery = self
::getQueryInfo();
1217 $rows = $db->select(
1218 $blockQuery['tables'],
1219 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1223 $blockQuery['joins']
1227 foreach ( $rows as $row ) {
1228 $block = self
::newFromRow( $row );
1229 if ( !$block->isExpired() ) {
1238 * From a list of multiple blocks, find the most exact and strongest block.
1240 * The logic for finding the "best" block is:
1241 * - Blocks that match the block's target IP are preferred over ones in a range
1242 * - Hardblocks are chosen over softblocks that prevent account creation
1243 * - Softblocks that prevent account creation are chosen over other softblocks
1244 * - Other softblocks are chosen over autoblocks
1245 * - If there are multiple exact or range blocks at the same level, the one chosen
1247 * This should be used when $blocks were retrieved from the user's IP address
1248 * and $ipChain is populated from the same IP address information.
1250 * @param array $blocks Array of DatabaseBlock objects
1251 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1252 * a block is to the server, and if a block matches exactly, or is in a range.
1253 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1255 * @throws MWException
1256 * @return DatabaseBlock|null The "best" block from the list
1258 public static function chooseBlock( array $blocks, array $ipChain ) {
1259 if ( $blocks === [] ) {
1261 } elseif ( count( $blocks ) == 1 ) {
1265 // Sort hard blocks before soft ones and secondarily sort blocks
1266 // that disable account creation before those that don't.
1267 usort( $blocks, function ( DatabaseBlock
$a, DatabaseBlock
$b ) {
1268 $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1269 $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1270 return strcmp( $bWeight, $aWeight ); // highest weight first
1273 $blocksListExact = [
1275 'disable_create' => false,
1279 $blocksListRange = [
1281 'disable_create' => false,
1285 $ipChain = array_reverse( $ipChain );
1287 foreach ( $blocks as $block ) {
1288 // Stop searching if we have already have a "better" block. This
1289 // is why the order of the blocks matters
1290 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1292 } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1296 foreach ( $ipChain as $checkip ) {
1297 $checkipHex = IP
::toHex( $checkip );
1298 if ( (string)$block->getTarget() === $checkip ) {
1299 if ( $block->isHardblock() ) {
1300 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1301 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1302 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1303 } elseif ( $block->mAuto
) {
1304 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1306 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1308 // We found closest exact match in the ip list, so go to the next block
1310 } elseif ( array_filter( $blocksListExact ) == []
1311 && $block->getRangeStart() <= $checkipHex
1312 && $block->getRangeEnd() >= $checkipHex
1314 if ( $block->isHardblock() ) {
1315 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1316 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1317 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1318 } elseif ( $block->mAuto
) {
1319 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1321 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1328 if ( array_filter( $blocksListExact ) == [] ) {
1329 $blocksList = &$blocksListRange;
1331 $blocksList = &$blocksListExact;
1334 $chosenBlock = null;
1335 if ( $blocksList['hard'] ) {
1336 $chosenBlock = $blocksList['hard'];
1337 } elseif ( $blocksList['disable_create'] ) {
1338 $chosenBlock = $blocksList['disable_create'];
1339 } elseif ( $blocksList['other'] ) {
1340 $chosenBlock = $blocksList['other'];
1341 } elseif ( $blocksList['auto'] ) {
1342 $chosenBlock = $blocksList['auto'];
1344 throw new MWException( "Proxy block found, but couldn't be classified." );
1347 return $chosenBlock;
1353 * Autoblocks have whichever type corresponds to their target, so to detect if a block is an
1354 * autoblock, we have to check the mAuto property instead.
1356 public function getType() {
1359 : parent
::getType();
1363 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1364 * the same as the block's, to a maximum of 24 hours.
1367 * @deprecated since 1.34 Set a cookie via BlockManager::trackBlockWithCookie instead.
1368 * @param WebResponse $response The response on which to set the cookie.
1370 public function setCookie( WebResponse
$response ) {
1371 MediaWikiServices
::getInstance()->getBlockManager()->setBlockCookie( $this, $response );
1375 * Unset the 'BlockID' cookie.
1378 * @deprecated since 1.34 Use BlockManager::clearBlockCookie instead
1379 * @param WebResponse $response The response on which to unset the cookie.
1381 public static function clearCookie( WebResponse
$response ) {
1382 MediaWikiServices
::getInstance()->getBlockManager()->clearBlockCookie( $response );
1386 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1387 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1391 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead of calling this
1393 * @return string The block ID, probably concatenated with "!" and the HMAC.
1395 public function getCookieValue() {
1396 return MediaWikiServices
::getInstance()->getBlockManager()->getCookieValue( $this );
1400 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1401 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
1404 * @deprecated since 1.34 Use BlockManager::getUserBlock instead
1405 * @param string $cookieValue The string in which to find the ID.
1406 * @return int|null The block ID, or null if the HMAC is present and invalid.
1408 public static function getIdFromCookieValue( $cookieValue ) {
1409 return MediaWikiServices
::getInstance()->getBlockManager()->getIdFromCookieValue( $cookieValue );
1415 * Build different messages for autoblocks and partial blocks.
1417 public function getPermissionsError( IContextSource
$context ) {
1418 $params = $this->getBlockErrorParams( $context );
1420 $msg = 'blockedtext';
1421 if ( $this->mAuto
) {
1422 $msg = 'autoblockedtext';
1423 } elseif ( !$this->isSitewide() ) {
1424 $msg = 'blockedtext-partial';
1427 array_unshift( $params, $msg );
1435 * Getting the restrictions will perform a database query if the restrictions
1436 * are not already loaded.
1439 * @return Restriction[]
1441 public function getRestrictions() {
1442 if ( $this->restrictions
=== null ) {
1443 // If the block id has not been set, then do not attempt to load the
1445 if ( !$this->mId
) {
1448 $this->restrictions
= $this->getBlockRestrictionStore()->loadByBlockId( $this->mId
);
1451 return $this->restrictions
;
1458 * @param Restriction[] $restrictions
1461 public function setRestrictions( array $restrictions ) {
1462 $this->restrictions
= array_filter( $restrictions, function ( $restriction ) {
1463 return $restriction instanceof Restriction
;
1472 public function appliesToTitle( Title
$title ) {
1473 if ( $this->isSitewide() ) {
1477 $restrictions = $this->getRestrictions();
1478 foreach ( $restrictions as $restriction ) {
1479 if ( $restriction->matches( $title ) ) {
1490 public function appliesToNamespace( $ns ) {
1491 if ( $this->isSitewide() ) {
1495 // Blocks do not apply to virtual namespaces.
1500 $restriction = $this->findRestriction( NamespaceRestriction
::TYPE
, $ns );
1502 return (bool)$restriction;
1508 public function appliesToPage( $pageId ) {
1509 if ( $this->isSitewide() ) {
1513 // If the pageId is not over zero, the block cannot apply to it.
1514 if ( $pageId <= 0 ) {
1518 $restriction = $this->findRestriction( PageRestriction
::TYPE
, $pageId );
1520 return (bool)$restriction;
1524 * Find Restriction by type and value.
1526 * @param string $type
1528 * @return Restriction|null
1530 private function findRestriction( $type, $value ) {
1531 $restrictions = $this->getRestrictions();
1532 foreach ( $restrictions as $restriction ) {
1533 if ( $restriction->getType() !== $type ) {
1537 if ( $restriction->getValue() === $value ) {
1538 return $restriction;
1546 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead of calling this
1550 public function shouldTrackWithCookie( $isAnon ) {
1551 wfDeprecated( __METHOD__
, '1.34' );
1552 $config = RequestContext
::getMain()->getConfig();
1553 switch ( $this->getType() ) {
1555 case self
::TYPE_RANGE
:
1556 return $isAnon && $config->get( 'CookieSetOnIpBlock' );
1557 case self
::TYPE_USER
:
1558 return !$isAnon && $config->get( 'CookieSetOnAutoblock' ) && $this->isAutoblocking();
1565 * Get a BlockRestrictionStore instance
1567 * @return BlockRestrictionStore
1569 private function getBlockRestrictionStore() : BlockRestrictionStore
{
1570 return MediaWikiServices
::getInstance()->getBlockRestrictionStore();
1575 * @deprecated since 1.34
1577 class_alias( DatabaseBlock
::class, 'Block' );