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;
71 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
81 private $isAutoblocking;
83 /** @var string|null */
84 private $systemBlockType;
89 /** @var Restriction[] */
90 private $restrictions;
100 * Create a new block with specified parameters on a user, IP or IP range.
102 * @param array $options Parameters of the block:
103 * address string|User Target user name, User object, IP address or IP range
104 * user int Override target user ID (for foreign users)
105 * by int User ID of the blocker
106 * reason string Reason of the block
107 * timestamp string The time at which the block comes into effect
108 * auto bool Is this an automatic block?
109 * expiry string Timestamp of expiration of the block or 'infinity'
110 * anonOnly bool Only disallow anonymous actions
111 * createAccount bool Disallow creation of new accounts
112 * enableAutoblock bool Enable automatic blocking
113 * hideName bool Hide the target user name
114 * blockEmail bool Disallow sending emails
115 * allowUsertalk bool Allow the target to edit its own talk page
116 * byText string Username of the blocker (for foreign users)
117 * systemBlock string Indicate that this block is automatically
118 * created by MediaWiki rather than being stored
119 * in the database. Value is a string to return
120 * from self::getSystemBlockType().
122 * @since 1.26 accepts $options array instead of individual parameters; order
123 * of parameters above reflects the original order
125 function __construct( $options = [] ) {
135 'createAccount' => false,
136 'enableAutoblock' => false,
138 'blockEmail' => false,
139 'allowUsertalk' => false,
141 'systemBlock' => null,
145 if ( func_num_args() > 1 ||
!is_array( $options ) ) {
146 $options = array_combine(
147 array_slice( array_keys( $defaults ), 0, func_num_args() ),
150 wfDeprecated( __METHOD__
. ' with multiple arguments', '1.26' );
153 $options +
= $defaults;
155 $this->setTarget( $options['address'] );
157 if ( $this->target
instanceof User
&& $options['user'] ) {
158 # Needed for foreign users
159 $this->forcedTargetID
= $options['user'];
162 if ( $options['by'] ) {
164 $this->setBlocker( User
::newFromId( $options['by'] ) );
167 $this->setBlocker( $options['byText'] );
170 $this->mReason
= $options['reason'];
171 $this->mTimestamp
= wfTimestamp( TS_MW
, $options['timestamp'] );
172 $this->mExpiry
= wfGetDB( DB_REPLICA
)->decodeExpiry( $options['expiry'] );
175 $this->mAuto
= (bool)$options['auto'];
176 $this->mHideName
= (bool)$options['hideName'];
177 $this->isHardblock( !$options['anonOnly'] );
178 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
179 $this->isSitewide( (bool)$options['sitewide'] );
181 # Prevention measures
182 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
183 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
184 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
186 $this->mFromMaster
= false;
187 $this->systemBlockType
= $options['systemBlock'];
191 * Load a blocked user from their block id.
193 * @param int $id Block id to search for
196 public static function newFromID( $id ) {
197 $dbr = wfGetDB( DB_REPLICA
);
198 $blockQuery = self
::getQueryInfo();
199 $res = $dbr->selectRow(
200 $blockQuery['tables'],
201 $blockQuery['fields'],
208 return self
::newFromRow( $res );
215 * Return the list of ipblocks fields that should be selected to create
217 * @deprecated since 1.31, use self::getQueryInfo() instead.
220 public static function selectFields() {
221 global $wgActorTableSchemaMigrationStage;
223 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
224 // If code is using this instead of self::getQueryInfo(), there's a
225 // decent chance it's going to try to directly access
226 // $row->ipb_by or $row->ipb_by_text and we can't give it
227 // useful values here once those aren't being used anymore.
228 throw new BadMethodCallException(
229 'Cannot use ' . __METHOD__
230 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
234 wfDeprecated( __METHOD__
, '1.31' );
240 'ipb_by_actor' => 'NULL',
244 'ipb_create_account',
245 'ipb_enable_autoblock',
249 'ipb_allow_usertalk',
250 'ipb_parent_block_id',
252 ] + CommentStore
::getStore()->getFields( 'ipb_reason' );
256 * Return the tables, fields, and join conditions to be selected to create
257 * a new block object.
259 * @return array With three keys:
260 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
261 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
262 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
264 public static function getQueryInfo() {
265 $commentQuery = CommentStore
::getStore()->getJoin( 'ipb_reason' );
266 $actorQuery = ActorMigration
::newMigration()->getJoin( 'ipb_by' );
268 'tables' => [ 'ipblocks' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
275 'ipb_create_account',
276 'ipb_enable_autoblock',
280 'ipb_allow_usertalk',
281 'ipb_parent_block_id',
283 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
284 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
289 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
290 * the blocking user or the block timestamp, only things which affect the blocked user
292 * @param Block $block
296 public function equals( Block
$block ) {
298 (string)$this->target
== (string)$block->target
299 && $this->type
== $block->type
300 && $this->mAuto
== $block->mAuto
301 && $this->isHardblock() == $block->isHardblock()
302 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
303 && $this->mExpiry
== $block->mExpiry
304 && $this->isAutoblocking() == $block->isAutoblocking()
305 && $this->mHideName
== $block->mHideName
306 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
307 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
308 && $this->mReason
== $block->mReason
309 && $this->isSitewide() == $block->isSitewide()
310 // Block::getRestrictions() may perform a database query, so keep it at
312 && BlockRestriction
::equals( $this->getRestrictions(), $block->getRestrictions() )
317 * Load a block from the database which affects the already-set $this->target:
318 * 1) A block directly on the given user or IP
319 * 2) A rangeblock encompassing the given IP (smallest first)
320 * 3) An autoblock on the given IP
321 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
322 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
323 * @throws MWException
324 * @return bool Whether a relevant block was found
326 protected function newLoad( $vagueTarget = null ) {
327 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_REPLICA
);
329 if ( $this->type
!== null ) {
331 'ipb_address' => [ (string)$this->target
],
334 $conds = [ 'ipb_address' => [] ];
337 # Be aware that the != '' check is explicit, since empty values will be
338 # passed by some callers (T31116)
339 if ( $vagueTarget != '' ) {
340 list( $target, $type ) = self
::parseTarget( $vagueTarget );
342 case self
::TYPE_USER
:
343 # Slightly weird, but who are we to argue?
344 $conds['ipb_address'][] = (string)$target;
348 $conds['ipb_address'][] = (string)$target;
349 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
350 $conds = $db->makeList( $conds, LIST_OR
);
353 case self
::TYPE_RANGE
:
354 list( $start, $end ) = IP
::parseRange( $target );
355 $conds['ipb_address'][] = (string)$target;
356 $conds[] = self
::getRangeCond( $start, $end );
357 $conds = $db->makeList( $conds, LIST_OR
);
361 throw new MWException( "Tried to load block with invalid type" );
365 $blockQuery = self
::getQueryInfo();
367 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
370 # This result could contain a block on the user, a block on the IP, and a russian-doll
371 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
374 # Lower will be better
375 $bestBlockScore = 100;
377 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
378 $bestBlockPreventsEdit = null;
380 foreach ( $res as $row ) {
381 $block = self
::newFromRow( $row );
383 # Don't use expired blocks
384 if ( $block->isExpired() ) {
388 # Don't use anon only blocks on users
389 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
393 if ( $block->getType() == self
::TYPE_RANGE
) {
394 # This is the number of bits that are allowed to vary in the block, give
395 # or take some floating point errors
396 $end = Wikimedia\base_convert
( $block->getRangeEnd(), 16, 10 );
397 $start = Wikimedia\base_convert
( $block->getRangeStart(), 16, 10 );
398 $size = log( $end - $start +
1, 2 );
400 # This has the nice property that a /32 block is ranked equally with a
401 # single-IP block, which is exactly what it is...
402 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
405 $score = $block->getType();
408 if ( $score < $bestBlockScore ) {
409 $bestBlockScore = $score;
411 $bestBlockPreventsEdit = $block->prevents( 'edit' );
415 if ( $bestRow !== null ) {
416 $this->initFromRow( $bestRow );
417 $this->prevents( 'edit', $bestBlockPreventsEdit );
425 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
426 * @param string $start Hexadecimal IP representation
427 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
430 public static function getRangeCond( $start, $end = null ) {
431 if ( $end === null ) {
434 # Per T16634, we want to include relevant active rangeblocks; for
435 # rangeblocks, we want to include larger ranges which enclose the given
436 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
437 # so we can improve performance by filtering on a LIKE clause
438 $chunk = self
::getIpFragment( $start );
439 $dbr = wfGetDB( DB_REPLICA
);
440 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
442 # Fairly hard to make a malicious SQL statement out of hex characters,
443 # but stranger things have happened...
444 $safeStart = $dbr->addQuotes( $start );
445 $safeEnd = $dbr->addQuotes( $end );
447 return $dbr->makeList(
449 "ipb_range_start $like",
450 "ipb_range_start <= $safeStart",
451 "ipb_range_end >= $safeEnd",
458 * Get the component of an IP address which is certain to be the same between an IP
459 * address and a rangeblock containing that IP address.
460 * @param string $hex Hexadecimal IP representation
463 protected static function getIpFragment( $hex ) {
464 global $wgBlockCIDRLimit;
465 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
466 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
468 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
473 * Given a database row from the ipblocks table, initialize
475 * @param stdClass $row A row from the ipblocks table
477 protected function initFromRow( $row ) {
478 $this->setTarget( $row->ipb_address
);
479 $this->setBlocker( User
::newFromAnyId(
480 $row->ipb_by
, $row->ipb_by_text
, $row->ipb_by_actor ??
null
483 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
484 $this->mAuto
= $row->ipb_auto
;
485 $this->mHideName
= $row->ipb_deleted
;
486 $this->mId
= (int)$row->ipb_id
;
487 $this->mParentBlockId
= $row->ipb_parent_block_id
;
489 // I wish I didn't have to do this
490 $db = wfGetDB( DB_REPLICA
);
491 $this->mExpiry
= $db->decodeExpiry( $row->ipb_expiry
);
492 $this->mReason
= CommentStore
::getStore()
493 // Legacy because $row may have come from self::selectFields()
494 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
;
496 $this->isHardblock( !$row->ipb_anon_only
);
497 $this->isAutoblocking( $row->ipb_enable_autoblock
);
498 $this->isSitewide( (bool)$row->ipb_sitewide
);
500 $this->prevents( 'createaccount', $row->ipb_create_account
);
501 $this->prevents( 'sendemail', $row->ipb_block_email
);
502 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
506 * Create a new Block object from a database row
507 * @param stdClass $row Row from the ipblocks table
510 public static function newFromRow( $row ) {
512 $block->initFromRow( $row );
517 * Delete the row from the IP blocks table.
519 * @throws MWException
522 public function delete() {
523 if ( wfReadOnly() ) {
527 if ( !$this->getId() ) {
528 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
531 $dbw = wfGetDB( DB_MASTER
);
533 BlockRestriction
::deleteByParentBlockId( $this->getId() );
534 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
536 BlockRestriction
::deleteByBlockId( $this->getId() );
537 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
539 return $dbw->affectedRows() > 0;
543 * Insert a block into the block table. Will fail if there is a conflicting
544 * block (same name and options) already in the database.
546 * @param IDatabase|null $dbw If you have one available
547 * @return bool|array False on failure, assoc array on success:
548 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
550 public function insert( $dbw = null ) {
551 global $wgBlockDisablesLogin;
553 if ( $this->getSystemBlockType() !== null ) {
554 throw new MWException( 'Cannot insert a system block into the database' );
556 if ( !$this->getBlocker() ||
$this->getBlocker()->getName() === '' ) {
557 throw new MWException( 'Cannot insert a block without a blocker set' );
560 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
562 if ( $dbw === null ) {
563 $dbw = wfGetDB( DB_MASTER
);
566 self
::purgeExpired();
568 $row = $this->getDatabaseArray( $dbw );
570 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
571 $affected = $dbw->affectedRows();
573 $this->setId( $dbw->insertId() );
574 if ( $this->restrictions
) {
575 BlockRestriction
::insert( $this->restrictions
);
579 # Don't collide with expired blocks.
580 # Do this after trying to insert to avoid locking.
582 # T96428: The ipb_address index uses a prefix on a field, so
583 # use a standard SELECT + DELETE to avoid annoying gap locks.
584 $ids = $dbw->selectFieldValues( 'ipblocks',
587 'ipb_address' => $row['ipb_address'],
588 'ipb_user' => $row['ipb_user'],
589 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
594 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
595 BlockRestriction
::deleteByBlockId( $ids );
596 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
597 $affected = $dbw->affectedRows();
598 $this->setId( $dbw->insertId() );
599 if ( $this->restrictions
) {
600 BlockRestriction
::insert( $this->restrictions
);
606 $auto_ipd_ids = $this->doRetroactiveAutoblock();
608 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
609 // Change user login token to force them to be logged out.
610 $this->target
->setToken();
611 $this->target
->saveSettings();
614 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
621 * Update a block in the DB with new parameters.
622 * The ID field needs to be loaded first.
624 * @return bool|array False on failure, array on success:
625 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
627 public function update() {
628 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
629 $dbw = wfGetDB( DB_MASTER
);
631 $dbw->startAtomic( __METHOD__
);
633 $result = $dbw->update(
635 $this->getDatabaseArray( $dbw ),
636 [ 'ipb_id' => $this->getId() ],
640 // Only update the restrictions if they have been modified.
641 if ( $this->restrictions
!== null ) {
642 // An empty array should remove all of the restrictions.
643 if ( empty( $this->restrictions
) ) {
644 $success = BlockRestriction
::deleteByBlockId( $this->getId() );
646 $success = BlockRestriction
::update( $this->restrictions
);
648 // Update the result. The first false is the result, otherwise, true.
649 $result = $result && $success;
652 if ( $this->isAutoblocking() ) {
653 // update corresponding autoblock(s) (T50813)
656 $this->getAutoblockUpdateArray( $dbw ),
657 [ 'ipb_parent_block_id' => $this->getId() ],
661 // Only update the restrictions if they have been modified.
662 if ( $this->restrictions
!== null ) {
663 BlockRestriction
::updateByParentBlockId( $this->getId(), $this->restrictions
);
666 // autoblock no longer required, delete corresponding autoblock(s)
667 BlockRestriction
::deleteByParentBlockId( $this->getId() );
670 [ 'ipb_parent_block_id' => $this->getId() ],
675 $dbw->endAtomic( __METHOD__
);
678 $auto_ipd_ids = $this->doRetroactiveAutoblock();
679 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
686 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
687 * @param IDatabase $dbw
690 protected function getDatabaseArray( IDatabase
$dbw ) {
691 $expiry = $dbw->encodeExpiry( $this->mExpiry
);
693 if ( $this->forcedTargetID
) {
694 $uid = $this->forcedTargetID
;
696 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
700 'ipb_address' => (string)$this->target
,
702 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
703 'ipb_auto' => $this->mAuto
,
704 'ipb_anon_only' => !$this->isHardblock(),
705 'ipb_create_account' => $this->prevents( 'createaccount' ),
706 'ipb_enable_autoblock' => $this->isAutoblocking(),
707 'ipb_expiry' => $expiry,
708 'ipb_range_start' => $this->getRangeStart(),
709 'ipb_range_end' => $this->getRangeEnd(),
710 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
711 'ipb_block_email' => $this->prevents( 'sendemail' ),
712 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
713 'ipb_parent_block_id' => $this->mParentBlockId
,
714 'ipb_sitewide' => $this->isSitewide(),
715 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->mReason
)
716 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
722 * @param IDatabase $dbw
725 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
727 'ipb_create_account' => $this->prevents( 'createaccount' ),
728 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
729 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
730 'ipb_sitewide' => $this->isSitewide(),
731 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->mReason
)
732 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
736 * Retroactively autoblocks the last IP used by the user (if it is a user)
737 * blocked by this Block.
739 * @return array Block IDs of retroactive autoblocks made
741 protected function doRetroactiveAutoblock() {
743 # If autoblock is enabled, autoblock the LAST IP(s) used
744 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
745 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
747 $continue = Hooks
::run(
748 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
751 self
::defaultRetroactiveAutoblock( $this, $blockIds );
758 * Retroactively autoblocks the last IP used by the user (if it is a user)
759 * blocked by this Block. This will use the recentchanges table.
761 * @param Block $block
762 * @param array &$blockIds
764 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
767 // No IPs are in recentchanges table, so nothing to select
768 if ( !$wgPutIPinRC ) {
772 // Autoblocks only apply to TYPE_USER
773 if ( $block->getType() !== self
::TYPE_USER
) {
776 $target = $block->getTarget(); // TYPE_USER => always a User object
778 $dbr = wfGetDB( DB_REPLICA
);
779 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
781 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
783 // Just the last IP used.
784 $options['LIMIT'] = 1;
787 [ 'recentchanges' ] +
$rcQuery['tables'],
795 if ( !$res->numRows() ) {
796 # No results, don't autoblock anything
797 wfDebug( "No IP found to retroactively autoblock\n" );
799 foreach ( $res as $row ) {
801 $id = $block->doAutoblock( $row->rc_ip
);
811 * Checks whether a given IP is on the autoblock whitelist.
812 * TODO: this probably belongs somewhere else, but not sure where...
814 * @param string $ip The IP to check
817 public static function isWhitelistedFromAutoblocks( $ip ) {
818 // Try to get the autoblock_whitelist from the cache, as it's faster
819 // than getting the msg raw and explode()'ing it.
820 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
821 $lines = $cache->getWithSetCallback(
822 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
824 function ( $curValue, &$ttl, array &$setOpts ) {
825 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
827 return explode( "\n",
828 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
832 wfDebug( "Checking the autoblock whitelist..\n" );
834 foreach ( $lines as $line ) {
836 if ( substr( $line, 0, 1 ) !== '*' ) {
840 $wlEntry = substr( $line, 1 );
841 $wlEntry = trim( $wlEntry );
843 wfDebug( "Checking $ip against $wlEntry..." );
845 # Is the IP in this range?
846 if ( IP
::isInRange( $ip, $wlEntry ) ) {
847 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
850 wfDebug( " No match\n" );
858 * Autoblocks the given IP, referring to this Block.
860 * @param string $autoblockIP The IP to autoblock.
861 * @return int|bool Block ID if an autoblock was inserted, false if not.
863 public function doAutoblock( $autoblockIP ) {
864 # If autoblocks are disabled, go away.
865 if ( !$this->isAutoblocking() ) {
869 # Don't autoblock for system blocks
870 if ( $this->getSystemBlockType() !== null ) {
871 throw new MWException( 'Cannot autoblock from a system block' );
874 # Check for presence on the autoblock whitelist.
875 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
879 // Avoid PHP 7.1 warning of passing $this by reference
881 # Allow hooks to cancel the autoblock.
882 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
883 wfDebug( "Autoblock aborted by hook.\n" );
887 # It's okay to autoblock. Go ahead and insert/update the block...
889 # Do not add a *new* block if the IP is already blocked.
890 $ipblock = self
::newFromTarget( $autoblockIP );
892 # Check if the block is an autoblock and would exceed the user block
893 # if renewed. If so, do nothing, otherwise prolong the block time...
894 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
895 $this->mExpiry
> self
::getAutoblockExpiry( $ipblock->mTimestamp
)
897 # Reset block timestamp to now and its expiry to
898 # $wgAutoblockExpiry in the future
899 $ipblock->updateTimestamp();
904 # Make a new block object with the desired properties.
905 $autoblock = new Block
;
906 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
907 $autoblock->setTarget( $autoblockIP );
908 $autoblock->setBlocker( $this->getBlocker() );
909 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
910 ->inContentLanguage()->plain();
911 $timestamp = wfTimestampNow();
912 $autoblock->mTimestamp
= $timestamp;
913 $autoblock->mAuto
= 1;
914 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
915 # Continue suppressing the name if needed
916 $autoblock->mHideName
= $this->mHideName
;
917 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
918 $autoblock->mParentBlockId
= $this->mId
;
919 $autoblock->isSitewide( $this->isSitewide() );
920 $autoblock->setRestrictions( $this->getRestrictions() );
922 if ( $this->mExpiry
== 'infinity' ) {
923 # Original block was indefinite, start an autoblock now
924 $autoblock->mExpiry
= self
::getAutoblockExpiry( $timestamp );
926 # If the user is already blocked with an expiry date, we don't
927 # want to pile on top of that.
928 $autoblock->mExpiry
= min( $this->mExpiry
, self
::getAutoblockExpiry( $timestamp ) );
931 # Insert the block...
932 $status = $autoblock->insert();
939 * Check if a block has expired. Delete it if it is.
942 public function deleteIfExpired() {
943 if ( $this->isExpired() ) {
944 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
948 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
956 * Has the block expired?
959 public function isExpired() {
960 $timestamp = wfTimestampNow();
961 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
963 if ( !$this->mExpiry
) {
966 return $timestamp > $this->mExpiry
;
971 * Is the block address valid (i.e. not a null string?)
974 public function isValid() {
975 return $this->getTarget() != null;
979 * Update the timestamp on autoblocks.
981 public function updateTimestamp() {
982 if ( $this->mAuto
) {
983 $this->mTimestamp
= wfTimestamp();
984 $this->mExpiry
= self
::getAutoblockExpiry( $this->mTimestamp
);
986 $dbw = wfGetDB( DB_MASTER
);
987 $dbw->update( 'ipblocks',
989 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
990 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
993 'ipb_id' => $this->getId(),
1001 * Get the IP address at the start of the range in Hex form
1002 * @throws MWException
1003 * @return string IP in Hex form
1005 public function getRangeStart() {
1006 switch ( $this->type
) {
1007 case self
::TYPE_USER
:
1010 return IP
::toHex( $this->target
);
1011 case self
::TYPE_RANGE
:
1012 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
1015 throw new MWException( "Block with invalid type" );
1020 * Get the IP address at the end of the range in Hex form
1021 * @throws MWException
1022 * @return string IP in Hex form
1024 public function getRangeEnd() {
1025 switch ( $this->type
) {
1026 case self
::TYPE_USER
:
1029 return IP
::toHex( $this->target
);
1030 case self
::TYPE_RANGE
:
1031 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
1034 throw new MWException( "Block with invalid type" );
1039 * Get the user id of the blocking sysop
1041 * @return int (0 for foreign users)
1043 public function getBy() {
1044 $blocker = $this->getBlocker();
1045 return ( $blocker instanceof User
)
1051 * Get the username of the blocking sysop
1055 public function getByName() {
1056 $blocker = $this->getBlocker();
1057 return ( $blocker instanceof User
)
1058 ?
$blocker->getName()
1059 : (string)$blocker; // username
1066 public function getId() {
1073 * @param int $blockId
1076 private function setId( $blockId ) {
1077 $this->mId
= (int)$blockId;
1079 if ( is_array( $this->restrictions
) ) {
1080 $this->restrictions
= BlockRestriction
::setBlockId( $blockId, $this->restrictions
);
1087 * Get the system block type, if any
1089 * @return string|null
1091 public function getSystemBlockType() {
1092 return $this->systemBlockType
;
1096 * Get/set a flag determining whether the master is used for reads
1098 * @param bool|null $x
1101 public function fromMaster( $x = null ) {
1102 return wfSetVar( $this->mFromMaster
, $x );
1106 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1107 * @param bool|null $x
1110 public function isHardblock( $x = null ) {
1111 wfSetVar( $this->isHardblock
, $x );
1113 # You can't *not* hardblock a user
1114 return $this->getType() == self
::TYPE_USER
1116 : $this->isHardblock
;
1120 * @param null|bool $x
1123 public function isAutoblocking( $x = null ) {
1124 wfSetVar( $this->isAutoblocking
, $x );
1126 # You can't put an autoblock on an IP or range as we don't have any history to
1127 # look over to get more IPs from
1128 return $this->getType() == self
::TYPE_USER
1129 ?
$this->isAutoblocking
1134 * Indicates that the block is a sitewide block. This means the user is
1135 * prohibited from editing any page on the site (other than their own talk
1139 * @param null|bool $x
1142 public function isSitewide( $x = null ) {
1143 return wfSetVar( $this->isSitewide
, $x );
1147 * Get/set whether the Block prevents a given action
1149 * @param string $action Action to check
1150 * @param bool|null $x Value for set, or null to just get value
1151 * @return bool|null Null for unrecognized rights.
1153 public function prevents( $action, $x = null ) {
1154 $config = RequestContext
::getMain()->getConfig();
1155 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1156 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1159 switch ( $action ) {
1161 # For now... <evil laugh>
1164 case 'createaccount':
1165 $res = wfSetVar( $this->mCreateAccount
, $x );
1168 $res = wfSetVar( $this->mBlockEmail
, $x );
1171 // Until T6995 is completed
1172 $res = $this->isSitewide();
1174 case 'editownusertalk':
1175 // NOTE: this check is not reliable on partial blocks
1176 // since partially blocked users are always allowed to edit
1177 // their own talk page unless a restriction exists on the
1178 // page or User_talk: namespace
1179 $res = wfSetVar( $this->mDisableUsertalk
, $x );
1181 // edit own user talk can be disabled by config
1182 if ( !$blockAllowsUTEdit ) {
1193 if ( !$res && $blockDisablesLogin ) {
1194 // If a block would disable login, then it should
1195 // prevent any action that all users cannot do
1197 $res = $anon->isAllowed( $action ) ?
$res : true;
1204 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1205 * @return string Text is escaped
1207 public function getRedactedName() {
1208 if ( $this->mAuto
) {
1209 return Html
::rawElement(
1211 [ 'class' => 'mw-autoblockid' ],
1212 wfMessage( 'autoblockid', $this->mId
)
1215 return htmlspecialchars( $this->getTarget() );
1220 * Get a timestamp of the expiry for autoblocks
1222 * @param string|int $timestamp
1225 public static function getAutoblockExpiry( $timestamp ) {
1226 global $wgAutoblockExpiry;
1228 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1232 * Purge expired blocks from the ipblocks table
1234 public static function purgeExpired() {
1235 if ( wfReadOnly() ) {
1239 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1240 wfGetDB( DB_MASTER
),
1242 function ( IDatabase
$dbw, $fname ) {
1243 $ids = $dbw->selectFieldValues( 'ipblocks',
1245 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1249 BlockRestriction
::deleteByBlockId( $ids );
1250 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1257 * Given a target and the target's type, get an existing Block object if possible.
1258 * @param string|User|int $specificTarget A block target, which may be one of several types:
1259 * * A user to block, in which case $target will be a User
1260 * * An IP to block, in which case $target will be a User generated by using
1261 * User::newFromName( $ip, false ) to turn off name validation
1262 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1263 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1265 * Calling this with a user, IP address or range will not select autoblocks, and will
1266 * only select a block where the targets match exactly (so looking for blocks on
1267 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1268 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1269 * affects that target (so for an IP address, get ranges containing that IP; and also
1270 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1271 * @param bool $fromMaster Whether to use the DB_MASTER database
1272 * @return Block|null (null if no relevant block could be found). The target and type
1273 * of the returned Block will refer to the actual block which was found, which might
1274 * not be the same as the target you gave if you used $vagueTarget!
1276 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1277 list( $target, $type ) = self
::parseTarget( $specificTarget );
1278 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1279 return self
::newFromID( $target );
1281 } elseif ( $target === null && $vagueTarget == '' ) {
1282 # We're not going to find anything useful here
1283 # Be aware that the == '' check is explicit, since empty values will be
1284 # passed by some callers (T31116)
1287 } elseif ( in_array(
1289 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1291 $block = new Block();
1292 $block->fromMaster( $fromMaster );
1294 if ( $type !== null ) {
1295 $block->setTarget( $target );
1298 if ( $block->newLoad( $vagueTarget ) ) {
1306 * Get all blocks that match any IP from an array of IP addresses
1308 * @param array $ipChain List of IPs (strings), usually retrieved from the
1309 * X-Forwarded-For header of the request
1310 * @param bool $isAnon Exclude anonymous-only blocks if false
1311 * @param bool $fromMaster Whether to query the master or replica DB
1312 * @return array Array of Blocks
1315 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1316 if ( $ipChain === [] ) {
1321 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1322 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1323 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1324 # necessarily trust the header given to us, make sure that we are only
1325 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1326 # Do not treat private IP spaces as special as it may be desirable for wikis
1327 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1328 if ( !IP
::isValid( $ipaddr ) ) {
1331 # Don't check trusted IPs (includes local squids which will be in every request)
1332 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1335 # Check both the original IP (to check against single blocks), as well as build
1336 # the clause to check for rangeblocks for the given IP.
1337 $conds['ipb_address'][] = $ipaddr;
1338 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1341 if ( $conds === [] ) {
1345 if ( $fromMaster ) {
1346 $db = wfGetDB( DB_MASTER
);
1348 $db = wfGetDB( DB_REPLICA
);
1350 $conds = $db->makeList( $conds, LIST_OR
);
1352 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1354 $blockQuery = self
::getQueryInfo();
1355 $rows = $db->select(
1356 $blockQuery['tables'],
1357 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1361 $blockQuery['joins']
1365 foreach ( $rows as $row ) {
1366 $block = self
::newFromRow( $row );
1367 if ( !$block->isExpired() ) {
1376 * From a list of multiple blocks, find the most exact and strongest Block.
1378 * The logic for finding the "best" block is:
1379 * - Blocks that match the block's target IP are preferred over ones in a range
1380 * - Hardblocks are chosen over softblocks that prevent account creation
1381 * - Softblocks that prevent account creation are chosen over other softblocks
1382 * - Other softblocks are chosen over autoblocks
1383 * - If there are multiple exact or range blocks at the same level, the one chosen
1385 * This should be used when $blocks where retrieved from the user's IP address
1386 * and $ipChain is populated from the same IP address information.
1388 * @param array $blocks Array of Block objects
1389 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1390 * a block is to the server, and if a block matches exactly, or is in a range.
1391 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1393 * @throws MWException
1394 * @return Block|null The "best" block from the list
1396 public static function chooseBlock( array $blocks, array $ipChain ) {
1397 if ( $blocks === [] ) {
1399 } elseif ( count( $blocks ) == 1 ) {
1403 // Sort hard blocks before soft ones and secondarily sort blocks
1404 // that disable account creation before those that don't.
1405 usort( $blocks, function ( Block
$a, Block
$b ) {
1406 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1407 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1408 return strcmp( $bWeight, $aWeight ); // highest weight first
1411 $blocksListExact = [
1413 'disable_create' => false,
1417 $blocksListRange = [
1419 'disable_create' => false,
1423 $ipChain = array_reverse( $ipChain );
1425 /** @var Block $block */
1426 foreach ( $blocks as $block ) {
1427 // Stop searching if we have already have a "better" block. This
1428 // is why the order of the blocks matters
1429 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1431 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1435 foreach ( $ipChain as $checkip ) {
1436 $checkipHex = IP
::toHex( $checkip );
1437 if ( (string)$block->getTarget() === $checkip ) {
1438 if ( $block->isHardblock() ) {
1439 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1440 } elseif ( $block->prevents( 'createaccount' ) ) {
1441 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1442 } elseif ( $block->mAuto
) {
1443 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1445 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1447 // We found closest exact match in the ip list, so go to the next Block
1449 } elseif ( array_filter( $blocksListExact ) == []
1450 && $block->getRangeStart() <= $checkipHex
1451 && $block->getRangeEnd() >= $checkipHex
1453 if ( $block->isHardblock() ) {
1454 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1455 } elseif ( $block->prevents( 'createaccount' ) ) {
1456 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1457 } elseif ( $block->mAuto
) {
1458 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1460 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1467 if ( array_filter( $blocksListExact ) == [] ) {
1468 $blocksList = &$blocksListRange;
1470 $blocksList = &$blocksListExact;
1473 $chosenBlock = null;
1474 if ( $blocksList['hard'] ) {
1475 $chosenBlock = $blocksList['hard'];
1476 } elseif ( $blocksList['disable_create'] ) {
1477 $chosenBlock = $blocksList['disable_create'];
1478 } elseif ( $blocksList['other'] ) {
1479 $chosenBlock = $blocksList['other'];
1480 } elseif ( $blocksList['auto'] ) {
1481 $chosenBlock = $blocksList['auto'];
1483 throw new MWException( "Proxy block found, but couldn't be classified." );
1486 return $chosenBlock;
1490 * From an existing Block, get the target and the type of target.
1491 * Note that, except for null, it is always safe to treat the target
1492 * as a string; for User objects this will return User::__toString()
1493 * which in turn gives User::getName().
1495 * @param string|int|User|null $target
1496 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1498 public static function parseTarget( $target ) {
1499 # We may have been through this before
1500 if ( $target instanceof User
) {
1501 if ( IP
::isValid( $target->getName() ) ) {
1502 return [ $target, self
::TYPE_IP
];
1504 return [ $target, self
::TYPE_USER
];
1506 } elseif ( $target === null ) {
1507 return [ null, null ];
1510 $target = trim( $target );
1512 if ( IP
::isValid( $target ) ) {
1513 # We can still create a User if it's an IP address, but we need to turn
1514 # off validation checking (which would exclude IP addresses)
1516 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1520 } elseif ( IP
::isValidRange( $target ) ) {
1521 # Can't create a User from an IP range
1522 return [ IP
::sanitizeRange( $target ), self
::TYPE_RANGE
];
1525 # Consider the possibility that this is not a username at all
1526 # but actually an old subpage (T31797)
1527 if ( strpos( $target, '/' ) !== false ) {
1528 # An old subpage, drill down to the user behind it
1529 $target = explode( '/', $target )[0];
1532 $userObj = User
::newFromName( $target );
1533 if ( $userObj instanceof User
) {
1534 # Note that since numbers are valid usernames, a $target of "12345" will be
1535 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1536 # since hash characters are not valid in usernames or titles generally.
1537 return [ $userObj, self
::TYPE_USER
];
1539 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1540 # Autoblock reference in the form "#12345"
1541 return [ substr( $target, 1 ), self
::TYPE_AUTO
];
1545 return [ null, null ];
1550 * Get the type of target for this particular block
1551 * @return int Block::TYPE_ constant, will never be TYPE_ID
1553 public function getType() {
1560 * Get the target and target type for this particular Block. Note that for autoblocks,
1561 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1562 * in this situation.
1563 * @return array [ User|String, Block::TYPE_ constant ]
1564 * @todo FIXME: This should be an integral part of the Block member variables
1566 public function getTargetAndType() {
1567 return [ $this->getTarget(), $this->getType() ];
1571 * Get the target for this particular Block. Note that for autoblocks,
1572 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1573 * in this situation.
1574 * @return User|string
1576 public function getTarget() {
1577 return $this->target
;
1583 * @return mixed|string
1585 public function getExpiry() {
1586 return $this->mExpiry
;
1590 * Set the target for this block, and update $this->type accordingly
1591 * @param mixed $target
1593 public function setTarget( $target ) {
1594 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1598 * Get the user who implemented this block
1599 * @return User User object. May name a foreign user.
1601 public function getBlocker() {
1602 return $this->blocker
;
1606 * Set the user who implemented (or will implement) this block
1607 * @param User|string $user Local User object or username string
1609 public function setBlocker( $user ) {
1610 if ( is_string( $user ) ) {
1611 $user = User
::newFromName( $user, false );
1614 if ( $user->isAnon() && User
::isUsableName( $user->getName() ) ) {
1615 throw new InvalidArgumentException(
1616 'Blocker must be a local user or a name that cannot be a local user'
1620 $this->blocker
= $user;
1624 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1625 * the same as the block's, to a maximum of 24 hours.
1629 * @param WebResponse $response The response on which to set the cookie.
1631 public function setCookie( WebResponse
$response ) {
1632 // Calculate the default expiry time.
1633 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1635 // Use the Block's expiry time only if it's less than the default.
1636 $expiryTime = $this->getExpiry();
1637 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1638 $expiryTime = $maxExpiryTime;
1641 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1642 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1643 $cookieOptions = [ 'httpOnly' => false ];
1644 $cookieValue = $this->getCookieValue();
1645 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1649 * Unset the 'BlockID' cookie.
1653 * @param WebResponse $response The response on which to unset the cookie.
1655 public static function clearCookie( WebResponse
$response ) {
1656 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1660 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1661 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1666 * @return string The block ID, probably concatenated with "!" and the HMAC.
1668 public function getCookieValue() {
1669 $config = RequestContext
::getMain()->getConfig();
1670 $id = $this->getId();
1671 $secretKey = $config->get( 'SecretKey' );
1672 if ( !$secretKey ) {
1673 // If there's no secret key, don't append a HMAC.
1676 $hmac = MWCryptHash
::hmac( $id, $secretKey, false );
1677 $cookieValue = $id . '!' . $hmac;
1678 return $cookieValue;
1682 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1683 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1687 * @param string $cookieValue The string in which to find the ID.
1689 * @return int|null The block ID, or null if the HMAC is present and invalid.
1691 public static function getIdFromCookieValue( $cookieValue ) {
1692 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1693 $bangPos = strpos( $cookieValue, '!' );
1694 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
1695 // Get the site-wide secret key.
1696 $config = RequestContext
::getMain()->getConfig();
1697 $secretKey = $config->get( 'SecretKey' );
1698 if ( !$secretKey ) {
1699 // If there's no secret key, just use the ID as given.
1702 $storedHmac = substr( $cookieValue, $bangPos +
1 );
1703 $calculatedHmac = MWCryptHash
::hmac( $id, $secretKey, false );
1704 if ( $calculatedHmac === $storedHmac ) {
1712 * Get the key and parameters for the corresponding error message.
1715 * @param IContextSource $context
1718 public function getPermissionsError( IContextSource
$context ) {
1719 $params = $this->getBlockErrorParams( $context );
1721 $msg = 'blockedtext';
1722 if ( $this->getSystemBlockType() !== null ) {
1723 $msg = 'systemblockedtext';
1724 } elseif ( $this->mAuto
) {
1725 $msg = 'autoblockedtext';
1726 } elseif ( !$this->isSitewide() ) {
1727 $msg = 'blockedtext-partial';
1730 array_unshift( $params, $msg );
1736 * Get block information used in different block error messages
1739 * @param IContextSource $context
1742 public function getBlockErrorParams( IContextSource
$context ) {
1743 $blocker = $this->getBlocker();
1744 if ( $blocker instanceof User
) { // local user
1745 $blockerUserpage = $blocker->getUserPage();
1746 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1747 } else { // foreign user
1751 $reason = $this->mReason
;
1752 if ( $reason == '' ) {
1753 $reason = $context->msg( 'blockednoreason' )->text();
1756 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1757 * This could be a username, an IP range, or a single IP. */
1758 $intended = $this->getTarget();
1759 $systemBlockType = $this->getSystemBlockType();
1760 $lang = $context->getLanguage();
1765 $context->getRequest()->getIP(),
1767 $systemBlockType ??
$this->getId(),
1768 $lang->formatExpiry( $this->mExpiry
),
1770 $lang->userTimeAndDate( $this->mTimestamp
, $context->getUser() ),
1777 * Getting the restrictions will perform a database query if the restrictions
1778 * are not already loaded.
1781 * @return Restriction[]
1783 public function getRestrictions() {
1784 if ( $this->restrictions
=== null ) {
1785 // If the block id has not been set, then do not attempt to load the
1787 if ( !$this->mId
) {
1790 $this->restrictions
= BlockRestriction
::loadByBlockId( $this->mId
);
1793 return $this->restrictions
;
1800 * @param Restriction[] $restrictions
1803 public function setRestrictions( array $restrictions ) {
1804 $this->restrictions
= array_filter( $restrictions, function ( $restriction ) {
1805 return $restriction instanceof Restriction
;
1812 * Checks if a block applies to a particular title
1814 * This check does not consider whether `$this->prevents( 'editownusertalk' )`
1815 * returns false, as the identity of the user making the hypothetical edit
1816 * isn't known here (particularly in the case of IP hardblocks, range
1817 * blocks, and auto-blocks).
1819 * @param Title $title
1822 public function appliesToTitle( Title
$title ) {
1823 if ( $this->isSitewide() ) {
1827 $restrictions = $this->getRestrictions();
1828 foreach ( $restrictions as $restriction ) {
1829 if ( $restriction->matches( $title ) ) {
1838 * Checks if a block applies to a particular namespace
1845 public function appliesToNamespace( $ns ) {
1846 if ( $this->isSitewide() ) {
1850 // Blocks do not apply to virtual namespaces.
1855 $restriction = $this->findRestriction( NamespaceRestriction
::TYPE
, $ns );
1857 return (bool)$restriction;
1861 * Checks if a block applies to a particular page
1863 * This check does not consider whether `$this->prevents( 'editownusertalk' )`
1864 * returns false, as the identity of the user making the hypothetical edit
1865 * isn't known here (particularly in the case of IP hardblocks, range
1866 * blocks, and auto-blocks).
1870 * @param int $pageId
1873 public function appliesToPage( $pageId ) {
1874 if ( $this->isSitewide() ) {
1878 // If the pageId is not over zero, the block cannot apply to it.
1879 if ( $pageId <= 0 ) {
1883 $restriction = $this->findRestriction( PageRestriction
::TYPE
, $pageId );
1885 return (bool)$restriction;
1889 * Find Restriction by type and value.
1891 * @param string $type
1893 * @return Restriction|null
1895 private function findRestriction( $type, $value ) {
1896 $restrictions = $this->getRestrictions();
1897 foreach ( $restrictions as $restriction ) {
1898 if ( $restriction->getType() !== $type ) {
1902 if ( $restriction->getValue() === $value ) {
1903 return $restriction;