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 $target = $block->getTarget();
770 if ( is_string( $target ) ) {
771 $target = User
::newFromName( $target, false );
774 $dbr = wfGetDB( DB_REPLICA
);
775 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
777 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
779 // Just the last IP used.
780 $options['LIMIT'] = 1;
783 [ 'recentchanges' ] +
$rcQuery['tables'],
791 if ( !$res->numRows() ) {
792 # No results, don't autoblock anything
793 wfDebug( "No IP found to retroactively autoblock\n" );
795 foreach ( $res as $row ) {
797 $id = $block->doAutoblock( $row->rc_ip
);
807 * Checks whether a given IP is on the autoblock whitelist.
808 * TODO: this probably belongs somewhere else, but not sure where...
810 * @param string $ip The IP to check
813 public static function isWhitelistedFromAutoblocks( $ip ) {
814 // Try to get the autoblock_whitelist from the cache, as it's faster
815 // than getting the msg raw and explode()'ing it.
816 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
817 $lines = $cache->getWithSetCallback(
818 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
820 function ( $curValue, &$ttl, array &$setOpts ) {
821 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
823 return explode( "\n",
824 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
828 wfDebug( "Checking the autoblock whitelist..\n" );
830 foreach ( $lines as $line ) {
832 if ( substr( $line, 0, 1 ) !== '*' ) {
836 $wlEntry = substr( $line, 1 );
837 $wlEntry = trim( $wlEntry );
839 wfDebug( "Checking $ip against $wlEntry..." );
841 # Is the IP in this range?
842 if ( IP
::isInRange( $ip, $wlEntry ) ) {
843 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
846 wfDebug( " No match\n" );
854 * Autoblocks the given IP, referring to this Block.
856 * @param string $autoblockIP The IP to autoblock.
857 * @return int|bool Block ID if an autoblock was inserted, false if not.
859 public function doAutoblock( $autoblockIP ) {
860 # If autoblocks are disabled, go away.
861 if ( !$this->isAutoblocking() ) {
865 # Don't autoblock for system blocks
866 if ( $this->getSystemBlockType() !== null ) {
867 throw new MWException( 'Cannot autoblock from a system block' );
870 # Check for presence on the autoblock whitelist.
871 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
875 // Avoid PHP 7.1 warning of passing $this by reference
877 # Allow hooks to cancel the autoblock.
878 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
879 wfDebug( "Autoblock aborted by hook.\n" );
883 # It's okay to autoblock. Go ahead and insert/update the block...
885 # Do not add a *new* block if the IP is already blocked.
886 $ipblock = self
::newFromTarget( $autoblockIP );
888 # Check if the block is an autoblock and would exceed the user block
889 # if renewed. If so, do nothing, otherwise prolong the block time...
890 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
891 $this->mExpiry
> self
::getAutoblockExpiry( $ipblock->mTimestamp
)
893 # Reset block timestamp to now and its expiry to
894 # $wgAutoblockExpiry in the future
895 $ipblock->updateTimestamp();
900 # Make a new block object with the desired properties.
901 $autoblock = new Block
;
902 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
903 $autoblock->setTarget( $autoblockIP );
904 $autoblock->setBlocker( $this->getBlocker() );
905 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
906 ->inContentLanguage()->plain();
907 $timestamp = wfTimestampNow();
908 $autoblock->mTimestamp
= $timestamp;
909 $autoblock->mAuto
= 1;
910 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
911 # Continue suppressing the name if needed
912 $autoblock->mHideName
= $this->mHideName
;
913 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
914 $autoblock->mParentBlockId
= $this->mId
;
915 $autoblock->isSitewide( $this->isSitewide() );
916 $autoblock->setRestrictions( $this->getRestrictions() );
918 if ( $this->mExpiry
== 'infinity' ) {
919 # Original block was indefinite, start an autoblock now
920 $autoblock->mExpiry
= self
::getAutoblockExpiry( $timestamp );
922 # If the user is already blocked with an expiry date, we don't
923 # want to pile on top of that.
924 $autoblock->mExpiry
= min( $this->mExpiry
, self
::getAutoblockExpiry( $timestamp ) );
927 # Insert the block...
928 $status = $autoblock->insert();
935 * Check if a block has expired. Delete it if it is.
938 public function deleteIfExpired() {
939 if ( $this->isExpired() ) {
940 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
944 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
952 * Has the block expired?
955 public function isExpired() {
956 $timestamp = wfTimestampNow();
957 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
959 if ( !$this->mExpiry
) {
962 return $timestamp > $this->mExpiry
;
967 * Is the block address valid (i.e. not a null string?)
970 public function isValid() {
971 return $this->getTarget() != null;
975 * Update the timestamp on autoblocks.
977 public function updateTimestamp() {
978 if ( $this->mAuto
) {
979 $this->mTimestamp
= wfTimestamp();
980 $this->mExpiry
= self
::getAutoblockExpiry( $this->mTimestamp
);
982 $dbw = wfGetDB( DB_MASTER
);
983 $dbw->update( 'ipblocks',
985 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
986 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
989 'ipb_id' => $this->getId(),
997 * Get the IP address at the start of the range in Hex form
998 * @throws MWException
999 * @return string IP in Hex form
1001 public function getRangeStart() {
1002 switch ( $this->type
) {
1003 case self
::TYPE_USER
:
1006 return IP
::toHex( $this->target
);
1007 case self
::TYPE_RANGE
:
1008 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
1011 throw new MWException( "Block with invalid type" );
1016 * Get the IP address at the end of the range in Hex form
1017 * @throws MWException
1018 * @return string IP in Hex form
1020 public function getRangeEnd() {
1021 switch ( $this->type
) {
1022 case self
::TYPE_USER
:
1025 return IP
::toHex( $this->target
);
1026 case self
::TYPE_RANGE
:
1027 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
1030 throw new MWException( "Block with invalid type" );
1035 * Get the user id of the blocking sysop
1037 * @return int (0 for foreign users)
1039 public function getBy() {
1040 $blocker = $this->getBlocker();
1041 return ( $blocker instanceof User
)
1047 * Get the username of the blocking sysop
1051 public function getByName() {
1052 $blocker = $this->getBlocker();
1053 return ( $blocker instanceof User
)
1054 ?
$blocker->getName()
1055 : (string)$blocker; // username
1062 public function getId() {
1069 * @param int $blockId
1072 private function setId( $blockId ) {
1073 $this->mId
= (int)$blockId;
1075 if ( is_array( $this->restrictions
) ) {
1076 $this->restrictions
= BlockRestriction
::setBlockId( $blockId, $this->restrictions
);
1083 * Get the system block type, if any
1085 * @return string|null
1087 public function getSystemBlockType() {
1088 return $this->systemBlockType
;
1092 * Get/set a flag determining whether the master is used for reads
1094 * @param bool|null $x
1097 public function fromMaster( $x = null ) {
1098 return wfSetVar( $this->mFromMaster
, $x );
1102 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1103 * @param bool|null $x
1106 public function isHardblock( $x = null ) {
1107 wfSetVar( $this->isHardblock
, $x );
1109 # You can't *not* hardblock a user
1110 return $this->getType() == self
::TYPE_USER
1112 : $this->isHardblock
;
1116 * @param null|bool $x
1119 public function isAutoblocking( $x = null ) {
1120 wfSetVar( $this->isAutoblocking
, $x );
1122 # You can't put an autoblock on an IP or range as we don't have any history to
1123 # look over to get more IPs from
1124 return $this->getType() == self
::TYPE_USER
1125 ?
$this->isAutoblocking
1130 * Indicates that the block is a sitewide block. This means the user is
1131 * prohibited from editing any page on the site (other than their own talk
1134 * @param null|bool $x
1137 public function isSitewide( $x = null ) {
1138 return wfSetVar( $this->isSitewide
, $x );
1142 * Get/set whether the Block prevents a given action
1144 * @param string $action Action to check
1145 * @param bool|null $x Value for set, or null to just get value
1146 * @return bool|null Null for unrecognized rights.
1148 public function prevents( $action, $x = null ) {
1149 $config = RequestContext
::getMain()->getConfig();
1150 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1151 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1154 switch ( $action ) {
1156 # For now... <evil laugh>
1159 case 'createaccount':
1160 $res = wfSetVar( $this->mCreateAccount
, $x );
1163 $res = wfSetVar( $this->mBlockEmail
, $x );
1166 // Until T6995 is completed
1167 $res = $this->isSitewide();
1169 case 'editownusertalk':
1170 $res = wfSetVar( $this->mDisableUsertalk
, $x );
1171 // edit own user talk can be disabled by config
1172 if ( !$blockAllowsUTEdit ) {
1180 if ( !$res && $blockDisablesLogin ) {
1181 // If a block would disable login, then it should
1182 // prevent any action that all users cannot do
1184 $res = $anon->isAllowed( $action ) ?
$res : true;
1191 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1192 * @return string Text is escaped
1194 public function getRedactedName() {
1195 if ( $this->mAuto
) {
1196 return Html
::rawElement(
1198 [ 'class' => 'mw-autoblockid' ],
1199 wfMessage( 'autoblockid', $this->mId
)
1202 return htmlspecialchars( $this->getTarget() );
1207 * Get a timestamp of the expiry for autoblocks
1209 * @param string|int $timestamp
1212 public static function getAutoblockExpiry( $timestamp ) {
1213 global $wgAutoblockExpiry;
1215 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1219 * Purge expired blocks from the ipblocks table
1221 public static function purgeExpired() {
1222 if ( wfReadOnly() ) {
1226 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1227 wfGetDB( DB_MASTER
),
1229 function ( IDatabase
$dbw, $fname ) {
1230 $ids = $dbw->selectFieldValues( 'ipblocks',
1232 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1236 BlockRestriction
::deleteByBlockId( $ids );
1237 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1244 * Given a target and the target's type, get an existing Block object if possible.
1245 * @param string|User|int $specificTarget A block target, which may be one of several types:
1246 * * A user to block, in which case $target will be a User
1247 * * An IP to block, in which case $target will be a User generated by using
1248 * User::newFromName( $ip, false ) to turn off name validation
1249 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1250 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1252 * Calling this with a user, IP address or range will not select autoblocks, and will
1253 * only select a block where the targets match exactly (so looking for blocks on
1254 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1255 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1256 * affects that target (so for an IP address, get ranges containing that IP; and also
1257 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1258 * @param bool $fromMaster Whether to use the DB_MASTER database
1259 * @return Block|null (null if no relevant block could be found). The target and type
1260 * of the returned Block will refer to the actual block which was found, which might
1261 * not be the same as the target you gave if you used $vagueTarget!
1263 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1264 list( $target, $type ) = self
::parseTarget( $specificTarget );
1265 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1266 return self
::newFromID( $target );
1268 } elseif ( $target === null && $vagueTarget == '' ) {
1269 # We're not going to find anything useful here
1270 # Be aware that the == '' check is explicit, since empty values will be
1271 # passed by some callers (T31116)
1274 } elseif ( in_array(
1276 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1278 $block = new Block();
1279 $block->fromMaster( $fromMaster );
1281 if ( $type !== null ) {
1282 $block->setTarget( $target );
1285 if ( $block->newLoad( $vagueTarget ) ) {
1293 * Get all blocks that match any IP from an array of IP addresses
1295 * @param array $ipChain List of IPs (strings), usually retrieved from the
1296 * X-Forwarded-For header of the request
1297 * @param bool $isAnon Exclude anonymous-only blocks if false
1298 * @param bool $fromMaster Whether to query the master or replica DB
1299 * @return array Array of Blocks
1302 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1303 if ( !count( $ipChain ) ) {
1308 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1309 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1310 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1311 # necessarily trust the header given to us, make sure that we are only
1312 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1313 # Do not treat private IP spaces as special as it may be desirable for wikis
1314 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1315 if ( !IP
::isValid( $ipaddr ) ) {
1318 # Don't check trusted IPs (includes local squids which will be in every request)
1319 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1322 # Check both the original IP (to check against single blocks), as well as build
1323 # the clause to check for rangeblocks for the given IP.
1324 $conds['ipb_address'][] = $ipaddr;
1325 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1328 if ( !count( $conds ) ) {
1332 if ( $fromMaster ) {
1333 $db = wfGetDB( DB_MASTER
);
1335 $db = wfGetDB( DB_REPLICA
);
1337 $conds = $db->makeList( $conds, LIST_OR
);
1339 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1341 $blockQuery = self
::getQueryInfo();
1342 $rows = $db->select(
1343 $blockQuery['tables'],
1344 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1348 $blockQuery['joins']
1352 foreach ( $rows as $row ) {
1353 $block = self
::newFromRow( $row );
1354 if ( !$block->isExpired() ) {
1363 * From a list of multiple blocks, find the most exact and strongest Block.
1365 * The logic for finding the "best" block is:
1366 * - Blocks that match the block's target IP are preferred over ones in a range
1367 * - Hardblocks are chosen over softblocks that prevent account creation
1368 * - Softblocks that prevent account creation are chosen over other softblocks
1369 * - Other softblocks are chosen over autoblocks
1370 * - If there are multiple exact or range blocks at the same level, the one chosen
1372 * This should be used when $blocks where retrieved from the user's IP address
1373 * and $ipChain is populated from the same IP address information.
1375 * @param array $blocks Array of Block objects
1376 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1377 * a block is to the server, and if a block matches exactly, or is in a range.
1378 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1380 * @throws MWException
1381 * @return Block|null The "best" block from the list
1383 public static function chooseBlock( array $blocks, array $ipChain ) {
1384 if ( !count( $blocks ) ) {
1386 } elseif ( count( $blocks ) == 1 ) {
1390 // Sort hard blocks before soft ones and secondarily sort blocks
1391 // that disable account creation before those that don't.
1392 usort( $blocks, function ( Block
$a, Block
$b ) {
1393 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1394 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1395 return strcmp( $bWeight, $aWeight ); // highest weight first
1398 $blocksListExact = [
1400 'disable_create' => false,
1404 $blocksListRange = [
1406 'disable_create' => false,
1410 $ipChain = array_reverse( $ipChain );
1412 /** @var Block $block */
1413 foreach ( $blocks as $block ) {
1414 // Stop searching if we have already have a "better" block. This
1415 // is why the order of the blocks matters
1416 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1418 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1422 foreach ( $ipChain as $checkip ) {
1423 $checkipHex = IP
::toHex( $checkip );
1424 if ( (string)$block->getTarget() === $checkip ) {
1425 if ( $block->isHardblock() ) {
1426 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1427 } elseif ( $block->prevents( 'createaccount' ) ) {
1428 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1429 } elseif ( $block->mAuto
) {
1430 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1432 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1434 // We found closest exact match in the ip list, so go to the next Block
1436 } elseif ( array_filter( $blocksListExact ) == []
1437 && $block->getRangeStart() <= $checkipHex
1438 && $block->getRangeEnd() >= $checkipHex
1440 if ( $block->isHardblock() ) {
1441 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1442 } elseif ( $block->prevents( 'createaccount' ) ) {
1443 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1444 } elseif ( $block->mAuto
) {
1445 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1447 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1454 if ( array_filter( $blocksListExact ) == [] ) {
1455 $blocksList = &$blocksListRange;
1457 $blocksList = &$blocksListExact;
1460 $chosenBlock = null;
1461 if ( $blocksList['hard'] ) {
1462 $chosenBlock = $blocksList['hard'];
1463 } elseif ( $blocksList['disable_create'] ) {
1464 $chosenBlock = $blocksList['disable_create'];
1465 } elseif ( $blocksList['other'] ) {
1466 $chosenBlock = $blocksList['other'];
1467 } elseif ( $blocksList['auto'] ) {
1468 $chosenBlock = $blocksList['auto'];
1470 throw new MWException( "Proxy block found, but couldn't be classified." );
1473 return $chosenBlock;
1477 * From an existing Block, get the target and the type of target.
1478 * Note that, except for null, it is always safe to treat the target
1479 * as a string; for User objects this will return User::__toString()
1480 * which in turn gives User::getName().
1482 * @param string|int|User|null $target
1483 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1485 public static function parseTarget( $target ) {
1486 # We may have been through this before
1487 if ( $target instanceof User
) {
1488 if ( IP
::isValid( $target->getName() ) ) {
1489 return [ $target, self
::TYPE_IP
];
1491 return [ $target, self
::TYPE_USER
];
1493 } elseif ( $target === null ) {
1494 return [ null, null ];
1497 $target = trim( $target );
1499 if ( IP
::isValid( $target ) ) {
1500 # We can still create a User if it's an IP address, but we need to turn
1501 # off validation checking (which would exclude IP addresses)
1503 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1507 } elseif ( IP
::isValidRange( $target ) ) {
1508 # Can't create a User from an IP range
1509 return [ IP
::sanitizeRange( $target ), self
::TYPE_RANGE
];
1512 # Consider the possibility that this is not a username at all
1513 # but actually an old subpage (T31797)
1514 if ( strpos( $target, '/' ) !== false ) {
1515 # An old subpage, drill down to the user behind it
1516 $target = explode( '/', $target )[0];
1519 $userObj = User
::newFromName( $target );
1520 if ( $userObj instanceof User
) {
1521 # Note that since numbers are valid usernames, a $target of "12345" will be
1522 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1523 # since hash characters are not valid in usernames or titles generally.
1524 return [ $userObj, self
::TYPE_USER
];
1526 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1527 # Autoblock reference in the form "#12345"
1528 return [ substr( $target, 1 ), self
::TYPE_AUTO
];
1532 return [ null, null ];
1537 * Get the type of target for this particular block
1538 * @return int Block::TYPE_ constant, will never be TYPE_ID
1540 public function getType() {
1547 * Get the target and target type for this particular Block. Note that for autoblocks,
1548 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1549 * in this situation.
1550 * @return array [ User|String, Block::TYPE_ constant ]
1551 * @todo FIXME: This should be an integral part of the Block member variables
1553 public function getTargetAndType() {
1554 return [ $this->getTarget(), $this->getType() ];
1558 * Get the target for this particular Block. Note that for autoblocks,
1559 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1560 * in this situation.
1561 * @return User|string
1563 public function getTarget() {
1564 return $this->target
;
1570 * @return mixed|string
1572 public function getExpiry() {
1573 return $this->mExpiry
;
1577 * Set the target for this block, and update $this->type accordingly
1578 * @param mixed $target
1580 public function setTarget( $target ) {
1581 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1585 * Get the user who implemented this block
1586 * @return User User object. May name a foreign user.
1588 public function getBlocker() {
1589 return $this->blocker
;
1593 * Set the user who implemented (or will implement) this block
1594 * @param User|string $user Local User object or username string
1596 public function setBlocker( $user ) {
1597 if ( is_string( $user ) ) {
1598 $user = User
::newFromName( $user, false );
1601 if ( $user->isAnon() && User
::isUsableName( $user->getName() ) ) {
1602 throw new InvalidArgumentException(
1603 'Blocker must be a local user or a name that cannot be a local user'
1607 $this->blocker
= $user;
1611 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1612 * the same as the block's, to a maximum of 24 hours.
1616 * @param WebResponse $response The response on which to set the cookie.
1618 public function setCookie( WebResponse
$response ) {
1619 // Calculate the default expiry time.
1620 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1622 // Use the Block's expiry time only if it's less than the default.
1623 $expiryTime = $this->getExpiry();
1624 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1625 $expiryTime = $maxExpiryTime;
1628 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1629 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1630 $cookieOptions = [ 'httpOnly' => false ];
1631 $cookieValue = $this->getCookieValue();
1632 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1636 * Unset the 'BlockID' cookie.
1640 * @param WebResponse $response The response on which to unset the cookie.
1642 public static function clearCookie( WebResponse
$response ) {
1643 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1647 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1648 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1653 * @return string The block ID, probably concatenated with "!" and the HMAC.
1655 public function getCookieValue() {
1656 $config = RequestContext
::getMain()->getConfig();
1657 $id = $this->getId();
1658 $secretKey = $config->get( 'SecretKey' );
1659 if ( !$secretKey ) {
1660 // If there's no secret key, don't append a HMAC.
1663 $hmac = MWCryptHash
::hmac( $id, $secretKey, false );
1664 $cookieValue = $id . '!' . $hmac;
1665 return $cookieValue;
1669 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1670 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1674 * @param string $cookieValue The string in which to find the ID.
1676 * @return int|null The block ID, or null if the HMAC is present and invalid.
1678 public static function getIdFromCookieValue( $cookieValue ) {
1679 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1680 $bangPos = strpos( $cookieValue, '!' );
1681 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
1682 // Get the site-wide secret key.
1683 $config = RequestContext
::getMain()->getConfig();
1684 $secretKey = $config->get( 'SecretKey' );
1685 if ( !$secretKey ) {
1686 // If there's no secret key, just use the ID as given.
1689 $storedHmac = substr( $cookieValue, $bangPos +
1 );
1690 $calculatedHmac = MWCryptHash
::hmac( $id, $secretKey, false );
1691 if ( $calculatedHmac === $storedHmac ) {
1699 * Get the key and parameters for the corresponding error message.
1702 * @param IContextSource $context
1705 public function getPermissionsError( IContextSource
$context ) {
1706 $params = $this->getBlockErrorParams( $context );
1708 $msg = 'blockedtext';
1709 if ( $this->getSystemBlockType() !== null ) {
1710 $msg = 'systemblockedtext';
1711 } elseif ( $this->mAuto
) {
1712 $msg = 'autoblockedtext';
1713 } elseif ( !$this->isSitewide() ) {
1714 $msg = 'blockedtext-partial';
1717 array_unshift( $params, $msg );
1723 * Get block information used in different block error messages
1725 * @param IContextSource $context
1728 public function getBlockErrorParams( IContextSource
$context ) {
1729 $blocker = $this->getBlocker();
1730 if ( $blocker instanceof User
) { // local user
1731 $blockerUserpage = $blocker->getUserPage();
1732 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1733 } else { // foreign user
1737 $reason = $this->mReason
;
1738 if ( $reason == '' ) {
1739 $reason = $context->msg( 'blockednoreason' )->text();
1742 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1743 * This could be a username, an IP range, or a single IP. */
1744 $intended = $this->getTarget();
1745 $systemBlockType = $this->getSystemBlockType();
1746 $lang = $context->getLanguage();
1751 $context->getRequest()->getIP(),
1753 $systemBlockType ??
$this->getId(),
1754 $lang->formatExpiry( $this->mExpiry
),
1756 $lang->userTimeAndDate( $this->mTimestamp
, $context->getUser() ),
1763 * Getting the restrictions will perform a database query if the restrictions
1764 * are not already loaded.
1766 * @return Restriction[]
1768 public function getRestrictions() {
1769 if ( $this->restrictions
=== null ) {
1770 // If the block id has not been set, then do not attempt to load the
1772 if ( !$this->mId
) {
1775 $this->restrictions
= BlockRestriction
::loadByBlockId( $this->mId
);
1778 return $this->restrictions
;
1784 * @param Restriction[] $restrictions
1788 public function setRestrictions( array $restrictions ) {
1789 $this->restrictions
= array_filter( $restrictions, function ( $restriction ) {
1790 return $restriction instanceof Restriction
;
1797 * Checks if a block prevents an edit on a given article
1799 * @param \Title $title
1802 public function preventsEdit( \Title
$title ) {
1803 $blocked = $this->isSitewide();
1805 // user talk page has it's own rules
1806 // This check happens before partial blocks because the flag
1807 // to allow user to edit their user talk page could be
1808 // overwritten by a partial block restriction (E.g. user talk namespace)
1809 $user = $this->getTarget();
1810 if ( $title->equals( $user->getTalkPage() ) ) {
1811 $blocked = $this->prevents( 'editownusertalk' );
1814 if ( !$this->isSitewide() ) {
1815 $restrictions = $this->getRestrictions();
1816 foreach ( $restrictions as $restriction ) {
1817 if ( $restriction->matches( $title ) ) {