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\Block\Restriction\NamespaceRestriction
;
28 use MediaWiki\Block\Restriction\PageRestriction
;
29 use MediaWiki\MediaWikiServices
;
48 public $mParentBlockId;
60 private $mDisableUsertalk;
63 private $mCreateAccount;
65 /** @var User|string */
68 /** @var int Hack for foreign blocking (CentralAuth) */
69 private $forcedTargetID;
72 * @var int Block::TYPE_ constant. After the block has been loaded
73 * from the database, this can only be USER, IP or RANGE.
84 private $isAutoblocking;
86 /** @var string|null */
87 private $systemBlockType;
92 /** @var Restriction[] */
93 private $restrictions;
103 * Create a new block with specified parameters on a user, IP or IP range.
105 * @param array $options Parameters of the block:
106 * address string|User Target user name, User object, IP address or IP range
107 * user int Override target user ID (for foreign users)
108 * by int User ID of the blocker
109 * reason string Reason of the block
110 * timestamp string The time at which the block comes into effect
111 * auto bool Is this an automatic block?
112 * expiry string Timestamp of expiration of the block or 'infinity'
113 * anonOnly bool Only disallow anonymous actions
114 * createAccount bool Disallow creation of new accounts
115 * enableAutoblock bool Enable automatic blocking
116 * hideName bool Hide the target user name
117 * blockEmail bool Disallow sending emails
118 * allowUsertalk bool Allow the target to edit its own talk page
119 * byText string Username of the blocker (for foreign users)
120 * systemBlock string Indicate that this block is automatically
121 * created by MediaWiki rather than being stored
122 * in the database. Value is a string to return
123 * from self::getSystemBlockType().
125 * @since 1.26 accepts $options array instead of individual parameters; order
126 * of parameters above reflects the original order
128 function __construct( $options = [] ) {
138 'createAccount' => false,
139 'enableAutoblock' => false,
141 'blockEmail' => false,
142 'allowUsertalk' => false,
144 'systemBlock' => null,
148 if ( func_num_args() > 1 ||
!is_array( $options ) ) {
149 $options = array_combine(
150 array_slice( array_keys( $defaults ), 0, func_num_args() ),
153 wfDeprecated( __METHOD__
. ' with multiple arguments', '1.26' );
156 $options +
= $defaults;
158 $this->setTarget( $options['address'] );
160 if ( $this->target
instanceof User
&& $options['user'] ) {
161 # Needed for foreign users
162 $this->forcedTargetID
= $options['user'];
165 if ( $options['by'] ) {
167 $this->setBlocker( User
::newFromId( $options['by'] ) );
170 $this->setBlocker( $options['byText'] );
173 $this->mReason
= $options['reason'];
174 $this->mTimestamp
= wfTimestamp( TS_MW
, $options['timestamp'] );
175 $this->mExpiry
= wfGetDB( DB_REPLICA
)->decodeExpiry( $options['expiry'] );
178 $this->mAuto
= (bool)$options['auto'];
179 $this->mHideName
= (bool)$options['hideName'];
180 $this->isHardblock( !$options['anonOnly'] );
181 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
182 $this->isSitewide( (bool)$options['sitewide'] );
184 # Prevention measures
185 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
186 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
187 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
189 $this->mFromMaster
= false;
190 $this->systemBlockType
= $options['systemBlock'];
194 * Load a block from the block id.
196 * @param int $id Block id to search for
199 public static function newFromID( $id ) {
200 $dbr = wfGetDB( DB_REPLICA
);
201 $blockQuery = self
::getQueryInfo();
202 $res = $dbr->selectRow(
203 $blockQuery['tables'],
204 $blockQuery['fields'],
211 return self
::newFromRow( $res );
218 * Return the list of ipblocks fields that should be selected to create
220 * @deprecated since 1.31, use self::getQueryInfo() instead.
223 public static function selectFields() {
224 global $wgActorTableSchemaMigrationStage;
226 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
227 // If code is using this instead of self::getQueryInfo(), there's a
228 // decent chance it's going to try to directly access
229 // $row->ipb_by or $row->ipb_by_text and we can't give it
230 // useful values here once those aren't being used anymore.
231 throw new BadMethodCallException(
232 'Cannot use ' . __METHOD__
233 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
237 wfDeprecated( __METHOD__
, '1.31' );
243 'ipb_by_actor' => 'NULL',
247 'ipb_create_account',
248 'ipb_enable_autoblock',
252 'ipb_allow_usertalk',
253 'ipb_parent_block_id',
255 ] + CommentStore
::getStore()->getFields( 'ipb_reason' );
259 * Return the tables, fields, and join conditions to be selected to create
260 * a new block object.
262 * @return array With three keys:
263 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
264 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
265 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
267 public static function getQueryInfo() {
268 $commentQuery = CommentStore
::getStore()->getJoin( 'ipb_reason' );
269 $actorQuery = ActorMigration
::newMigration()->getJoin( 'ipb_by' );
271 'tables' => [ 'ipblocks' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
278 'ipb_create_account',
279 'ipb_enable_autoblock',
283 'ipb_allow_usertalk',
284 'ipb_parent_block_id',
286 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
287 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
292 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
293 * the blocking user or the block timestamp, only things which affect the blocked user
295 * @param Block $block
299 public function equals( Block
$block ) {
301 (string)$this->target
== (string)$block->target
302 && $this->type
== $block->type
303 && $this->mAuto
== $block->mAuto
304 && $this->isHardblock() == $block->isHardblock()
305 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
306 && $this->mExpiry
== $block->mExpiry
307 && $this->isAutoblocking() == $block->isAutoblocking()
308 && $this->mHideName
== $block->mHideName
309 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
310 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
311 && $this->mReason
== $block->mReason
312 && $this->isSitewide() == $block->isSitewide()
313 // Block::getRestrictions() may perform a database query, so keep it at
315 && BlockRestriction
::equals( $this->getRestrictions(), $block->getRestrictions() )
320 * Load a block from the database which affects the already-set $this->target:
321 * 1) A block directly on the given user or IP
322 * 2) A rangeblock encompassing the given IP (smallest first)
323 * 3) An autoblock on the given IP
324 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
325 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
326 * @throws MWException
327 * @return bool Whether a relevant block was found
329 protected function newLoad( $vagueTarget = null ) {
330 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_REPLICA
);
332 if ( $this->type
!== null ) {
334 'ipb_address' => [ (string)$this->target
],
337 $conds = [ 'ipb_address' => [] ];
340 # Be aware that the != '' check is explicit, since empty values will be
341 # passed by some callers (T31116)
342 if ( $vagueTarget != '' ) {
343 list( $target, $type ) = self
::parseTarget( $vagueTarget );
345 case self
::TYPE_USER
:
346 # Slightly weird, but who are we to argue?
347 $conds['ipb_address'][] = (string)$target;
351 $conds['ipb_address'][] = (string)$target;
352 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
353 $conds = $db->makeList( $conds, LIST_OR
);
356 case self
::TYPE_RANGE
:
357 list( $start, $end ) = IP
::parseRange( $target );
358 $conds['ipb_address'][] = (string)$target;
359 $conds[] = self
::getRangeCond( $start, $end );
360 $conds = $db->makeList( $conds, LIST_OR
);
364 throw new MWException( "Tried to load block with invalid type" );
368 $blockQuery = self
::getQueryInfo();
370 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
373 # This result could contain a block on the user, a block on the IP, and a russian-doll
374 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
377 # Lower will be better
378 $bestBlockScore = 100;
380 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
381 $bestBlockPreventsEdit = null;
383 foreach ( $res as $row ) {
384 $block = self
::newFromRow( $row );
386 # Don't use expired blocks
387 if ( $block->isExpired() ) {
391 # Don't use anon only blocks on users
392 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
396 if ( $block->getType() == self
::TYPE_RANGE
) {
397 # This is the number of bits that are allowed to vary in the block, give
398 # or take some floating point errors
399 $end = Wikimedia\base_convert
( $block->getRangeEnd(), 16, 10 );
400 $start = Wikimedia\base_convert
( $block->getRangeStart(), 16, 10 );
401 $size = log( $end - $start +
1, 2 );
403 # This has the nice property that a /32 block is ranked equally with a
404 # single-IP block, which is exactly what it is...
405 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
408 $score = $block->getType();
411 if ( $score < $bestBlockScore ) {
412 $bestBlockScore = $score;
414 $bestBlockPreventsEdit = $block->prevents( 'edit' );
418 if ( $bestRow !== null ) {
419 $this->initFromRow( $bestRow );
420 $this->prevents( 'edit', $bestBlockPreventsEdit );
428 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
429 * @param string $start Hexadecimal IP representation
430 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
433 public static function getRangeCond( $start, $end = null ) {
434 if ( $end === null ) {
437 # Per T16634, we want to include relevant active rangeblocks; for
438 # rangeblocks, we want to include larger ranges which enclose the given
439 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
440 # so we can improve performance by filtering on a LIKE clause
441 $chunk = self
::getIpFragment( $start );
442 $dbr = wfGetDB( DB_REPLICA
);
443 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
445 # Fairly hard to make a malicious SQL statement out of hex characters,
446 # but stranger things have happened...
447 $safeStart = $dbr->addQuotes( $start );
448 $safeEnd = $dbr->addQuotes( $end );
450 return $dbr->makeList(
452 "ipb_range_start $like",
453 "ipb_range_start <= $safeStart",
454 "ipb_range_end >= $safeEnd",
461 * Get the component of an IP address which is certain to be the same between an IP
462 * address and a rangeblock containing that IP address.
463 * @param string $hex Hexadecimal IP representation
466 protected static function getIpFragment( $hex ) {
467 global $wgBlockCIDRLimit;
468 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
469 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
471 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
476 * Given a database row from the ipblocks table, initialize
478 * @param stdClass $row A row from the ipblocks table
480 protected function initFromRow( $row ) {
481 $this->setTarget( $row->ipb_address
);
482 $this->setBlocker( User
::newFromAnyId(
483 $row->ipb_by
, $row->ipb_by_text
, $row->ipb_by_actor ??
null
486 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
487 $this->mAuto
= $row->ipb_auto
;
488 $this->mHideName
= $row->ipb_deleted
;
489 $this->mId
= (int)$row->ipb_id
;
490 $this->mParentBlockId
= $row->ipb_parent_block_id
;
492 // I wish I didn't have to do this
493 $db = wfGetDB( DB_REPLICA
);
494 $this->mExpiry
= $db->decodeExpiry( $row->ipb_expiry
);
495 $this->mReason
= CommentStore
::getStore()
496 // Legacy because $row may have come from self::selectFields()
497 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
;
499 $this->isHardblock( !$row->ipb_anon_only
);
500 $this->isAutoblocking( $row->ipb_enable_autoblock
);
501 $this->isSitewide( (bool)$row->ipb_sitewide
);
503 $this->prevents( 'createaccount', $row->ipb_create_account
);
504 $this->prevents( 'sendemail', $row->ipb_block_email
);
505 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
509 * Create a new Block object from a database row
510 * @param stdClass $row Row from the ipblocks table
513 public static function newFromRow( $row ) {
515 $block->initFromRow( $row );
520 * Delete the row from the IP blocks table.
522 * @throws MWException
525 public function delete() {
526 if ( wfReadOnly() ) {
530 if ( !$this->getId() ) {
531 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
534 $dbw = wfGetDB( DB_MASTER
);
536 BlockRestriction
::deleteByParentBlockId( $this->getId() );
537 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
539 BlockRestriction
::deleteByBlockId( $this->getId() );
540 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
542 return $dbw->affectedRows() > 0;
546 * Insert a block into the block table. Will fail if there is a conflicting
547 * block (same name and options) already in the database.
549 * @param IDatabase|null $dbw If you have one available
550 * @return bool|array False on failure, assoc array on success:
551 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
553 public function insert( $dbw = null ) {
554 global $wgBlockDisablesLogin;
556 if ( $this->getSystemBlockType() !== null ) {
557 throw new MWException( 'Cannot insert a system block into the database' );
559 if ( !$this->getBlocker() ||
$this->getBlocker()->getName() === '' ) {
560 throw new MWException( 'Cannot insert a block without a blocker set' );
563 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
565 if ( $dbw === null ) {
566 $dbw = wfGetDB( DB_MASTER
);
569 self
::purgeExpired();
571 $row = $this->getDatabaseArray( $dbw );
573 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
574 $affected = $dbw->affectedRows();
576 $this->setId( $dbw->insertId() );
577 if ( $this->restrictions
) {
578 BlockRestriction
::insert( $this->restrictions
);
582 # Don't collide with expired blocks.
583 # Do this after trying to insert to avoid locking.
585 # T96428: The ipb_address index uses a prefix on a field, so
586 # use a standard SELECT + DELETE to avoid annoying gap locks.
587 $ids = $dbw->selectFieldValues( 'ipblocks',
590 'ipb_address' => $row['ipb_address'],
591 'ipb_user' => $row['ipb_user'],
592 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
597 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
598 BlockRestriction
::deleteByBlockId( $ids );
599 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
600 $affected = $dbw->affectedRows();
601 $this->setId( $dbw->insertId() );
602 if ( $this->restrictions
) {
603 BlockRestriction
::insert( $this->restrictions
);
609 $auto_ipd_ids = $this->doRetroactiveAutoblock();
611 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
612 // Change user login token to force them to be logged out.
613 $this->target
->setToken();
614 $this->target
->saveSettings();
617 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
624 * Update a block in the DB with new parameters.
625 * The ID field needs to be loaded first.
627 * @return bool|array False on failure, array on success:
628 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
630 public function update() {
631 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
632 $dbw = wfGetDB( DB_MASTER
);
634 $dbw->startAtomic( __METHOD__
);
636 $result = $dbw->update(
638 $this->getDatabaseArray( $dbw ),
639 [ 'ipb_id' => $this->getId() ],
643 // Only update the restrictions if they have been modified.
644 if ( $this->restrictions
!== null ) {
645 // An empty array should remove all of the restrictions.
646 if ( empty( $this->restrictions
) ) {
647 $success = BlockRestriction
::deleteByBlockId( $this->getId() );
649 $success = BlockRestriction
::update( $this->restrictions
);
651 // Update the result. The first false is the result, otherwise, true.
652 $result = $result && $success;
655 if ( $this->isAutoblocking() ) {
656 // update corresponding autoblock(s) (T50813)
659 $this->getAutoblockUpdateArray( $dbw ),
660 [ 'ipb_parent_block_id' => $this->getId() ],
664 // Only update the restrictions if they have been modified.
665 if ( $this->restrictions
!== null ) {
666 BlockRestriction
::updateByParentBlockId( $this->getId(), $this->restrictions
);
669 // autoblock no longer required, delete corresponding autoblock(s)
670 BlockRestriction
::deleteByParentBlockId( $this->getId() );
673 [ 'ipb_parent_block_id' => $this->getId() ],
678 $dbw->endAtomic( __METHOD__
);
681 $auto_ipd_ids = $this->doRetroactiveAutoblock();
682 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
689 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
690 * @param IDatabase $dbw
693 protected function getDatabaseArray( IDatabase
$dbw ) {
694 $expiry = $dbw->encodeExpiry( $this->mExpiry
);
696 if ( $this->forcedTargetID
) {
697 $uid = $this->forcedTargetID
;
699 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
703 'ipb_address' => (string)$this->target
,
705 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
706 'ipb_auto' => $this->mAuto
,
707 'ipb_anon_only' => !$this->isHardblock(),
708 'ipb_create_account' => $this->prevents( 'createaccount' ),
709 'ipb_enable_autoblock' => $this->isAutoblocking(),
710 'ipb_expiry' => $expiry,
711 'ipb_range_start' => $this->getRangeStart(),
712 'ipb_range_end' => $this->getRangeEnd(),
713 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
714 'ipb_block_email' => $this->prevents( 'sendemail' ),
715 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
716 'ipb_parent_block_id' => $this->mParentBlockId
,
717 'ipb_sitewide' => $this->isSitewide(),
718 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->mReason
)
719 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
725 * @param IDatabase $dbw
728 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
730 'ipb_create_account' => $this->prevents( 'createaccount' ),
731 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
732 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
733 'ipb_sitewide' => $this->isSitewide(),
734 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->mReason
)
735 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
739 * Retroactively autoblocks the last IP used by the user (if it is a user)
740 * blocked by this Block.
742 * @return array Block IDs of retroactive autoblocks made
744 protected function doRetroactiveAutoblock() {
746 # If autoblock is enabled, autoblock the LAST IP(s) used
747 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
748 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
750 $continue = Hooks
::run(
751 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
754 self
::defaultRetroactiveAutoblock( $this, $blockIds );
761 * Retroactively autoblocks the last IP used by the user (if it is a user)
762 * blocked by this Block. This will use the recentchanges table.
764 * @param Block $block
765 * @param array &$blockIds
767 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
770 // No IPs are in recentchanges table, so nothing to select
771 if ( !$wgPutIPinRC ) {
775 // Autoblocks only apply to TYPE_USER
776 if ( $block->getType() !== self
::TYPE_USER
) {
779 $target = $block->getTarget(); // TYPE_USER => always a User object
781 $dbr = wfGetDB( DB_REPLICA
);
782 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
784 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
786 // Just the last IP used.
787 $options['LIMIT'] = 1;
790 [ 'recentchanges' ] +
$rcQuery['tables'],
798 if ( !$res->numRows() ) {
799 # No results, don't autoblock anything
800 wfDebug( "No IP found to retroactively autoblock\n" );
802 foreach ( $res as $row ) {
804 $id = $block->doAutoblock( $row->rc_ip
);
814 * Checks whether a given IP is on the autoblock whitelist.
815 * TODO: this probably belongs somewhere else, but not sure where...
817 * @param string $ip The IP to check
820 public static function isWhitelistedFromAutoblocks( $ip ) {
821 // Try to get the autoblock_whitelist from the cache, as it's faster
822 // than getting the msg raw and explode()'ing it.
823 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
824 $lines = $cache->getWithSetCallback(
825 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
827 function ( $curValue, &$ttl, array &$setOpts ) {
828 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
830 return explode( "\n",
831 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
835 wfDebug( "Checking the autoblock whitelist..\n" );
837 foreach ( $lines as $line ) {
839 if ( substr( $line, 0, 1 ) !== '*' ) {
843 $wlEntry = substr( $line, 1 );
844 $wlEntry = trim( $wlEntry );
846 wfDebug( "Checking $ip against $wlEntry..." );
848 # Is the IP in this range?
849 if ( IP
::isInRange( $ip, $wlEntry ) ) {
850 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
853 wfDebug( " No match\n" );
861 * Autoblocks the given IP, referring to this Block.
863 * @param string $autoblockIP The IP to autoblock.
864 * @return int|bool Block ID if an autoblock was inserted, false if not.
866 public function doAutoblock( $autoblockIP ) {
867 # If autoblocks are disabled, go away.
868 if ( !$this->isAutoblocking() ) {
872 # Don't autoblock for system blocks
873 if ( $this->getSystemBlockType() !== null ) {
874 throw new MWException( 'Cannot autoblock from a system block' );
877 # Check for presence on the autoblock whitelist.
878 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
882 // Avoid PHP 7.1 warning of passing $this by reference
884 # Allow hooks to cancel the autoblock.
885 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
886 wfDebug( "Autoblock aborted by hook.\n" );
890 # It's okay to autoblock. Go ahead and insert/update the block...
892 # Do not add a *new* block if the IP is already blocked.
893 $ipblock = self
::newFromTarget( $autoblockIP );
895 # Check if the block is an autoblock and would exceed the user block
896 # if renewed. If so, do nothing, otherwise prolong the block time...
897 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
898 $this->mExpiry
> self
::getAutoblockExpiry( $ipblock->mTimestamp
)
900 # Reset block timestamp to now and its expiry to
901 # $wgAutoblockExpiry in the future
902 $ipblock->updateTimestamp();
907 # Make a new block object with the desired properties.
908 $autoblock = new Block
;
909 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
910 $autoblock->setTarget( $autoblockIP );
911 $autoblock->setBlocker( $this->getBlocker() );
912 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
913 ->inContentLanguage()->plain();
914 $timestamp = wfTimestampNow();
915 $autoblock->mTimestamp
= $timestamp;
916 $autoblock->mAuto
= 1;
917 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
918 # Continue suppressing the name if needed
919 $autoblock->mHideName
= $this->mHideName
;
920 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
921 $autoblock->mParentBlockId
= $this->mId
;
922 $autoblock->isSitewide( $this->isSitewide() );
923 $autoblock->setRestrictions( $this->getRestrictions() );
925 if ( $this->mExpiry
== 'infinity' ) {
926 # Original block was indefinite, start an autoblock now
927 $autoblock->mExpiry
= self
::getAutoblockExpiry( $timestamp );
929 # If the user is already blocked with an expiry date, we don't
930 # want to pile on top of that.
931 $autoblock->mExpiry
= min( $this->mExpiry
, self
::getAutoblockExpiry( $timestamp ) );
934 # Insert the block...
935 $status = $autoblock->insert();
942 * Check if a block has expired. Delete it if it is.
945 public function deleteIfExpired() {
946 if ( $this->isExpired() ) {
947 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
951 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
959 * Has the block expired?
962 public function isExpired() {
963 $timestamp = wfTimestampNow();
964 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
966 if ( !$this->mExpiry
) {
969 return $timestamp > $this->mExpiry
;
974 * Is the block address valid (i.e. not a null string?)
977 public function isValid() {
978 return $this->getTarget() != null;
982 * Update the timestamp on autoblocks.
984 public function updateTimestamp() {
985 if ( $this->mAuto
) {
986 $this->mTimestamp
= wfTimestamp();
987 $this->mExpiry
= self
::getAutoblockExpiry( $this->mTimestamp
);
989 $dbw = wfGetDB( DB_MASTER
);
990 $dbw->update( 'ipblocks',
992 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
993 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
996 'ipb_id' => $this->getId(),
1004 * Get the IP address at the start of the range in Hex form
1005 * @throws MWException
1006 * @return string IP in Hex form
1008 public function getRangeStart() {
1009 switch ( $this->type
) {
1010 case self
::TYPE_USER
:
1013 return IP
::toHex( $this->target
);
1014 case self
::TYPE_RANGE
:
1015 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
1018 throw new MWException( "Block with invalid type" );
1023 * Get the IP address at the end of the range in Hex form
1024 * @throws MWException
1025 * @return string IP in Hex form
1027 public function getRangeEnd() {
1028 switch ( $this->type
) {
1029 case self
::TYPE_USER
:
1032 return IP
::toHex( $this->target
);
1033 case self
::TYPE_RANGE
:
1034 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
1037 throw new MWException( "Block with invalid type" );
1042 * Get the user id of the blocking sysop
1044 * @return int (0 for foreign users)
1046 public function getBy() {
1047 $blocker = $this->getBlocker();
1048 return ( $blocker instanceof User
)
1054 * Get the username of the blocking sysop
1058 public function getByName() {
1059 $blocker = $this->getBlocker();
1060 return ( $blocker instanceof User
)
1061 ?
$blocker->getName()
1062 : (string)$blocker; // username
1069 public function getId() {
1076 * @param int $blockId
1079 private function setId( $blockId ) {
1080 $this->mId
= (int)$blockId;
1082 if ( is_array( $this->restrictions
) ) {
1083 $this->restrictions
= BlockRestriction
::setBlockId( $blockId, $this->restrictions
);
1090 * Get the system block type, if any
1092 * @return string|null
1094 public function getSystemBlockType() {
1095 return $this->systemBlockType
;
1099 * Get/set a flag determining whether the master is used for reads
1101 * @param bool|null $x
1104 public function fromMaster( $x = null ) {
1105 return wfSetVar( $this->mFromMaster
, $x );
1109 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1110 * @param bool|null $x
1113 public function isHardblock( $x = null ) {
1114 wfSetVar( $this->isHardblock
, $x );
1116 # You can't *not* hardblock a user
1117 return $this->getType() == self
::TYPE_USER
1119 : $this->isHardblock
;
1123 * @param null|bool $x
1126 public function isAutoblocking( $x = null ) {
1127 wfSetVar( $this->isAutoblocking
, $x );
1129 # You can't put an autoblock on an IP or range as we don't have any history to
1130 # look over to get more IPs from
1131 return $this->getType() == self
::TYPE_USER
1132 ?
$this->isAutoblocking
1137 * Indicates that the block is a sitewide block. This means the user is
1138 * prohibited from editing any page on the site (other than their own talk
1142 * @param null|bool $x
1145 public function isSitewide( $x = null ) {
1146 return wfSetVar( $this->isSitewide
, $x );
1150 * Get/set whether the Block prevents a given action
1152 * @param string $action Action to check
1153 * @param bool|null $x Value for set, or null to just get value
1154 * @return bool|null Null for unrecognized rights.
1156 public function prevents( $action, $x = null ) {
1157 $config = RequestContext
::getMain()->getConfig();
1158 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1159 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1162 switch ( $action ) {
1164 # For now... <evil laugh>
1167 case 'createaccount':
1168 $res = wfSetVar( $this->mCreateAccount
, $x );
1171 $res = wfSetVar( $this->mBlockEmail
, $x );
1174 // Until T6995 is completed
1175 $res = $this->isSitewide();
1177 case 'editownusertalk':
1178 // NOTE: this check is not reliable on partial blocks
1179 // since partially blocked users are always allowed to edit
1180 // their own talk page unless a restriction exists on the
1181 // page or User_talk: namespace
1182 $res = wfSetVar( $this->mDisableUsertalk
, $x );
1184 // edit own user talk can be disabled by config
1185 if ( !$blockAllowsUTEdit ) {
1196 if ( !$res && $blockDisablesLogin ) {
1197 // If a block would disable login, then it should
1198 // prevent any action that all users cannot do
1200 $res = $anon->isAllowed( $action ) ?
$res : true;
1207 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1208 * @return string Text is escaped
1210 public function getRedactedName() {
1211 if ( $this->mAuto
) {
1212 return Html
::rawElement(
1214 [ 'class' => 'mw-autoblockid' ],
1215 wfMessage( 'autoblockid', $this->mId
)
1218 return htmlspecialchars( $this->getTarget() );
1223 * Get a timestamp of the expiry for autoblocks
1225 * @param string|int $timestamp
1228 public static function getAutoblockExpiry( $timestamp ) {
1229 global $wgAutoblockExpiry;
1231 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1235 * Purge expired blocks from the ipblocks table
1237 public static function purgeExpired() {
1238 if ( wfReadOnly() ) {
1242 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1243 wfGetDB( DB_MASTER
),
1245 function ( IDatabase
$dbw, $fname ) {
1246 $ids = $dbw->selectFieldValues( 'ipblocks',
1248 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1252 BlockRestriction
::deleteByBlockId( $ids );
1253 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1260 * Given a target and the target's type, get an existing Block object if possible.
1261 * @param string|User|int $specificTarget A block target, which may be one of several types:
1262 * * A user to block, in which case $target will be a User
1263 * * An IP to block, in which case $target will be a User generated by using
1264 * User::newFromName( $ip, false ) to turn off name validation
1265 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1266 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1268 * Calling this with a user, IP address or range will not select autoblocks, and will
1269 * only select a block where the targets match exactly (so looking for blocks on
1270 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1271 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1272 * affects that target (so for an IP address, get ranges containing that IP; and also
1273 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1274 * @param bool $fromMaster Whether to use the DB_MASTER database
1275 * @return Block|null (null if no relevant block could be found). The target and type
1276 * of the returned Block will refer to the actual block which was found, which might
1277 * not be the same as the target you gave if you used $vagueTarget!
1279 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1280 list( $target, $type ) = self
::parseTarget( $specificTarget );
1281 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1282 return self
::newFromID( $target );
1284 } elseif ( $target === null && $vagueTarget == '' ) {
1285 # We're not going to find anything useful here
1286 # Be aware that the == '' check is explicit, since empty values will be
1287 # passed by some callers (T31116)
1290 } elseif ( in_array(
1292 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1294 $block = new Block();
1295 $block->fromMaster( $fromMaster );
1297 if ( $type !== null ) {
1298 $block->setTarget( $target );
1301 if ( $block->newLoad( $vagueTarget ) ) {
1309 * Get all blocks that match any IP from an array of IP addresses
1311 * @param array $ipChain List of IPs (strings), usually retrieved from the
1312 * X-Forwarded-For header of the request
1313 * @param bool $isAnon Exclude anonymous-only blocks if false
1314 * @param bool $fromMaster Whether to query the master or replica DB
1315 * @return array Array of Blocks
1318 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1319 if ( $ipChain === [] ) {
1324 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1325 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1326 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1327 # necessarily trust the header given to us, make sure that we are only
1328 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1329 # Do not treat private IP spaces as special as it may be desirable for wikis
1330 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1331 if ( !IP
::isValid( $ipaddr ) ) {
1334 # Don't check trusted IPs (includes local squids which will be in every request)
1335 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1338 # Check both the original IP (to check against single blocks), as well as build
1339 # the clause to check for rangeblocks for the given IP.
1340 $conds['ipb_address'][] = $ipaddr;
1341 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1344 if ( $conds === [] ) {
1348 if ( $fromMaster ) {
1349 $db = wfGetDB( DB_MASTER
);
1351 $db = wfGetDB( DB_REPLICA
);
1353 $conds = $db->makeList( $conds, LIST_OR
);
1355 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1357 $blockQuery = self
::getQueryInfo();
1358 $rows = $db->select(
1359 $blockQuery['tables'],
1360 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1364 $blockQuery['joins']
1368 foreach ( $rows as $row ) {
1369 $block = self
::newFromRow( $row );
1370 if ( !$block->isExpired() ) {
1379 * From a list of multiple blocks, find the most exact and strongest Block.
1381 * The logic for finding the "best" block is:
1382 * - Blocks that match the block's target IP are preferred over ones in a range
1383 * - Hardblocks are chosen over softblocks that prevent account creation
1384 * - Softblocks that prevent account creation are chosen over other softblocks
1385 * - Other softblocks are chosen over autoblocks
1386 * - If there are multiple exact or range blocks at the same level, the one chosen
1388 * This should be used when $blocks where retrieved from the user's IP address
1389 * and $ipChain is populated from the same IP address information.
1391 * @param array $blocks Array of Block objects
1392 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1393 * a block is to the server, and if a block matches exactly, or is in a range.
1394 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1396 * @throws MWException
1397 * @return Block|null The "best" block from the list
1399 public static function chooseBlock( array $blocks, array $ipChain ) {
1400 if ( $blocks === [] ) {
1402 } elseif ( count( $blocks ) == 1 ) {
1406 // Sort hard blocks before soft ones and secondarily sort blocks
1407 // that disable account creation before those that don't.
1408 usort( $blocks, function ( Block
$a, Block
$b ) {
1409 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1410 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1411 return strcmp( $bWeight, $aWeight ); // highest weight first
1414 $blocksListExact = [
1416 'disable_create' => false,
1420 $blocksListRange = [
1422 'disable_create' => false,
1426 $ipChain = array_reverse( $ipChain );
1428 /** @var Block $block */
1429 foreach ( $blocks as $block ) {
1430 // Stop searching if we have already have a "better" block. This
1431 // is why the order of the blocks matters
1432 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1434 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1438 foreach ( $ipChain as $checkip ) {
1439 $checkipHex = IP
::toHex( $checkip );
1440 if ( (string)$block->getTarget() === $checkip ) {
1441 if ( $block->isHardblock() ) {
1442 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1443 } elseif ( $block->prevents( 'createaccount' ) ) {
1444 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1445 } elseif ( $block->mAuto
) {
1446 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1448 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1450 // We found closest exact match in the ip list, so go to the next Block
1452 } elseif ( array_filter( $blocksListExact ) == []
1453 && $block->getRangeStart() <= $checkipHex
1454 && $block->getRangeEnd() >= $checkipHex
1456 if ( $block->isHardblock() ) {
1457 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1458 } elseif ( $block->prevents( 'createaccount' ) ) {
1459 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1460 } elseif ( $block->mAuto
) {
1461 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1463 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1470 if ( array_filter( $blocksListExact ) == [] ) {
1471 $blocksList = &$blocksListRange;
1473 $blocksList = &$blocksListExact;
1476 $chosenBlock = null;
1477 if ( $blocksList['hard'] ) {
1478 $chosenBlock = $blocksList['hard'];
1479 } elseif ( $blocksList['disable_create'] ) {
1480 $chosenBlock = $blocksList['disable_create'];
1481 } elseif ( $blocksList['other'] ) {
1482 $chosenBlock = $blocksList['other'];
1483 } elseif ( $blocksList['auto'] ) {
1484 $chosenBlock = $blocksList['auto'];
1486 throw new MWException( "Proxy block found, but couldn't be classified." );
1489 return $chosenBlock;
1493 * From an existing Block, get the target and the type of target.
1494 * Note that, except for null, it is always safe to treat the target
1495 * as a string; for User objects this will return User::__toString()
1496 * which in turn gives User::getName().
1498 * @param string|int|User|null $target
1499 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1501 public static function parseTarget( $target ) {
1502 # We may have been through this before
1503 if ( $target instanceof User
) {
1504 if ( IP
::isValid( $target->getName() ) ) {
1505 return [ $target, self
::TYPE_IP
];
1507 return [ $target, self
::TYPE_USER
];
1509 } elseif ( $target === null ) {
1510 return [ null, null ];
1513 $target = trim( $target );
1515 if ( IP
::isValid( $target ) ) {
1516 # We can still create a User if it's an IP address, but we need to turn
1517 # off validation checking (which would exclude IP addresses)
1519 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1523 } elseif ( IP
::isValidRange( $target ) ) {
1524 # Can't create a User from an IP range
1525 return [ IP
::sanitizeRange( $target ), self
::TYPE_RANGE
];
1528 # Consider the possibility that this is not a username at all
1529 # but actually an old subpage (T31797)
1530 if ( strpos( $target, '/' ) !== false ) {
1531 # An old subpage, drill down to the user behind it
1532 $target = explode( '/', $target )[0];
1535 $userObj = User
::newFromName( $target );
1536 if ( $userObj instanceof User
) {
1537 # Note that since numbers are valid usernames, a $target of "12345" will be
1538 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1539 # since hash characters are not valid in usernames or titles generally.
1540 return [ $userObj, self
::TYPE_USER
];
1542 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1543 # Autoblock reference in the form "#12345"
1544 return [ substr( $target, 1 ), self
::TYPE_AUTO
];
1548 return [ null, null ];
1553 * Get the type of target for this particular block. Autoblocks have whichever type
1554 * corresponds to their target, so to detect if a block is an autoblock, we have to
1555 * check the mAuto property instead.
1556 * @return int Block::TYPE_ constant, will never be TYPE_ID
1558 public function getType() {
1565 * Get the target and target type for this particular Block. Note that for autoblocks,
1566 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1567 * in this situation.
1568 * @return array [ User|String, Block::TYPE_ constant ]
1569 * @todo FIXME: This should be an integral part of the Block member variables
1571 public function getTargetAndType() {
1572 return [ $this->getTarget(), $this->getType() ];
1576 * Get the target for this particular Block. Note that for autoblocks,
1577 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1578 * in this situation.
1579 * @return User|string
1581 public function getTarget() {
1582 return $this->target
;
1588 * @return mixed|string
1590 public function getExpiry() {
1591 return $this->mExpiry
;
1595 * Set the target for this block, and update $this->type accordingly
1596 * @param mixed $target
1598 public function setTarget( $target ) {
1599 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1603 * Get the user who implemented this block
1604 * @return User User object. May name a foreign user.
1606 public function getBlocker() {
1607 return $this->blocker
;
1611 * Set the user who implemented (or will implement) this block
1612 * @param User|string $user Local User object or username string
1614 public function setBlocker( $user ) {
1615 if ( is_string( $user ) ) {
1616 $user = User
::newFromName( $user, false );
1619 if ( $user->isAnon() && User
::isUsableName( $user->getName() ) ) {
1620 throw new InvalidArgumentException(
1621 'Blocker must be a local user or a name that cannot be a local user'
1625 $this->blocker
= $user;
1629 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1630 * the same as the block's, to a maximum of 24 hours.
1634 * @param WebResponse $response The response on which to set the cookie.
1636 public function setCookie( WebResponse
$response ) {
1637 // Calculate the default expiry time.
1638 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1640 // Use the Block's expiry time only if it's less than the default.
1641 $expiryTime = $this->getExpiry();
1642 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1643 $expiryTime = $maxExpiryTime;
1646 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1647 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1648 $cookieOptions = [ 'httpOnly' => false ];
1649 $cookieValue = $this->getCookieValue();
1650 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1654 * Unset the 'BlockID' cookie.
1658 * @param WebResponse $response The response on which to unset the cookie.
1660 public static function clearCookie( WebResponse
$response ) {
1661 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1665 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1666 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1671 * @return string The block ID, probably concatenated with "!" and the HMAC.
1673 public function getCookieValue() {
1674 $config = RequestContext
::getMain()->getConfig();
1675 $id = $this->getId();
1676 $secretKey = $config->get( 'SecretKey' );
1677 if ( !$secretKey ) {
1678 // If there's no secret key, don't append a HMAC.
1681 $hmac = MWCryptHash
::hmac( $id, $secretKey, false );
1682 $cookieValue = $id . '!' . $hmac;
1683 return $cookieValue;
1687 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1688 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1692 * @param string $cookieValue The string in which to find the ID.
1694 * @return int|null The block ID, or null if the HMAC is present and invalid.
1696 public static function getIdFromCookieValue( $cookieValue ) {
1697 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1698 $bangPos = strpos( $cookieValue, '!' );
1699 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
1700 // Get the site-wide secret key.
1701 $config = RequestContext
::getMain()->getConfig();
1702 $secretKey = $config->get( 'SecretKey' );
1703 if ( !$secretKey ) {
1704 // If there's no secret key, just use the ID as given.
1707 $storedHmac = substr( $cookieValue, $bangPos +
1 );
1708 $calculatedHmac = MWCryptHash
::hmac( $id, $secretKey, false );
1709 if ( $calculatedHmac === $storedHmac ) {
1717 * Get the key and parameters for the corresponding error message.
1720 * @param IContextSource $context
1723 public function getPermissionsError( IContextSource
$context ) {
1724 $params = $this->getBlockErrorParams( $context );
1726 $msg = 'blockedtext';
1727 if ( $this->getSystemBlockType() !== null ) {
1728 $msg = 'systemblockedtext';
1729 } elseif ( $this->mAuto
) {
1730 $msg = 'autoblockedtext';
1731 } elseif ( !$this->isSitewide() ) {
1732 $msg = 'blockedtext-partial';
1735 array_unshift( $params, $msg );
1741 * Get block information used in different block error messages
1744 * @param IContextSource $context
1747 public function getBlockErrorParams( IContextSource
$context ) {
1748 $blocker = $this->getBlocker();
1749 if ( $blocker instanceof User
) { // local user
1750 $blockerUserpage = $blocker->getUserPage();
1751 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1752 } else { // foreign user
1756 $reason = $this->mReason
;
1757 if ( $reason == '' ) {
1758 $reason = $context->msg( 'blockednoreason' )->text();
1761 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1762 * This could be a username, an IP range, or a single IP. */
1763 $intended = $this->getTarget();
1764 $systemBlockType = $this->getSystemBlockType();
1765 $lang = $context->getLanguage();
1770 $context->getRequest()->getIP(),
1772 $systemBlockType ??
$this->getId(),
1773 $lang->formatExpiry( $this->mExpiry
),
1775 $lang->userTimeAndDate( $this->mTimestamp
, $context->getUser() ),
1782 * Getting the restrictions will perform a database query if the restrictions
1783 * are not already loaded.
1786 * @return Restriction[]
1788 public function getRestrictions() {
1789 if ( $this->restrictions
=== null ) {
1790 // If the block id has not been set, then do not attempt to load the
1792 if ( !$this->mId
) {
1795 $this->restrictions
= BlockRestriction
::loadByBlockId( $this->mId
);
1798 return $this->restrictions
;
1805 * @param Restriction[] $restrictions
1808 public function setRestrictions( array $restrictions ) {
1809 $this->restrictions
= array_filter( $restrictions, function ( $restriction ) {
1810 return $restriction instanceof Restriction
;
1817 * Checks if a block applies to a particular title
1819 * This check does not consider whether `$this->prevents( 'editownusertalk' )`
1820 * returns false, as the identity of the user making the hypothetical edit
1821 * isn't known here (particularly in the case of IP hardblocks, range
1822 * blocks, and auto-blocks).
1824 * @param Title $title
1827 public function appliesToTitle( Title
$title ) {
1828 if ( $this->isSitewide() ) {
1832 $restrictions = $this->getRestrictions();
1833 foreach ( $restrictions as $restriction ) {
1834 if ( $restriction->matches( $title ) ) {
1843 * Checks if a block applies to a particular namespace
1850 public function appliesToNamespace( $ns ) {
1851 if ( $this->isSitewide() ) {
1855 // Blocks do not apply to virtual namespaces.
1860 $restriction = $this->findRestriction( NamespaceRestriction
::TYPE
, $ns );
1862 return (bool)$restriction;
1866 * Checks if a block applies to a particular page
1868 * This check does not consider whether `$this->prevents( 'editownusertalk' )`
1869 * returns false, as the identity of the user making the hypothetical edit
1870 * isn't known here (particularly in the case of IP hardblocks, range
1871 * blocks, and auto-blocks).
1875 * @param int $pageId
1878 public function appliesToPage( $pageId ) {
1879 if ( $this->isSitewide() ) {
1883 // If the pageId is not over zero, the block cannot apply to it.
1884 if ( $pageId <= 0 ) {
1888 $restriction = $this->findRestriction( PageRestriction
::TYPE
, $pageId );
1890 return (bool)$restriction;
1894 * Find Restriction by type and value.
1896 * @param string $type
1898 * @return Restriction|null
1900 private function findRestriction( $type, $value ) {
1901 $restrictions = $this->getRestrictions();
1902 foreach ( $restrictions as $restriction ) {
1903 if ( $restriction->getType() !== $type ) {
1907 if ( $restriction->getValue() === $value ) {
1908 return $restriction;