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 use Wikimedia\Rdbms\Database
;
24 use Wikimedia\Rdbms\IDatabase
;
25 use MediaWiki\Block\AbstractBlock
;
26 use MediaWiki\Block\BlockRestrictionStore
;
27 use MediaWiki\Block\Restriction\Restriction
;
28 use MediaWiki\Block\Restriction\NamespaceRestriction
;
29 use MediaWiki\Block\Restriction\PageRestriction
;
30 use MediaWiki\MediaWikiServices
;
33 * Blocks (as opposed to system blocks) are stored in the database, may
34 * give rise to autoblocks and may be tracked with cookies. Blocks are
35 * more customizable than system blocks: they may be hardblocks, and
36 * they may be sitewide or partial.
38 class Block
extends AbstractBlock
{
43 public $mParentBlockId;
51 /** @var int Hack for foreign blocking (CentralAuth) */
52 private $forcedTargetID;
58 private $isAutoblocking;
60 /** @var Restriction[] */
61 private $restrictions;
64 * Create a new block with specified option parameters on a user, IP or IP range.
66 * @param array $options Parameters of the block:
67 * user int Override target user ID (for foreign users)
68 * auto bool Is this an automatic block?
69 * expiry string Timestamp of expiration of the block or 'infinity'
70 * anonOnly bool Only disallow anonymous actions
71 * createAccount bool Disallow creation of new accounts
72 * enableAutoblock bool Enable automatic blocking
73 * hideName bool Hide the target user name
74 * blockEmail bool Disallow sending emails
75 * allowUsertalk bool Allow the target to edit its own talk page
76 * sitewide bool Disallow editing all pages and all contribution
77 * actions, except those specifically allowed by
80 * @since 1.26 $options array
82 public function __construct( array $options = [] ) {
83 parent
::__construct( $options );
90 'createAccount' => false,
91 'enableAutoblock' => false,
93 'blockEmail' => false,
94 'allowUsertalk' => false,
98 $options +
= $defaults;
100 if ( $this->target
instanceof User
&& $options['user'] ) {
101 # Needed for foreign users
102 $this->forcedTargetID
= $options['user'];
105 $this->setExpiry( wfGetDB( DB_REPLICA
)->decodeExpiry( $options['expiry'] ) );
108 $this->mAuto
= (bool)$options['auto'];
109 $this->setHideName( (bool)$options['hideName'] );
110 $this->isHardblock( !$options['anonOnly'] );
111 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
112 $this->isSitewide( (bool)$options['sitewide'] );
113 $this->isEmailBlocked( (bool)$options['blockEmail'] );
114 $this->isCreateAccountBlocked( (bool)$options['createAccount'] );
115 $this->isUsertalkEditAllowed( (bool)$options['allowUsertalk'] );
117 $this->mFromMaster
= false;
121 * Load a block from the block id.
123 * @param int $id Block id to search for
126 public static function newFromID( $id ) {
127 $dbr = wfGetDB( DB_REPLICA
);
128 $blockQuery = self
::getQueryInfo();
129 $res = $dbr->selectRow(
130 $blockQuery['tables'],
131 $blockQuery['fields'],
138 return self
::newFromRow( $res );
145 * Return the list of ipblocks fields that should be selected to create
147 * @deprecated since 1.31, use self::getQueryInfo() instead.
150 public static function selectFields() {
151 global $wgActorTableSchemaMigrationStage;
153 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
154 // If code is using this instead of self::getQueryInfo(), there's a
155 // decent chance it's going to try to directly access
156 // $row->ipb_by or $row->ipb_by_text and we can't give it
157 // useful values here once those aren't being used anymore.
158 throw new BadMethodCallException(
159 'Cannot use ' . __METHOD__
160 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
164 wfDeprecated( __METHOD__
, '1.31' );
170 'ipb_by_actor' => 'NULL',
174 'ipb_create_account',
175 'ipb_enable_autoblock',
179 'ipb_allow_usertalk',
180 'ipb_parent_block_id',
182 ] + CommentStore
::getStore()->getFields( 'ipb_reason' );
186 * Return the tables, fields, and join conditions to be selected to create
187 * a new block object.
189 * @return array With three keys:
190 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
191 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
192 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
194 public static function getQueryInfo() {
195 $commentQuery = CommentStore
::getStore()->getJoin( 'ipb_reason' );
196 $actorQuery = ActorMigration
::newMigration()->getJoin( 'ipb_by' );
198 'tables' => [ 'ipblocks' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
205 'ipb_create_account',
206 'ipb_enable_autoblock',
210 'ipb_allow_usertalk',
211 'ipb_parent_block_id',
213 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
214 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
219 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
220 * the blocking user or the block timestamp, only things which affect the blocked user
222 * @param Block $block
226 public function equals( Block
$block ) {
228 (string)$this->target
== (string)$block->target
229 && $this->type
== $block->type
230 && $this->mAuto
== $block->mAuto
231 && $this->isHardblock() == $block->isHardblock()
232 && $this->isCreateAccountBlocked() == $block->isCreateAccountBlocked()
233 && $this->getExpiry() == $block->getExpiry()
234 && $this->isAutoblocking() == $block->isAutoblocking()
235 && $this->getHideName() == $block->getHideName()
236 && $this->isEmailBlocked() == $block->isEmailBlocked()
237 && $this->isUsertalkEditAllowed() == $block->isUsertalkEditAllowed()
238 && $this->getReason() == $block->getReason()
239 && $this->isSitewide() == $block->isSitewide()
240 // Block::getRestrictions() may perform a database query, so keep it at
242 && $this->getBlockRestrictionStore()->equals(
243 $this->getRestrictions(), $block->getRestrictions()
249 * Load a block from the database which affects the already-set $this->target:
250 * 1) A block directly on the given user or IP
251 * 2) A rangeblock encompassing the given IP (smallest first)
252 * 3) An autoblock on the given IP
253 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
254 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
255 * @throws MWException
256 * @return bool Whether a relevant block was found
258 protected function newLoad( $vagueTarget = null ) {
259 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_REPLICA
);
261 if ( $this->type
!== null ) {
263 'ipb_address' => [ (string)$this->target
],
266 $conds = [ 'ipb_address' => [] ];
269 # Be aware that the != '' check is explicit, since empty values will be
270 # passed by some callers (T31116)
271 if ( $vagueTarget != '' ) {
272 list( $target, $type ) = self
::parseTarget( $vagueTarget );
274 case self
::TYPE_USER
:
275 # Slightly weird, but who are we to argue?
276 $conds['ipb_address'][] = (string)$target;
280 $conds['ipb_address'][] = (string)$target;
281 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
282 $conds = $db->makeList( $conds, LIST_OR
);
285 case self
::TYPE_RANGE
:
286 list( $start, $end ) = IP
::parseRange( $target );
287 $conds['ipb_address'][] = (string)$target;
288 $conds[] = self
::getRangeCond( $start, $end );
289 $conds = $db->makeList( $conds, LIST_OR
);
293 throw new MWException( "Tried to load block with invalid type" );
297 $blockQuery = self
::getQueryInfo();
299 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
302 # This result could contain a block on the user, a block on the IP, and a russian-doll
303 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
306 # Lower will be better
307 $bestBlockScore = 100;
309 foreach ( $res as $row ) {
310 $block = self
::newFromRow( $row );
312 # Don't use expired blocks
313 if ( $block->isExpired() ) {
317 # Don't use anon only blocks on users
318 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
322 if ( $block->getType() == self
::TYPE_RANGE
) {
323 # This is the number of bits that are allowed to vary in the block, give
324 # or take some floating point errors
325 $target = $block->getTarget();
326 $max = IP
::isIPv6( $target ) ?
128 : 32;
327 list( $network, $bits ) = IP
::parseCIDR( $target );
328 $size = $max - $bits;
330 # Rank a range block covering a single IP equally with a single-IP block
331 $score = self
::TYPE_RANGE
- 1 +
( $size / $max );
334 $score = $block->getType();
337 if ( $score < $bestBlockScore ) {
338 $bestBlockScore = $score;
343 if ( $bestRow !== null ) {
344 $this->initFromRow( $bestRow );
352 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
353 * @param string $start Hexadecimal IP representation
354 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
357 public static function getRangeCond( $start, $end = null ) {
358 if ( $end === null ) {
361 # Per T16634, we want to include relevant active rangeblocks; for
362 # rangeblocks, we want to include larger ranges which enclose the given
363 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
364 # so we can improve performance by filtering on a LIKE clause
365 $chunk = self
::getIpFragment( $start );
366 $dbr = wfGetDB( DB_REPLICA
);
367 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
369 # Fairly hard to make a malicious SQL statement out of hex characters,
370 # but stranger things have happened...
371 $safeStart = $dbr->addQuotes( $start );
372 $safeEnd = $dbr->addQuotes( $end );
374 return $dbr->makeList(
376 "ipb_range_start $like",
377 "ipb_range_start <= $safeStart",
378 "ipb_range_end >= $safeEnd",
385 * Get the component of an IP address which is certain to be the same between an IP
386 * address and a rangeblock containing that IP address.
387 * @param string $hex Hexadecimal IP representation
390 protected static function getIpFragment( $hex ) {
391 global $wgBlockCIDRLimit;
392 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
393 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
395 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
400 * Given a database row from the ipblocks table, initialize
402 * @param stdClass $row A row from the ipblocks table
404 protected function initFromRow( $row ) {
405 $this->setTarget( $row->ipb_address
);
406 $this->setBlocker( User
::newFromAnyId(
407 $row->ipb_by
, $row->ipb_by_text
, $row->ipb_by_actor ??
null
410 $this->setTimestamp( wfTimestamp( TS_MW
, $row->ipb_timestamp
) );
411 $this->mAuto
= $row->ipb_auto
;
412 $this->setHideName( $row->ipb_deleted
);
413 $this->mId
= (int)$row->ipb_id
;
414 $this->mParentBlockId
= $row->ipb_parent_block_id
;
416 // I wish I didn't have to do this
417 $db = wfGetDB( DB_REPLICA
);
418 $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry
) );
420 CommentStore
::getStore()
421 // Legacy because $row may have come from self::selectFields()
422 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
425 $this->isHardblock( !$row->ipb_anon_only
);
426 $this->isAutoblocking( $row->ipb_enable_autoblock
);
427 $this->isSitewide( (bool)$row->ipb_sitewide
);
429 $this->isCreateAccountBlocked( $row->ipb_create_account
);
430 $this->isEmailBlocked( $row->ipb_block_email
);
431 $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk
);
435 * Create a new Block object from a database row
436 * @param stdClass $row Row from the ipblocks table
439 public static function newFromRow( $row ) {
441 $block->initFromRow( $row );
446 * Delete the row from the IP blocks table.
448 * @throws MWException
451 public function delete() {
452 if ( wfReadOnly() ) {
456 if ( !$this->getId() ) {
457 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
460 $dbw = wfGetDB( DB_MASTER
);
462 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
463 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
465 $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
466 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
468 return $dbw->affectedRows() > 0;
472 * Insert a block into the block table. Will fail if there is a conflicting
473 * block (same name and options) already in the database.
475 * @param IDatabase|null $dbw If you have one available
476 * @return bool|array False on failure, assoc array on success:
477 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
479 public function insert( $dbw = null ) {
480 global $wgBlockDisablesLogin;
482 if ( !$this->getBlocker() ||
$this->getBlocker()->getName() === '' ) {
483 throw new MWException( 'Cannot insert a block without a blocker set' );
486 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
488 if ( $dbw === null ) {
489 $dbw = wfGetDB( DB_MASTER
);
492 self
::purgeExpired();
494 $row = $this->getDatabaseArray( $dbw );
496 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
497 $affected = $dbw->affectedRows();
499 $this->setId( $dbw->insertId() );
500 if ( $this->restrictions
) {
501 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
505 # Don't collide with expired blocks.
506 # Do this after trying to insert to avoid locking.
508 # T96428: The ipb_address index uses a prefix on a field, so
509 # use a standard SELECT + DELETE to avoid annoying gap locks.
510 $ids = $dbw->selectFieldValues( 'ipblocks',
513 'ipb_address' => $row['ipb_address'],
514 'ipb_user' => $row['ipb_user'],
515 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
520 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
521 $this->getBlockRestrictionStore()->deleteByBlockId( $ids );
522 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
523 $affected = $dbw->affectedRows();
524 $this->setId( $dbw->insertId() );
525 if ( $this->restrictions
) {
526 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
532 $auto_ipd_ids = $this->doRetroactiveAutoblock();
534 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
535 // Change user login token to force them to be logged out.
536 $this->target
->setToken();
537 $this->target
->saveSettings();
540 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
547 * Update a block in the DB with new parameters.
548 * The ID field needs to be loaded first.
550 * @return bool|array False on failure, array on success:
551 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
553 public function update() {
554 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
555 $dbw = wfGetDB( DB_MASTER
);
557 $dbw->startAtomic( __METHOD__
);
559 $result = $dbw->update(
561 $this->getDatabaseArray( $dbw ),
562 [ 'ipb_id' => $this->getId() ],
566 // Only update the restrictions if they have been modified.
567 if ( $this->restrictions
!== null ) {
568 // An empty array should remove all of the restrictions.
569 if ( empty( $this->restrictions
) ) {
570 $success = $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
572 $success = $this->getBlockRestrictionStore()->update( $this->restrictions
);
574 // Update the result. The first false is the result, otherwise, true.
575 $result = $result && $success;
578 if ( $this->isAutoblocking() ) {
579 // update corresponding autoblock(s) (T50813)
582 $this->getAutoblockUpdateArray( $dbw ),
583 [ 'ipb_parent_block_id' => $this->getId() ],
587 // Only update the restrictions if they have been modified.
588 if ( $this->restrictions
!== null ) {
589 $this->getBlockRestrictionStore()->updateByParentBlockId( $this->getId(), $this->restrictions
);
592 // autoblock no longer required, delete corresponding autoblock(s)
593 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
596 [ 'ipb_parent_block_id' => $this->getId() ],
601 $dbw->endAtomic( __METHOD__
);
604 $auto_ipd_ids = $this->doRetroactiveAutoblock();
605 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
612 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
613 * @param IDatabase $dbw
616 protected function getDatabaseArray( IDatabase
$dbw ) {
617 $expiry = $dbw->encodeExpiry( $this->getExpiry() );
619 if ( $this->forcedTargetID
) {
620 $uid = $this->forcedTargetID
;
622 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
626 'ipb_address' => (string)$this->target
,
628 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
629 'ipb_auto' => $this->mAuto
,
630 'ipb_anon_only' => !$this->isHardblock(),
631 'ipb_create_account' => $this->isCreateAccountBlocked(),
632 'ipb_enable_autoblock' => $this->isAutoblocking(),
633 'ipb_expiry' => $expiry,
634 'ipb_range_start' => $this->getRangeStart(),
635 'ipb_range_end' => $this->getRangeEnd(),
636 'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
637 'ipb_block_email' => $this->isEmailBlocked(),
638 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
639 'ipb_parent_block_id' => $this->mParentBlockId
,
640 'ipb_sitewide' => $this->isSitewide(),
641 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
642 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
648 * @param IDatabase $dbw
651 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
653 'ipb_create_account' => $this->isCreateAccountBlocked(),
654 'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
655 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
656 'ipb_sitewide' => $this->isSitewide(),
657 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
658 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
662 * Retroactively autoblocks the last IP used by the user (if it is a user)
663 * blocked by this Block.
665 * @return array Block IDs of retroactive autoblocks made
667 protected function doRetroactiveAutoblock() {
669 # If autoblock is enabled, autoblock the LAST IP(s) used
670 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
671 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
673 $continue = Hooks
::run(
674 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
677 self
::defaultRetroactiveAutoblock( $this, $blockIds );
684 * Retroactively autoblocks the last IP used by the user (if it is a user)
685 * blocked by this Block. This will use the recentchanges table.
687 * @param Block $block
688 * @param array &$blockIds
690 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
693 // No IPs are in recentchanges table, so nothing to select
694 if ( !$wgPutIPinRC ) {
698 // Autoblocks only apply to TYPE_USER
699 if ( $block->getType() !== self
::TYPE_USER
) {
702 $target = $block->getTarget(); // TYPE_USER => always a User object
704 $dbr = wfGetDB( DB_REPLICA
);
705 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
707 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
709 // Just the last IP used.
710 $options['LIMIT'] = 1;
713 [ 'recentchanges' ] +
$rcQuery['tables'],
721 if ( !$res->numRows() ) {
722 # No results, don't autoblock anything
723 wfDebug( "No IP found to retroactively autoblock\n" );
725 foreach ( $res as $row ) {
727 $id = $block->doAutoblock( $row->rc_ip
);
737 * Checks whether a given IP is on the autoblock whitelist.
738 * TODO: this probably belongs somewhere else, but not sure where...
740 * @param string $ip The IP to check
743 public static function isWhitelistedFromAutoblocks( $ip ) {
744 // Try to get the autoblock_whitelist from the cache, as it's faster
745 // than getting the msg raw and explode()'ing it.
746 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
747 $lines = $cache->getWithSetCallback(
748 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
750 function ( $curValue, &$ttl, array &$setOpts ) {
751 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
753 return explode( "\n",
754 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
758 wfDebug( "Checking the autoblock whitelist..\n" );
760 foreach ( $lines as $line ) {
762 if ( substr( $line, 0, 1 ) !== '*' ) {
766 $wlEntry = substr( $line, 1 );
767 $wlEntry = trim( $wlEntry );
769 wfDebug( "Checking $ip against $wlEntry..." );
771 # Is the IP in this range?
772 if ( IP
::isInRange( $ip, $wlEntry ) ) {
773 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
776 wfDebug( " No match\n" );
784 * Autoblocks the given IP, referring to this Block.
786 * @param string $autoblockIP The IP to autoblock.
787 * @return int|bool Block ID if an autoblock was inserted, false if not.
789 public function doAutoblock( $autoblockIP ) {
790 # If autoblocks are disabled, go away.
791 if ( !$this->isAutoblocking() ) {
795 # Check for presence on the autoblock whitelist.
796 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
800 // Avoid PHP 7.1 warning of passing $this by reference
802 # Allow hooks to cancel the autoblock.
803 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
804 wfDebug( "Autoblock aborted by hook.\n" );
808 # It's okay to autoblock. Go ahead and insert/update the block...
810 # Do not add a *new* block if the IP is already blocked.
811 $ipblock = self
::newFromTarget( $autoblockIP );
813 # Check if the block is an autoblock and would exceed the user block
814 # if renewed. If so, do nothing, otherwise prolong the block time...
815 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
816 $this->getExpiry() > self
::getAutoblockExpiry( $ipblock->getTimestamp() )
818 # Reset block timestamp to now and its expiry to
819 # $wgAutoblockExpiry in the future
820 $ipblock->updateTimestamp();
825 # Make a new block object with the desired properties.
826 $autoblock = new Block
;
827 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
828 $autoblock->setTarget( $autoblockIP );
829 $autoblock->setBlocker( $this->getBlocker() );
830 $autoblock->setReason(
831 wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
832 ->inContentLanguage()->plain()
834 $timestamp = wfTimestampNow();
835 $autoblock->setTimestamp( $timestamp );
836 $autoblock->mAuto
= 1;
837 $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
838 # Continue suppressing the name if needed
839 $autoblock->setHideName( $this->getHideName() );
840 $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
841 $autoblock->mParentBlockId
= $this->mId
;
842 $autoblock->isSitewide( $this->isSitewide() );
843 $autoblock->setRestrictions( $this->getRestrictions() );
845 if ( $this->getExpiry() == 'infinity' ) {
846 # Original block was indefinite, start an autoblock now
847 $autoblock->setExpiry( self
::getAutoblockExpiry( $timestamp ) );
849 # If the user is already blocked with an expiry date, we don't
850 # want to pile on top of that.
851 $autoblock->setExpiry( min( $this->getExpiry(), self
::getAutoblockExpiry( $timestamp ) ) );
854 # Insert the block...
855 $status = $autoblock->insert();
862 * Check if a block has expired. Delete it if it is.
865 public function deleteIfExpired() {
866 if ( $this->isExpired() ) {
867 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
871 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
879 * Has the block expired?
882 public function isExpired() {
883 $timestamp = wfTimestampNow();
884 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
886 if ( !$this->getExpiry() ) {
889 return $timestamp > $this->getExpiry();
894 * Is the block address valid (i.e. not a null string?)
896 * @deprecated since 1.33 No longer needed in core.
899 public function isValid() {
900 wfDeprecated( __METHOD__
, '1.33' );
901 return $this->getTarget() != null;
905 * Update the timestamp on autoblocks.
907 public function updateTimestamp() {
908 if ( $this->mAuto
) {
909 $this->setTimestamp( wfTimestamp() );
910 $this->setExpiry( self
::getAutoblockExpiry( $this->getTimestamp() ) );
912 $dbw = wfGetDB( DB_MASTER
);
913 $dbw->update( 'ipblocks',
915 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
916 'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
919 'ipb_id' => $this->getId(),
927 * Get the IP address at the start of the range in Hex form
928 * @throws MWException
929 * @return string IP in Hex form
931 public function getRangeStart() {
932 switch ( $this->type
) {
933 case self
::TYPE_USER
:
936 return IP
::toHex( $this->target
);
937 case self
::TYPE_RANGE
:
938 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
941 throw new MWException( "Block with invalid type" );
946 * Get the IP address at the end of the range in Hex form
947 * @throws MWException
948 * @return string IP in Hex form
950 public function getRangeEnd() {
951 switch ( $this->type
) {
952 case self
::TYPE_USER
:
955 return IP
::toHex( $this->target
);
956 case self
::TYPE_RANGE
:
957 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
960 throw new MWException( "Block with invalid type" );
967 public function getId() {
974 * @param int $blockId
977 private function setId( $blockId ) {
978 $this->mId
= (int)$blockId;
980 if ( is_array( $this->restrictions
) ) {
981 $this->restrictions
= $this->getBlockRestrictionStore()->setBlockId(
982 $blockId, $this->restrictions
990 * Get/set a flag determining whether the master is used for reads
992 * @param bool|null $x
995 public function fromMaster( $x = null ) {
996 return wfSetVar( $this->mFromMaster
, $x );
1000 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1001 * @param bool|null $x
1004 public function isHardblock( $x = null ) {
1005 wfSetVar( $this->isHardblock
, $x );
1007 # You can't *not* hardblock a user
1008 return $this->getType() == self
::TYPE_USER
1010 : $this->isHardblock
;
1014 * @param null|bool $x
1017 public function isAutoblocking( $x = null ) {
1018 wfSetVar( $this->isAutoblocking
, $x );
1020 # You can't put an autoblock on an IP or range as we don't have any history to
1021 # look over to get more IPs from
1022 return $this->getType() == self
::TYPE_USER
1023 ?
$this->isAutoblocking
1028 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1029 * @return string Text is escaped
1031 public function getRedactedName() {
1032 if ( $this->mAuto
) {
1033 return Html
::element(
1035 [ 'class' => 'mw-autoblockid' ],
1036 wfMessage( 'autoblockid', $this->mId
)->text()
1039 return htmlspecialchars( $this->getTarget() );
1044 * Get a timestamp of the expiry for autoblocks
1046 * @param string|int $timestamp
1049 public static function getAutoblockExpiry( $timestamp ) {
1050 global $wgAutoblockExpiry;
1052 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1056 * Purge expired blocks from the ipblocks table
1058 public static function purgeExpired() {
1059 if ( wfReadOnly() ) {
1063 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1064 wfGetDB( DB_MASTER
),
1066 function ( IDatabase
$dbw, $fname ) {
1067 $ids = $dbw->selectFieldValues( 'ipblocks',
1069 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1073 $blockRestrictionStore = MediaWikiServices
::getInstance()->getBlockRestrictionStore();
1074 $blockRestrictionStore->deleteByBlockId( $ids );
1076 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1083 * Given a target and the target's type, get an existing Block object if possible.
1084 * @param string|User|int $specificTarget A block target, which may be one of several types:
1085 * * A user to block, in which case $target will be a User
1086 * * An IP to block, in which case $target will be a User generated by using
1087 * User::newFromName( $ip, false ) to turn off name validation
1088 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1089 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1091 * Calling this with a user, IP address or range will not select autoblocks, and will
1092 * only select a block where the targets match exactly (so looking for blocks on
1093 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1094 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1095 * affects that target (so for an IP address, get ranges containing that IP; and also
1096 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1097 * @param bool $fromMaster Whether to use the DB_MASTER database
1098 * @return Block|null (null if no relevant block could be found). The target and type
1099 * of the returned Block will refer to the actual block which was found, which might
1100 * not be the same as the target you gave if you used $vagueTarget!
1102 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1103 list( $target, $type ) = self
::parseTarget( $specificTarget );
1104 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1105 return self
::newFromID( $target );
1107 } elseif ( $target === null && $vagueTarget == '' ) {
1108 # We're not going to find anything useful here
1109 # Be aware that the == '' check is explicit, since empty values will be
1110 # passed by some callers (T31116)
1113 } elseif ( in_array(
1115 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1117 $block = new Block();
1118 $block->fromMaster( $fromMaster );
1120 if ( $type !== null ) {
1121 $block->setTarget( $target );
1124 if ( $block->newLoad( $vagueTarget ) ) {
1132 * Get all blocks that match any IP from an array of IP addresses
1134 * @param array $ipChain List of IPs (strings), usually retrieved from the
1135 * X-Forwarded-For header of the request
1136 * @param bool $isAnon Exclude anonymous-only blocks if false
1137 * @param bool $fromMaster Whether to query the master or replica DB
1138 * @return array Array of Blocks
1141 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1142 if ( $ipChain === [] ) {
1147 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1148 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1149 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1150 # necessarily trust the header given to us, make sure that we are only
1151 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1152 # Do not treat private IP spaces as special as it may be desirable for wikis
1153 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1154 if ( !IP
::isValid( $ipaddr ) ) {
1157 # Don't check trusted IPs (includes local squids which will be in every request)
1158 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1161 # Check both the original IP (to check against single blocks), as well as build
1162 # the clause to check for rangeblocks for the given IP.
1163 $conds['ipb_address'][] = $ipaddr;
1164 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1167 if ( $conds === [] ) {
1171 if ( $fromMaster ) {
1172 $db = wfGetDB( DB_MASTER
);
1174 $db = wfGetDB( DB_REPLICA
);
1176 $conds = $db->makeList( $conds, LIST_OR
);
1178 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1180 $blockQuery = self
::getQueryInfo();
1181 $rows = $db->select(
1182 $blockQuery['tables'],
1183 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1187 $blockQuery['joins']
1191 foreach ( $rows as $row ) {
1192 $block = self
::newFromRow( $row );
1193 if ( !$block->isExpired() ) {
1202 * From a list of multiple blocks, find the most exact and strongest Block.
1204 * The logic for finding the "best" block is:
1205 * - Blocks that match the block's target IP are preferred over ones in a range
1206 * - Hardblocks are chosen over softblocks that prevent account creation
1207 * - Softblocks that prevent account creation are chosen over other softblocks
1208 * - Other softblocks are chosen over autoblocks
1209 * - If there are multiple exact or range blocks at the same level, the one chosen
1211 * This should be used when $blocks where retrieved from the user's IP address
1212 * and $ipChain is populated from the same IP address information.
1214 * @param array $blocks Array of Block objects
1215 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1216 * a block is to the server, and if a block matches exactly, or is in a range.
1217 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1219 * @throws MWException
1220 * @return Block|null The "best" block from the list
1222 public static function chooseBlock( array $blocks, array $ipChain ) {
1223 if ( $blocks === [] ) {
1225 } elseif ( count( $blocks ) == 1 ) {
1229 // Sort hard blocks before soft ones and secondarily sort blocks
1230 // that disable account creation before those that don't.
1231 usort( $blocks, function ( Block
$a, Block
$b ) {
1232 $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1233 $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1234 return strcmp( $bWeight, $aWeight ); // highest weight first
1237 $blocksListExact = [
1239 'disable_create' => false,
1243 $blocksListRange = [
1245 'disable_create' => false,
1249 $ipChain = array_reverse( $ipChain );
1251 /** @var Block $block */
1252 foreach ( $blocks as $block ) {
1253 // Stop searching if we have already have a "better" block. This
1254 // is why the order of the blocks matters
1255 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1257 } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1261 foreach ( $ipChain as $checkip ) {
1262 $checkipHex = IP
::toHex( $checkip );
1263 if ( (string)$block->getTarget() === $checkip ) {
1264 if ( $block->isHardblock() ) {
1265 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1266 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1267 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1268 } elseif ( $block->mAuto
) {
1269 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1271 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1273 // We found closest exact match in the ip list, so go to the next Block
1275 } elseif ( array_filter( $blocksListExact ) == []
1276 && $block->getRangeStart() <= $checkipHex
1277 && $block->getRangeEnd() >= $checkipHex
1279 if ( $block->isHardblock() ) {
1280 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1281 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1282 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1283 } elseif ( $block->mAuto
) {
1284 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1286 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1293 if ( array_filter( $blocksListExact ) == [] ) {
1294 $blocksList = &$blocksListRange;
1296 $blocksList = &$blocksListExact;
1299 $chosenBlock = null;
1300 if ( $blocksList['hard'] ) {
1301 $chosenBlock = $blocksList['hard'];
1302 } elseif ( $blocksList['disable_create'] ) {
1303 $chosenBlock = $blocksList['disable_create'];
1304 } elseif ( $blocksList['other'] ) {
1305 $chosenBlock = $blocksList['other'];
1306 } elseif ( $blocksList['auto'] ) {
1307 $chosenBlock = $blocksList['auto'];
1309 throw new MWException( "Proxy block found, but couldn't be classified." );
1312 return $chosenBlock;
1318 * Autoblocks have whichever type corresponds to their target, so to detect if a block is an
1319 * autoblock, we have to check the mAuto property instead.
1321 public function getType() {
1324 : parent
::getType();
1328 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1329 * the same as the block's, to a maximum of 24 hours.
1333 * @param WebResponse $response The response on which to set the cookie.
1335 public function setCookie( WebResponse
$response ) {
1336 // Calculate the default expiry time.
1337 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1339 // Use the Block's expiry time only if it's less than the default.
1340 $expiryTime = $this->getExpiry();
1341 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1342 $expiryTime = $maxExpiryTime;
1345 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1346 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1347 $cookieOptions = [ 'httpOnly' => false ];
1348 $cookieValue = $this->getCookieValue();
1349 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1353 * Unset the 'BlockID' cookie.
1357 * @param WebResponse $response The response on which to unset the cookie.
1359 public static function clearCookie( WebResponse
$response ) {
1360 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1364 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1365 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1370 * @return string The block ID, probably concatenated with "!" and the HMAC.
1372 public function getCookieValue() {
1373 $config = RequestContext
::getMain()->getConfig();
1374 $id = $this->getId();
1375 $secretKey = $config->get( 'SecretKey' );
1376 if ( !$secretKey ) {
1377 // If there's no secret key, don't append a HMAC.
1380 $hmac = MWCryptHash
::hmac( $id, $secretKey, false );
1381 $cookieValue = $id . '!' . $hmac;
1382 return $cookieValue;
1386 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1387 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1391 * @param string $cookieValue The string in which to find the ID.
1393 * @return int|null The block ID, or null if the HMAC is present and invalid.
1395 public static function getIdFromCookieValue( $cookieValue ) {
1396 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1397 $bangPos = strpos( $cookieValue, '!' );
1398 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
1399 // Get the site-wide secret key.
1400 $config = RequestContext
::getMain()->getConfig();
1401 $secretKey = $config->get( 'SecretKey' );
1402 if ( !$secretKey ) {
1403 // If there's no secret key, just use the ID as given.
1406 $storedHmac = substr( $cookieValue, $bangPos +
1 );
1407 $calculatedHmac = MWCryptHash
::hmac( $id, $secretKey, false );
1408 if ( $calculatedHmac === $storedHmac ) {
1418 * Build different messages for autoblocks and partial blocks.
1420 public function getPermissionsError( IContextSource
$context ) {
1421 $params = $this->getBlockErrorParams( $context );
1423 $msg = 'blockedtext';
1424 if ( $this->mAuto
) {
1425 $msg = 'autoblockedtext';
1426 } elseif ( !$this->isSitewide() ) {
1427 $msg = 'blockedtext-partial';
1430 array_unshift( $params, $msg );
1438 * Getting the restrictions will perform a database query if the restrictions
1439 * are not already loaded.
1442 * @return Restriction[]
1444 public function getRestrictions() {
1445 if ( $this->restrictions
=== null ) {
1446 // If the block id has not been set, then do not attempt to load the
1448 if ( !$this->mId
) {
1451 $this->restrictions
= $this->getBlockRestrictionStore()->loadByBlockId( $this->mId
);
1454 return $this->restrictions
;
1461 * @param Restriction[] $restrictions
1464 public function setRestrictions( array $restrictions ) {
1465 $this->restrictions
= array_filter( $restrictions, function ( $restriction ) {
1466 return $restriction instanceof Restriction
;
1475 public function appliesToTitle( Title
$title ) {
1476 if ( $this->isSitewide() ) {
1480 $restrictions = $this->getRestrictions();
1481 foreach ( $restrictions as $restriction ) {
1482 if ( $restriction->matches( $title ) ) {
1493 public function appliesToNamespace( $ns ) {
1494 if ( $this->isSitewide() ) {
1498 // Blocks do not apply to virtual namespaces.
1503 $restriction = $this->findRestriction( NamespaceRestriction
::TYPE
, $ns );
1505 return (bool)$restriction;
1511 public function appliesToPage( $pageId ) {
1512 if ( $this->isSitewide() ) {
1516 // If the pageId is not over zero, the block cannot apply to it.
1517 if ( $pageId <= 0 ) {
1521 $restriction = $this->findRestriction( PageRestriction
::TYPE
, $pageId );
1523 return (bool)$restriction;
1527 * Find Restriction by type and value.
1529 * @param string $type
1531 * @return Restriction|null
1533 private function findRestriction( $type, $value ) {
1534 $restrictions = $this->getRestrictions();
1535 foreach ( $restrictions as $restriction ) {
1536 if ( $restriction->getType() !== $type ) {
1540 if ( $restriction->getValue() === $value ) {
1541 return $restriction;
1551 public function shouldTrackWithCookie( $isAnon ) {
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();