3 * Blocks and bans object
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Wikimedia\Rdbms\Database
;
24 use Wikimedia\Rdbms\IDatabase
;
25 use MediaWiki\Block\BlockRestriction
;
26 use MediaWiki\Block\Restriction\Restriction
;
27 use MediaWiki\MediaWikiServices
;
46 public $mParentBlockId;
58 private $mDisableUsertalk;
61 private $mCreateAccount;
63 /** @var User|string */
66 /** @var int Hack for foreign blocking (CentralAuth) */
67 private $forcedTargetID;
69 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
79 private $isAutoblocking;
81 /** @var string|null */
82 private $systemBlockType;
87 /** @var Restriction[] */
88 private $restrictions;
98 * Create a new block with specified parameters on a user, IP or IP range.
100 * @param array $options Parameters of the block:
101 * address string|User Target user name, User object, IP address or IP range
102 * user int Override target user ID (for foreign users)
103 * by int User ID of the blocker
104 * reason string Reason of the block
105 * timestamp string The time at which the block comes into effect
106 * auto bool Is this an automatic block?
107 * expiry string Timestamp of expiration of the block or 'infinity'
108 * anonOnly bool Only disallow anonymous actions
109 * createAccount bool Disallow creation of new accounts
110 * enableAutoblock bool Enable automatic blocking
111 * hideName bool Hide the target user name
112 * blockEmail bool Disallow sending emails
113 * allowUsertalk bool Allow the target to edit its own talk page
114 * byText string Username of the blocker (for foreign users)
115 * systemBlock string Indicate that this block is automatically
116 * created by MediaWiki rather than being stored
117 * in the database. Value is a string to return
118 * from self::getSystemBlockType().
120 * @since 1.26 accepts $options array instead of individual parameters; order
121 * of parameters above reflects the original order
123 function __construct( $options = [] ) {
133 'createAccount' => false,
134 'enableAutoblock' => false,
136 'blockEmail' => false,
137 'allowUsertalk' => false,
139 'systemBlock' => null,
143 if ( func_num_args() > 1 ||
!is_array( $options ) ) {
144 $options = array_combine(
145 array_slice( array_keys( $defaults ), 0, func_num_args() ),
148 wfDeprecated( __METHOD__
. ' with multiple arguments', '1.26' );
151 $options +
= $defaults;
153 $this->setTarget( $options['address'] );
155 if ( $this->target
instanceof User
&& $options['user'] ) {
156 # Needed for foreign users
157 $this->forcedTargetID
= $options['user'];
160 if ( $options['by'] ) {
162 $this->setBlocker( User
::newFromId( $options['by'] ) );
165 $this->setBlocker( $options['byText'] );
168 $this->mReason
= $options['reason'];
169 $this->mTimestamp
= wfTimestamp( TS_MW
, $options['timestamp'] );
170 $this->mExpiry
= wfGetDB( DB_REPLICA
)->decodeExpiry( $options['expiry'] );
173 $this->mAuto
= (bool)$options['auto'];
174 $this->mHideName
= (bool)$options['hideName'];
175 $this->isHardblock( !$options['anonOnly'] );
176 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
177 $this->isSitewide( (bool)$options['sitewide'] );
179 # Prevention measures
180 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
181 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
182 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
184 $this->mFromMaster
= false;
185 $this->systemBlockType
= $options['systemBlock'];
189 * Load a blocked user from their block id.
191 * @param int $id Block id to search for
194 public static function newFromID( $id ) {
195 $dbr = wfGetDB( DB_REPLICA
);
196 $blockQuery = self
::getQueryInfo();
197 $res = $dbr->selectRow(
198 $blockQuery['tables'],
199 $blockQuery['fields'],
206 return self
::newFromRow( $res );
213 * Return the list of ipblocks fields that should be selected to create
215 * @deprecated since 1.31, use self::getQueryInfo() instead.
218 public static function selectFields() {
219 global $wgActorTableSchemaMigrationStage;
221 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
222 // If code is using this instead of self::getQueryInfo(), there's a
223 // decent chance it's going to try to directly access
224 // $row->ipb_by or $row->ipb_by_text and we can't give it
225 // useful values here once those aren't being used anymore.
226 throw new BadMethodCallException(
227 'Cannot use ' . __METHOD__
228 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
232 wfDeprecated( __METHOD__
, '1.31' );
238 'ipb_by_actor' => 'NULL',
242 'ipb_create_account',
243 'ipb_enable_autoblock',
247 'ipb_allow_usertalk',
248 'ipb_parent_block_id',
250 ] + CommentStore
::getStore()->getFields( 'ipb_reason' );
254 * Return the tables, fields, and join conditions to be selected to create
255 * a new block object.
257 * @return array With three keys:
258 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
259 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
260 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
262 public static function getQueryInfo() {
263 $commentQuery = CommentStore
::getStore()->getJoin( 'ipb_reason' );
264 $actorQuery = ActorMigration
::newMigration()->getJoin( 'ipb_by' );
266 'tables' => [ 'ipblocks' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
273 'ipb_create_account',
274 'ipb_enable_autoblock',
278 'ipb_allow_usertalk',
279 'ipb_parent_block_id',
281 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
282 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
287 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
288 * the blocking user or the block timestamp, only things which affect the blocked user
290 * @param Block $block
294 public function equals( Block
$block ) {
296 (string)$this->target
== (string)$block->target
297 && $this->type
== $block->type
298 && $this->mAuto
== $block->mAuto
299 && $this->isHardblock() == $block->isHardblock()
300 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
301 && $this->mExpiry
== $block->mExpiry
302 && $this->isAutoblocking() == $block->isAutoblocking()
303 && $this->mHideName
== $block->mHideName
304 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
305 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
306 && $this->mReason
== $block->mReason
307 && $this->isSitewide() == $block->isSitewide()
308 // Block::getRestrictions() may perform a database query, so keep it at
310 && BlockRestriction
::equals( $this->getRestrictions(), $block->getRestrictions() )
315 * Load a block from the database which affects the already-set $this->target:
316 * 1) A block directly on the given user or IP
317 * 2) A rangeblock encompassing the given IP (smallest first)
318 * 3) An autoblock on the given IP
319 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
320 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
321 * @throws MWException
322 * @return bool Whether a relevant block was found
324 protected function newLoad( $vagueTarget = null ) {
325 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_REPLICA
);
327 if ( $this->type
!== null ) {
329 'ipb_address' => [ (string)$this->target
],
332 $conds = [ 'ipb_address' => [] ];
335 # Be aware that the != '' check is explicit, since empty values will be
336 # passed by some callers (T31116)
337 if ( $vagueTarget != '' ) {
338 list( $target, $type ) = self
::parseTarget( $vagueTarget );
340 case self
::TYPE_USER
:
341 # Slightly weird, but who are we to argue?
342 $conds['ipb_address'][] = (string)$target;
346 $conds['ipb_address'][] = (string)$target;
347 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
348 $conds = $db->makeList( $conds, LIST_OR
);
351 case self
::TYPE_RANGE
:
352 list( $start, $end ) = IP
::parseRange( $target );
353 $conds['ipb_address'][] = (string)$target;
354 $conds[] = self
::getRangeCond( $start, $end );
355 $conds = $db->makeList( $conds, LIST_OR
);
359 throw new MWException( "Tried to load block with invalid type" );
363 $blockQuery = self
::getQueryInfo();
365 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
368 # This result could contain a block on the user, a block on the IP, and a russian-doll
369 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
372 # Lower will be better
373 $bestBlockScore = 100;
375 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
376 $bestBlockPreventsEdit = null;
378 foreach ( $res as $row ) {
379 $block = self
::newFromRow( $row );
381 # Don't use expired blocks
382 if ( $block->isExpired() ) {
386 # Don't use anon only blocks on users
387 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
391 if ( $block->getType() == self
::TYPE_RANGE
) {
392 # This is the number of bits that are allowed to vary in the block, give
393 # or take some floating point errors
394 $end = Wikimedia\base_convert
( $block->getRangeEnd(), 16, 10 );
395 $start = Wikimedia\base_convert
( $block->getRangeStart(), 16, 10 );
396 $size = log( $end - $start +
1, 2 );
398 # This has the nice property that a /32 block is ranked equally with a
399 # single-IP block, which is exactly what it is...
400 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
403 $score = $block->getType();
406 if ( $score < $bestBlockScore ) {
407 $bestBlockScore = $score;
409 $bestBlockPreventsEdit = $block->prevents( 'edit' );
413 if ( $bestRow !== null ) {
414 $this->initFromRow( $bestRow );
415 $this->prevents( 'edit', $bestBlockPreventsEdit );
423 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
424 * @param string $start Hexadecimal IP representation
425 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
428 public static function getRangeCond( $start, $end = null ) {
429 if ( $end === null ) {
432 # Per T16634, we want to include relevant active rangeblocks; for
433 # rangeblocks, we want to include larger ranges which enclose the given
434 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
435 # so we can improve performance by filtering on a LIKE clause
436 $chunk = self
::getIpFragment( $start );
437 $dbr = wfGetDB( DB_REPLICA
);
438 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
440 # Fairly hard to make a malicious SQL statement out of hex characters,
441 # but stranger things have happened...
442 $safeStart = $dbr->addQuotes( $start );
443 $safeEnd = $dbr->addQuotes( $end );
445 return $dbr->makeList(
447 "ipb_range_start $like",
448 "ipb_range_start <= $safeStart",
449 "ipb_range_end >= $safeEnd",
456 * Get the component of an IP address which is certain to be the same between an IP
457 * address and a rangeblock containing that IP address.
458 * @param string $hex Hexadecimal IP representation
461 protected static function getIpFragment( $hex ) {
462 global $wgBlockCIDRLimit;
463 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
464 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
466 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
471 * Given a database row from the ipblocks table, initialize
473 * @param stdClass $row A row from the ipblocks table
475 protected function initFromRow( $row ) {
476 $this->setTarget( $row->ipb_address
);
477 $this->setBlocker( User
::newFromAnyId(
478 $row->ipb_by
, $row->ipb_by_text
, $row->ipb_by_actor ??
null
481 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
482 $this->mAuto
= $row->ipb_auto
;
483 $this->mHideName
= $row->ipb_deleted
;
484 $this->mId
= (int)$row->ipb_id
;
485 $this->mParentBlockId
= $row->ipb_parent_block_id
;
487 // I wish I didn't have to do this
488 $db = wfGetDB( DB_REPLICA
);
489 $this->mExpiry
= $db->decodeExpiry( $row->ipb_expiry
);
490 $this->mReason
= CommentStore
::getStore()
491 // Legacy because $row may have come from self::selectFields()
492 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
;
494 $this->isHardblock( !$row->ipb_anon_only
);
495 $this->isAutoblocking( $row->ipb_enable_autoblock
);
496 $this->isSitewide( (bool)$row->ipb_sitewide
);
498 $this->prevents( 'createaccount', $row->ipb_create_account
);
499 $this->prevents( 'sendemail', $row->ipb_block_email
);
500 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
504 * Create a new Block object from a database row
505 * @param stdClass $row Row from the ipblocks table
508 public static function newFromRow( $row ) {
510 $block->initFromRow( $row );
515 * Delete the row from the IP blocks table.
517 * @throws MWException
520 public function delete() {
521 if ( wfReadOnly() ) {
525 if ( !$this->getId() ) {
526 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
529 $dbw = wfGetDB( DB_MASTER
);
531 BlockRestriction
::deleteByParentBlockId( $this->getId() );
532 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
534 BlockRestriction
::deleteByBlockId( $this->getId() );
535 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
537 return $dbw->affectedRows() > 0;
541 * Insert a block into the block table. Will fail if there is a conflicting
542 * block (same name and options) already in the database.
544 * @param IDatabase|null $dbw If you have one available
545 * @return bool|array False on failure, assoc array on success:
546 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
548 public function insert( $dbw = null ) {
549 global $wgBlockDisablesLogin;
551 if ( $this->getSystemBlockType() !== null ) {
552 throw new MWException( 'Cannot insert a system block into the database' );
554 if ( !$this->getBlocker() ||
$this->getBlocker()->getName() === '' ) {
555 throw new MWException( 'Cannot insert a block without a blocker set' );
558 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
560 if ( $dbw === null ) {
561 $dbw = wfGetDB( DB_MASTER
);
564 self
::purgeExpired();
566 $row = $this->getDatabaseArray( $dbw );
568 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
569 $affected = $dbw->affectedRows();
571 $this->setId( $dbw->insertId() );
572 if ( $this->restrictions
) {
573 BlockRestriction
::insert( $this->restrictions
);
577 # Don't collide with expired blocks.
578 # Do this after trying to insert to avoid locking.
580 # T96428: The ipb_address index uses a prefix on a field, so
581 # use a standard SELECT + DELETE to avoid annoying gap locks.
582 $ids = $dbw->selectFieldValues( 'ipblocks',
585 'ipb_address' => $row['ipb_address'],
586 'ipb_user' => $row['ipb_user'],
587 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
592 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
593 BlockRestriction
::deleteByBlockId( $ids );
594 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
595 $affected = $dbw->affectedRows();
596 $this->setId( $dbw->insertId() );
597 if ( $this->restrictions
) {
598 BlockRestriction
::insert( $this->restrictions
);
604 $auto_ipd_ids = $this->doRetroactiveAutoblock();
606 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
607 // Change user login token to force them to be logged out.
608 $this->target
->setToken();
609 $this->target
->saveSettings();
612 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
619 * Update a block in the DB with new parameters.
620 * The ID field needs to be loaded first.
622 * @return bool|array False on failure, array on success:
623 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
625 public function update() {
626 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
627 $dbw = wfGetDB( DB_MASTER
);
629 $dbw->startAtomic( __METHOD__
);
631 $result = $dbw->update(
633 $this->getDatabaseArray( $dbw ),
634 [ 'ipb_id' => $this->getId() ],
638 // Only update the restrictions if they have been modified.
639 if ( $this->restrictions
!== null ) {
640 // An empty array should remove all of the restrictions.
641 if ( empty( $this->restrictions
) ) {
642 $success = BlockRestriction
::deleteByBlockId( $this->getId() );
644 $success = BlockRestriction
::update( $this->restrictions
);
646 // Update the result. The first false is the result, otherwise, true.
647 $result = $result && $success;
650 if ( $this->isAutoblocking() ) {
651 // update corresponding autoblock(s) (T50813)
654 $this->getAutoblockUpdateArray( $dbw ),
655 [ 'ipb_parent_block_id' => $this->getId() ],
659 // Only update the restrictions if they have been modified.
660 if ( $this->restrictions
!== null ) {
661 BlockRestriction
::updateByParentBlockId( $this->getId(), $this->restrictions
);
664 // autoblock no longer required, delete corresponding autoblock(s)
665 BlockRestriction
::deleteByParentBlockId( $this->getId() );
668 [ 'ipb_parent_block_id' => $this->getId() ],
673 $dbw->endAtomic( __METHOD__
);
676 $auto_ipd_ids = $this->doRetroactiveAutoblock();
677 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
684 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
685 * @param IDatabase $dbw
688 protected function getDatabaseArray( IDatabase
$dbw ) {
689 $expiry = $dbw->encodeExpiry( $this->mExpiry
);
691 if ( $this->forcedTargetID
) {
692 $uid = $this->forcedTargetID
;
694 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
698 'ipb_address' => (string)$this->target
,
700 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
701 'ipb_auto' => $this->mAuto
,
702 'ipb_anon_only' => !$this->isHardblock(),
703 'ipb_create_account' => $this->prevents( 'createaccount' ),
704 'ipb_enable_autoblock' => $this->isAutoblocking(),
705 'ipb_expiry' => $expiry,
706 'ipb_range_start' => $this->getRangeStart(),
707 'ipb_range_end' => $this->getRangeEnd(),
708 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
709 'ipb_block_email' => $this->prevents( 'sendemail' ),
710 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
711 'ipb_parent_block_id' => $this->mParentBlockId
,
712 'ipb_sitewide' => $this->isSitewide(),
713 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->mReason
)
714 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
720 * @param IDatabase $dbw
723 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
725 'ipb_create_account' => $this->prevents( 'createaccount' ),
726 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
727 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
728 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->mReason
)
729 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
733 * Retroactively autoblocks the last IP used by the user (if it is a user)
734 * blocked by this Block.
736 * @return array Block IDs of retroactive autoblocks made
738 protected function doRetroactiveAutoblock() {
740 # If autoblock is enabled, autoblock the LAST IP(s) used
741 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
742 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
744 $continue = Hooks
::run(
745 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
748 self
::defaultRetroactiveAutoblock( $this, $blockIds );
755 * Retroactively autoblocks the last IP used by the user (if it is a user)
756 * blocked by this Block. This will use the recentchanges table.
758 * @param Block $block
759 * @param array &$blockIds
761 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
764 // No IPs are in recentchanges table, so nothing to select
765 if ( !$wgPutIPinRC ) {
769 // Autoblocks only apply to TYPE_USER
770 if ( $block->getType() !== self
::TYPE_USER
) {
773 $target = $block->getTarget(); // TYPE_USER => always a User object
775 $dbr = wfGetDB( DB_REPLICA
);
776 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
778 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
780 // Just the last IP used.
781 $options['LIMIT'] = 1;
784 [ 'recentchanges' ] +
$rcQuery['tables'],
792 if ( !$res->numRows() ) {
793 # No results, don't autoblock anything
794 wfDebug( "No IP found to retroactively autoblock\n" );
796 foreach ( $res as $row ) {
798 $id = $block->doAutoblock( $row->rc_ip
);
808 * Checks whether a given IP is on the autoblock whitelist.
809 * TODO: this probably belongs somewhere else, but not sure where...
811 * @param string $ip The IP to check
814 public static function isWhitelistedFromAutoblocks( $ip ) {
815 // Try to get the autoblock_whitelist from the cache, as it's faster
816 // than getting the msg raw and explode()'ing it.
817 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
818 $lines = $cache->getWithSetCallback(
819 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
821 function ( $curValue, &$ttl, array &$setOpts ) {
822 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
824 return explode( "\n",
825 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
829 wfDebug( "Checking the autoblock whitelist..\n" );
831 foreach ( $lines as $line ) {
833 if ( substr( $line, 0, 1 ) !== '*' ) {
837 $wlEntry = substr( $line, 1 );
838 $wlEntry = trim( $wlEntry );
840 wfDebug( "Checking $ip against $wlEntry..." );
842 # Is the IP in this range?
843 if ( IP
::isInRange( $ip, $wlEntry ) ) {
844 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
847 wfDebug( " No match\n" );
855 * Autoblocks the given IP, referring to this Block.
857 * @param string $autoblockIP The IP to autoblock.
858 * @return int|bool Block ID if an autoblock was inserted, false if not.
860 public function doAutoblock( $autoblockIP ) {
861 # If autoblocks are disabled, go away.
862 if ( !$this->isAutoblocking() ) {
866 # Don't autoblock for system blocks
867 if ( $this->getSystemBlockType() !== null ) {
868 throw new MWException( 'Cannot autoblock from a system block' );
871 # Check for presence on the autoblock whitelist.
872 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
876 // Avoid PHP 7.1 warning of passing $this by reference
878 # Allow hooks to cancel the autoblock.
879 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
880 wfDebug( "Autoblock aborted by hook.\n" );
884 # It's okay to autoblock. Go ahead and insert/update the block...
886 # Do not add a *new* block if the IP is already blocked.
887 $ipblock = self
::newFromTarget( $autoblockIP );
889 # Check if the block is an autoblock and would exceed the user block
890 # if renewed. If so, do nothing, otherwise prolong the block time...
891 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
892 $this->mExpiry
> self
::getAutoblockExpiry( $ipblock->mTimestamp
)
894 # Reset block timestamp to now and its expiry to
895 # $wgAutoblockExpiry in the future
896 $ipblock->updateTimestamp();
901 # Make a new block object with the desired properties.
902 $autoblock = new Block
;
903 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
904 $autoblock->setTarget( $autoblockIP );
905 $autoblock->setBlocker( $this->getBlocker() );
906 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
907 ->inContentLanguage()->plain();
908 $timestamp = wfTimestampNow();
909 $autoblock->mTimestamp
= $timestamp;
910 $autoblock->mAuto
= 1;
911 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
912 # Continue suppressing the name if needed
913 $autoblock->mHideName
= $this->mHideName
;
914 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
915 $autoblock->mParentBlockId
= $this->mId
;
916 $autoblock->isSitewide( $this->isSitewide() );
917 $autoblock->setRestrictions( $this->getRestrictions() );
919 if ( $this->mExpiry
== 'infinity' ) {
920 # Original block was indefinite, start an autoblock now
921 $autoblock->mExpiry
= self
::getAutoblockExpiry( $timestamp );
923 # If the user is already blocked with an expiry date, we don't
924 # want to pile on top of that.
925 $autoblock->mExpiry
= min( $this->mExpiry
, self
::getAutoblockExpiry( $timestamp ) );
928 # Insert the block...
929 $status = $autoblock->insert();
936 * Check if a block has expired. Delete it if it is.
939 public function deleteIfExpired() {
940 if ( $this->isExpired() ) {
941 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
945 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
953 * Has the block expired?
956 public function isExpired() {
957 $timestamp = wfTimestampNow();
958 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
960 if ( !$this->mExpiry
) {
963 return $timestamp > $this->mExpiry
;
968 * Is the block address valid (i.e. not a null string?)
971 public function isValid() {
972 return $this->getTarget() != null;
976 * Update the timestamp on autoblocks.
978 public function updateTimestamp() {
979 if ( $this->mAuto
) {
980 $this->mTimestamp
= wfTimestamp();
981 $this->mExpiry
= self
::getAutoblockExpiry( $this->mTimestamp
);
983 $dbw = wfGetDB( DB_MASTER
);
984 $dbw->update( 'ipblocks',
986 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
987 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
990 'ipb_id' => $this->getId(),
998 * Get the IP address at the start of the range in Hex form
999 * @throws MWException
1000 * @return string IP in Hex form
1002 public function getRangeStart() {
1003 switch ( $this->type
) {
1004 case self
::TYPE_USER
:
1007 return IP
::toHex( $this->target
);
1008 case self
::TYPE_RANGE
:
1009 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
1012 throw new MWException( "Block with invalid type" );
1017 * Get the IP address at the end of the range in Hex form
1018 * @throws MWException
1019 * @return string IP in Hex form
1021 public function getRangeEnd() {
1022 switch ( $this->type
) {
1023 case self
::TYPE_USER
:
1026 return IP
::toHex( $this->target
);
1027 case self
::TYPE_RANGE
:
1028 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
1031 throw new MWException( "Block with invalid type" );
1036 * Get the user id of the blocking sysop
1038 * @return int (0 for foreign users)
1040 public function getBy() {
1041 $blocker = $this->getBlocker();
1042 return ( $blocker instanceof User
)
1048 * Get the username of the blocking sysop
1052 public function getByName() {
1053 $blocker = $this->getBlocker();
1054 return ( $blocker instanceof User
)
1055 ?
$blocker->getName()
1056 : (string)$blocker; // username
1063 public function getId() {
1070 * @param int $blockId
1073 private function setId( $blockId ) {
1074 $this->mId
= (int)$blockId;
1076 if ( is_array( $this->restrictions
) ) {
1077 $this->restrictions
= BlockRestriction
::setBlockId( $blockId, $this->restrictions
);
1084 * Get the system block type, if any
1086 * @return string|null
1088 public function getSystemBlockType() {
1089 return $this->systemBlockType
;
1093 * Get/set a flag determining whether the master is used for reads
1095 * @param bool|null $x
1098 public function fromMaster( $x = null ) {
1099 return wfSetVar( $this->mFromMaster
, $x );
1103 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1104 * @param bool|null $x
1107 public function isHardblock( $x = null ) {
1108 wfSetVar( $this->isHardblock
, $x );
1110 # You can't *not* hardblock a user
1111 return $this->getType() == self
::TYPE_USER
1113 : $this->isHardblock
;
1117 * @param null|bool $x
1120 public function isAutoblocking( $x = null ) {
1121 wfSetVar( $this->isAutoblocking
, $x );
1123 # You can't put an autoblock on an IP or range as we don't have any history to
1124 # look over to get more IPs from
1125 return $this->getType() == self
::TYPE_USER
1126 ?
$this->isAutoblocking
1131 * Indicates that the block is a sitewide block. This means the user is
1132 * prohibited from editing any page on the site (other than their own talk
1135 * @param null|bool $x
1138 public function isSitewide( $x = null ) {
1139 return wfSetVar( $this->isSitewide
, $x );
1143 * Get/set whether the Block prevents a given action
1145 * @param string $action Action to check
1146 * @param bool|null $x Value for set, or null to just get value
1147 * @return bool|null Null for unrecognized rights.
1149 public function prevents( $action, $x = null ) {
1150 $config = RequestContext
::getMain()->getConfig();
1151 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1152 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1155 switch ( $action ) {
1157 # For now... <evil laugh>
1160 case 'createaccount':
1161 $res = wfSetVar( $this->mCreateAccount
, $x );
1164 $res = wfSetVar( $this->mBlockEmail
, $x );
1167 // Until T6995 is completed
1168 $res = $this->isSitewide();
1170 case 'editownusertalk':
1171 // NOTE: this check is not reliable on partial blocks
1172 // since partially blocked users are always allowed to edit
1173 // their own talk page unless a restriction exists on the
1174 // page or User_talk: namespace
1175 $res = wfSetVar( $this->mDisableUsertalk
, $x );
1177 // edit own user talk can be disabled by config
1178 if ( !$blockAllowsUTEdit ) {
1186 if ( !$res && $blockDisablesLogin ) {
1187 // If a block would disable login, then it should
1188 // prevent any action that all users cannot do
1190 $res = $anon->isAllowed( $action ) ?
$res : true;
1197 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1198 * @return string Text is escaped
1200 public function getRedactedName() {
1201 if ( $this->mAuto
) {
1202 return Html
::rawElement(
1204 [ 'class' => 'mw-autoblockid' ],
1205 wfMessage( 'autoblockid', $this->mId
)
1208 return htmlspecialchars( $this->getTarget() );
1213 * Get a timestamp of the expiry for autoblocks
1215 * @param string|int $timestamp
1218 public static function getAutoblockExpiry( $timestamp ) {
1219 global $wgAutoblockExpiry;
1221 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1225 * Purge expired blocks from the ipblocks table
1227 public static function purgeExpired() {
1228 if ( wfReadOnly() ) {
1232 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1233 wfGetDB( DB_MASTER
),
1235 function ( IDatabase
$dbw, $fname ) {
1236 $ids = $dbw->selectFieldValues( 'ipblocks',
1238 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1242 BlockRestriction
::deleteByBlockId( $ids );
1243 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1250 * Given a target and the target's type, get an existing Block object if possible.
1251 * @param string|User|int $specificTarget A block target, which may be one of several types:
1252 * * A user to block, in which case $target will be a User
1253 * * An IP to block, in which case $target will be a User generated by using
1254 * User::newFromName( $ip, false ) to turn off name validation
1255 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1256 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1258 * Calling this with a user, IP address or range will not select autoblocks, and will
1259 * only select a block where the targets match exactly (so looking for blocks on
1260 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1261 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1262 * affects that target (so for an IP address, get ranges containing that IP; and also
1263 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1264 * @param bool $fromMaster Whether to use the DB_MASTER database
1265 * @return Block|null (null if no relevant block could be found). The target and type
1266 * of the returned Block will refer to the actual block which was found, which might
1267 * not be the same as the target you gave if you used $vagueTarget!
1269 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1270 list( $target, $type ) = self
::parseTarget( $specificTarget );
1271 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1272 return self
::newFromID( $target );
1274 } elseif ( $target === null && $vagueTarget == '' ) {
1275 # We're not going to find anything useful here
1276 # Be aware that the == '' check is explicit, since empty values will be
1277 # passed by some callers (T31116)
1280 } elseif ( in_array(
1282 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1284 $block = new Block();
1285 $block->fromMaster( $fromMaster );
1287 if ( $type !== null ) {
1288 $block->setTarget( $target );
1291 if ( $block->newLoad( $vagueTarget ) ) {
1299 * Get all blocks that match any IP from an array of IP addresses
1301 * @param array $ipChain List of IPs (strings), usually retrieved from the
1302 * X-Forwarded-For header of the request
1303 * @param bool $isAnon Exclude anonymous-only blocks if false
1304 * @param bool $fromMaster Whether to query the master or replica DB
1305 * @return array Array of Blocks
1308 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1309 if ( !count( $ipChain ) ) {
1314 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1315 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1316 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1317 # necessarily trust the header given to us, make sure that we are only
1318 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1319 # Do not treat private IP spaces as special as it may be desirable for wikis
1320 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1321 if ( !IP
::isValid( $ipaddr ) ) {
1324 # Don't check trusted IPs (includes local squids which will be in every request)
1325 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1328 # Check both the original IP (to check against single blocks), as well as build
1329 # the clause to check for rangeblocks for the given IP.
1330 $conds['ipb_address'][] = $ipaddr;
1331 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1334 if ( !count( $conds ) ) {
1338 if ( $fromMaster ) {
1339 $db = wfGetDB( DB_MASTER
);
1341 $db = wfGetDB( DB_REPLICA
);
1343 $conds = $db->makeList( $conds, LIST_OR
);
1345 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1347 $blockQuery = self
::getQueryInfo();
1348 $rows = $db->select(
1349 $blockQuery['tables'],
1350 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1354 $blockQuery['joins']
1358 foreach ( $rows as $row ) {
1359 $block = self
::newFromRow( $row );
1360 if ( !$block->isExpired() ) {
1369 * From a list of multiple blocks, find the most exact and strongest Block.
1371 * The logic for finding the "best" block is:
1372 * - Blocks that match the block's target IP are preferred over ones in a range
1373 * - Hardblocks are chosen over softblocks that prevent account creation
1374 * - Softblocks that prevent account creation are chosen over other softblocks
1375 * - Other softblocks are chosen over autoblocks
1376 * - If there are multiple exact or range blocks at the same level, the one chosen
1378 * This should be used when $blocks where retrieved from the user's IP address
1379 * and $ipChain is populated from the same IP address information.
1381 * @param array $blocks Array of Block objects
1382 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1383 * a block is to the server, and if a block matches exactly, or is in a range.
1384 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1386 * @throws MWException
1387 * @return Block|null The "best" block from the list
1389 public static function chooseBlock( array $blocks, array $ipChain ) {
1390 if ( !count( $blocks ) ) {
1392 } elseif ( count( $blocks ) == 1 ) {
1396 // Sort hard blocks before soft ones and secondarily sort blocks
1397 // that disable account creation before those that don't.
1398 usort( $blocks, function ( Block
$a, Block
$b ) {
1399 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1400 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1401 return strcmp( $bWeight, $aWeight ); // highest weight first
1404 $blocksListExact = [
1406 'disable_create' => false,
1410 $blocksListRange = [
1412 'disable_create' => false,
1416 $ipChain = array_reverse( $ipChain );
1418 /** @var Block $block */
1419 foreach ( $blocks as $block ) {
1420 // Stop searching if we have already have a "better" block. This
1421 // is why the order of the blocks matters
1422 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1424 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1428 foreach ( $ipChain as $checkip ) {
1429 $checkipHex = IP
::toHex( $checkip );
1430 if ( (string)$block->getTarget() === $checkip ) {
1431 if ( $block->isHardblock() ) {
1432 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1433 } elseif ( $block->prevents( 'createaccount' ) ) {
1434 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1435 } elseif ( $block->mAuto
) {
1436 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1438 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1440 // We found closest exact match in the ip list, so go to the next Block
1442 } elseif ( array_filter( $blocksListExact ) == []
1443 && $block->getRangeStart() <= $checkipHex
1444 && $block->getRangeEnd() >= $checkipHex
1446 if ( $block->isHardblock() ) {
1447 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1448 } elseif ( $block->prevents( 'createaccount' ) ) {
1449 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1450 } elseif ( $block->mAuto
) {
1451 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1453 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1460 if ( array_filter( $blocksListExact ) == [] ) {
1461 $blocksList = &$blocksListRange;
1463 $blocksList = &$blocksListExact;
1466 $chosenBlock = null;
1467 if ( $blocksList['hard'] ) {
1468 $chosenBlock = $blocksList['hard'];
1469 } elseif ( $blocksList['disable_create'] ) {
1470 $chosenBlock = $blocksList['disable_create'];
1471 } elseif ( $blocksList['other'] ) {
1472 $chosenBlock = $blocksList['other'];
1473 } elseif ( $blocksList['auto'] ) {
1474 $chosenBlock = $blocksList['auto'];
1476 throw new MWException( "Proxy block found, but couldn't be classified." );
1479 return $chosenBlock;
1483 * From an existing Block, get the target and the type of target.
1484 * Note that, except for null, it is always safe to treat the target
1485 * as a string; for User objects this will return User::__toString()
1486 * which in turn gives User::getName().
1488 * @param string|int|User|null $target
1489 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1491 public static function parseTarget( $target ) {
1492 # We may have been through this before
1493 if ( $target instanceof User
) {
1494 if ( IP
::isValid( $target->getName() ) ) {
1495 return [ $target, self
::TYPE_IP
];
1497 return [ $target, self
::TYPE_USER
];
1499 } elseif ( $target === null ) {
1500 return [ null, null ];
1503 $target = trim( $target );
1505 if ( IP
::isValid( $target ) ) {
1506 # We can still create a User if it's an IP address, but we need to turn
1507 # off validation checking (which would exclude IP addresses)
1509 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1513 } elseif ( IP
::isValidRange( $target ) ) {
1514 # Can't create a User from an IP range
1515 return [ IP
::sanitizeRange( $target ), self
::TYPE_RANGE
];
1518 # Consider the possibility that this is not a username at all
1519 # but actually an old subpage (T31797)
1520 if ( strpos( $target, '/' ) !== false ) {
1521 # An old subpage, drill down to the user behind it
1522 $target = explode( '/', $target )[0];
1525 $userObj = User
::newFromName( $target );
1526 if ( $userObj instanceof User
) {
1527 # Note that since numbers are valid usernames, a $target of "12345" will be
1528 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1529 # since hash characters are not valid in usernames or titles generally.
1530 return [ $userObj, self
::TYPE_USER
];
1532 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1533 # Autoblock reference in the form "#12345"
1534 return [ substr( $target, 1 ), self
::TYPE_AUTO
];
1538 return [ null, null ];
1543 * Get the type of target for this particular block
1544 * @return int Block::TYPE_ constant, will never be TYPE_ID
1546 public function getType() {
1553 * Get the target and target type for this particular Block. Note that for autoblocks,
1554 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1555 * in this situation.
1556 * @return array [ User|String, Block::TYPE_ constant ]
1557 * @todo FIXME: This should be an integral part of the Block member variables
1559 public function getTargetAndType() {
1560 return [ $this->getTarget(), $this->getType() ];
1564 * Get the target for this particular Block. Note that for autoblocks,
1565 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1566 * in this situation.
1567 * @return User|string
1569 public function getTarget() {
1570 return $this->target
;
1576 * @return mixed|string
1578 public function getExpiry() {
1579 return $this->mExpiry
;
1583 * Set the target for this block, and update $this->type accordingly
1584 * @param mixed $target
1586 public function setTarget( $target ) {
1587 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1591 * Get the user who implemented this block
1592 * @return User User object. May name a foreign user.
1594 public function getBlocker() {
1595 return $this->blocker
;
1599 * Set the user who implemented (or will implement) this block
1600 * @param User|string $user Local User object or username string
1602 public function setBlocker( $user ) {
1603 if ( is_string( $user ) ) {
1604 $user = User
::newFromName( $user, false );
1607 if ( $user->isAnon() && User
::isUsableName( $user->getName() ) ) {
1608 throw new InvalidArgumentException(
1609 'Blocker must be a local user or a name that cannot be a local user'
1613 $this->blocker
= $user;
1617 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1618 * the same as the block's, to a maximum of 24 hours.
1622 * @param WebResponse $response The response on which to set the cookie.
1624 public function setCookie( WebResponse
$response ) {
1625 // Calculate the default expiry time.
1626 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1628 // Use the Block's expiry time only if it's less than the default.
1629 $expiryTime = $this->getExpiry();
1630 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1631 $expiryTime = $maxExpiryTime;
1634 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1635 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1636 $cookieOptions = [ 'httpOnly' => false ];
1637 $cookieValue = $this->getCookieValue();
1638 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1642 * Unset the 'BlockID' cookie.
1646 * @param WebResponse $response The response on which to unset the cookie.
1648 public static function clearCookie( WebResponse
$response ) {
1649 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1653 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1654 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1659 * @return string The block ID, probably concatenated with "!" and the HMAC.
1661 public function getCookieValue() {
1662 $config = RequestContext
::getMain()->getConfig();
1663 $id = $this->getId();
1664 $secretKey = $config->get( 'SecretKey' );
1665 if ( !$secretKey ) {
1666 // If there's no secret key, don't append a HMAC.
1669 $hmac = MWCryptHash
::hmac( $id, $secretKey, false );
1670 $cookieValue = $id . '!' . $hmac;
1671 return $cookieValue;
1675 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1676 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1680 * @param string $cookieValue The string in which to find the ID.
1682 * @return int|null The block ID, or null if the HMAC is present and invalid.
1684 public static function getIdFromCookieValue( $cookieValue ) {
1685 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1686 $bangPos = strpos( $cookieValue, '!' );
1687 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
1688 // Get the site-wide secret key.
1689 $config = RequestContext
::getMain()->getConfig();
1690 $secretKey = $config->get( 'SecretKey' );
1691 if ( !$secretKey ) {
1692 // If there's no secret key, just use the ID as given.
1695 $storedHmac = substr( $cookieValue, $bangPos +
1 );
1696 $calculatedHmac = MWCryptHash
::hmac( $id, $secretKey, false );
1697 if ( $calculatedHmac === $storedHmac ) {
1705 * Get the key and parameters for the corresponding error message.
1708 * @param IContextSource $context
1711 public function getPermissionsError( IContextSource
$context ) {
1712 $params = $this->getBlockErrorParams( $context );
1714 $msg = 'blockedtext';
1715 if ( $this->getSystemBlockType() !== null ) {
1716 $msg = 'systemblockedtext';
1717 } elseif ( $this->mAuto
) {
1718 $msg = 'autoblockedtext';
1719 } elseif ( !$this->isSitewide() ) {
1720 $msg = 'blockedtext-partial';
1723 array_unshift( $params, $msg );
1729 * Get block information used in different block error messages
1731 * @param IContextSource $context
1734 public function getBlockErrorParams( IContextSource
$context ) {
1735 $blocker = $this->getBlocker();
1736 if ( $blocker instanceof User
) { // local user
1737 $blockerUserpage = $blocker->getUserPage();
1738 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1739 } else { // foreign user
1743 $reason = $this->mReason
;
1744 if ( $reason == '' ) {
1745 $reason = $context->msg( 'blockednoreason' )->text();
1748 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1749 * This could be a username, an IP range, or a single IP. */
1750 $intended = $this->getTarget();
1751 $systemBlockType = $this->getSystemBlockType();
1752 $lang = $context->getLanguage();
1757 $context->getRequest()->getIP(),
1759 $systemBlockType ??
$this->getId(),
1760 $lang->formatExpiry( $this->mExpiry
),
1762 $lang->userTimeAndDate( $this->mTimestamp
, $context->getUser() ),
1769 * Getting the restrictions will perform a database query if the restrictions
1770 * are not already loaded.
1772 * @return Restriction[]
1774 public function getRestrictions() {
1775 if ( $this->restrictions
=== null ) {
1776 // If the block id has not been set, then do not attempt to load the
1778 if ( !$this->mId
) {
1781 $this->restrictions
= BlockRestriction
::loadByBlockId( $this->mId
);
1784 return $this->restrictions
;
1790 * @param Restriction[] $restrictions
1794 public function setRestrictions( array $restrictions ) {
1795 $this->restrictions
= array_filter( $restrictions, function ( $restriction ) {
1796 return $restriction instanceof Restriction
;
1803 * Checks if a block applies to a particular title
1805 * This check does not consider whether `$this->prevents( 'editownusertalk' )`
1806 * returns false, as the identity of the user making the hypothetical edit
1807 * isn't known here (particularly in the case of IP hardblocks, range
1808 * blocks, and auto-blocks).
1810 * @param Title $title
1813 public function appliesToTitle( Title
$title ) {
1814 if ( $this->isSitewide() ) {
1818 $restrictions = $this->getRestrictions();
1819 foreach ( $restrictions as $restriction ) {
1820 if ( $restriction->matches( $title ) ) {