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\AbstractBlock
;
26 use MediaWiki\Block\BlockRestrictionStore
;
27 use MediaWiki\Block\Restriction\Restriction
;
28 use MediaWiki\Block\Restriction\NamespaceRestriction
;
29 use MediaWiki\Block\Restriction\PageRestriction
;
30 use MediaWiki\MediaWikiServices
;
32 class Block
extends AbstractBlock
{
49 public $mParentBlockId;
61 private $allowUsertalk;
64 private $blockCreateAccount;
66 /** @var User|string */
69 /** @var int Hack for foreign blocking (CentralAuth) */
70 private $forcedTargetID;
73 * @var int Block::TYPE_ constant. After the block has been loaded
74 * from the database, this can only be USER, IP or RANGE.
85 private $isAutoblocking;
87 /** @var string|null */
88 private $systemBlockType;
93 /** @var Restriction[] */
94 private $restrictions;
104 * Create a new block with specified option parameters on a user, IP or IP range.
106 * @param array $options Parameters of the block:
107 * address string|User Target user name, User object, IP address or IP range
108 * user int Override target user ID (for foreign users)
109 * by int User ID of the blocker
110 * reason string Reason of the block
111 * timestamp string The time at which the block comes into effect
112 * auto bool Is this an automatic block?
113 * expiry string Timestamp of expiration of the block or 'infinity'
114 * anonOnly bool Only disallow anonymous actions
115 * createAccount bool Disallow creation of new accounts
116 * enableAutoblock bool Enable automatic blocking
117 * hideName bool Hide the target user name
118 * blockEmail bool Disallow sending emails
119 * allowUsertalk bool Allow the target to edit its own talk page
120 * byText string Username of the blocker (for foreign users)
121 * systemBlock string Indicate that this block is automatically
122 * created by MediaWiki rather than being stored
123 * in the database. Value is a string to return
124 * from self::getSystemBlockType().
125 * sitewide bool Disallow editing all pages and all contribution
126 * actions, except those specifically allowed by
129 * @since 1.26 $options array
131 public function __construct( array $options = [] ) {
141 'createAccount' => false,
142 'enableAutoblock' => false,
144 'blockEmail' => false,
145 'allowUsertalk' => false,
147 'systemBlock' => null,
151 $options +
= $defaults;
153 $this->setTarget( $options['address'] );
155 if ( $this->target
instanceof User
&& $options['user'] ) {
156 # Needed for foreign users
157 $this->forcedTargetID
= $options['user'];
160 if ( $options['by'] ) {
162 $this->setBlocker( User
::newFromId( $options['by'] ) );
165 $this->setBlocker( $options['byText'] );
168 $this->setReason( $options['reason'] );
169 $this->setTimestamp( wfTimestamp( TS_MW
, $options['timestamp'] ) );
170 $this->setExpiry( wfGetDB( DB_REPLICA
)->decodeExpiry( $options['expiry'] ) );
173 $this->mAuto
= (bool)$options['auto'];
174 $this->setHideName( (bool)$options['hideName'] );
175 $this->isHardblock( !$options['anonOnly'] );
176 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
177 $this->isSitewide( (bool)$options['sitewide'] );
178 $this->isEmailBlocked( (bool)$options['blockEmail'] );
179 $this->isCreateAccountBlocked( (bool)$options['createAccount'] );
180 $this->isUsertalkEditAllowed( (bool)$options['allowUsertalk'] );
182 $this->mFromMaster
= false;
183 $this->systemBlockType
= $options['systemBlock'];
187 * Load a block from the block id.
189 * @param int $id Block id to search for
192 public static function newFromID( $id ) {
193 $dbr = wfGetDB( DB_REPLICA
);
194 $blockQuery = self
::getQueryInfo();
195 $res = $dbr->selectRow(
196 $blockQuery['tables'],
197 $blockQuery['fields'],
204 return self
::newFromRow( $res );
211 * Return the list of ipblocks fields that should be selected to create
213 * @deprecated since 1.31, use self::getQueryInfo() instead.
216 public static function selectFields() {
217 global $wgActorTableSchemaMigrationStage;
219 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
220 // If code is using this instead of self::getQueryInfo(), there's a
221 // decent chance it's going to try to directly access
222 // $row->ipb_by or $row->ipb_by_text and we can't give it
223 // useful values here once those aren't being used anymore.
224 throw new BadMethodCallException(
225 'Cannot use ' . __METHOD__
226 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
230 wfDeprecated( __METHOD__
, '1.31' );
236 'ipb_by_actor' => 'NULL',
240 'ipb_create_account',
241 'ipb_enable_autoblock',
245 'ipb_allow_usertalk',
246 'ipb_parent_block_id',
248 ] + CommentStore
::getStore()->getFields( 'ipb_reason' );
252 * Return the tables, fields, and join conditions to be selected to create
253 * a new block object.
255 * @return array With three keys:
256 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
257 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
258 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
260 public static function getQueryInfo() {
261 $commentQuery = CommentStore
::getStore()->getJoin( 'ipb_reason' );
262 $actorQuery = ActorMigration
::newMigration()->getJoin( 'ipb_by' );
264 'tables' => [ 'ipblocks' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
271 'ipb_create_account',
272 'ipb_enable_autoblock',
276 'ipb_allow_usertalk',
277 'ipb_parent_block_id',
279 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
280 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
285 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
286 * the blocking user or the block timestamp, only things which affect the blocked user
288 * @param Block $block
292 public function equals( Block
$block ) {
294 (string)$this->target
== (string)$block->target
295 && $this->type
== $block->type
296 && $this->mAuto
== $block->mAuto
297 && $this->isHardblock() == $block->isHardblock()
298 && $this->isCreateAccountBlocked() == $block->isCreateAccountBlocked()
299 && $this->getExpiry() == $block->getExpiry()
300 && $this->isAutoblocking() == $block->isAutoblocking()
301 && $this->getHideName() == $block->getHideName()
302 && $this->isEmailBlocked() == $block->isEmailBlocked()
303 && $this->isUsertalkEditAllowed() == $block->isUsertalkEditAllowed()
304 && $this->getReason() == $block->getReason()
305 && $this->isSitewide() == $block->isSitewide()
306 // Block::getRestrictions() may perform a database query, so keep it at
308 && $this->getBlockRestrictionStore()->equals(
309 $this->getRestrictions(), $block->getRestrictions()
315 * Load a block from the database which affects the already-set $this->target:
316 * 1) A block directly on the given user or IP
317 * 2) A rangeblock encompassing the given IP (smallest first)
318 * 3) An autoblock on the given IP
319 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
320 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
321 * @throws MWException
322 * @return bool Whether a relevant block was found
324 protected function newLoad( $vagueTarget = null ) {
325 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_REPLICA
);
327 if ( $this->type
!== null ) {
329 'ipb_address' => [ (string)$this->target
],
332 $conds = [ 'ipb_address' => [] ];
335 # Be aware that the != '' check is explicit, since empty values will be
336 # passed by some callers (T31116)
337 if ( $vagueTarget != '' ) {
338 list( $target, $type ) = self
::parseTarget( $vagueTarget );
340 case self
::TYPE_USER
:
341 # Slightly weird, but who are we to argue?
342 $conds['ipb_address'][] = (string)$target;
346 $conds['ipb_address'][] = (string)$target;
347 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
348 $conds = $db->makeList( $conds, LIST_OR
);
351 case self
::TYPE_RANGE
:
352 list( $start, $end ) = IP
::parseRange( $target );
353 $conds['ipb_address'][] = (string)$target;
354 $conds[] = self
::getRangeCond( $start, $end );
355 $conds = $db->makeList( $conds, LIST_OR
);
359 throw new MWException( "Tried to load block with invalid type" );
363 $blockQuery = self
::getQueryInfo();
365 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
368 # This result could contain a block on the user, a block on the IP, and a russian-doll
369 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
372 # Lower will be better
373 $bestBlockScore = 100;
375 foreach ( $res as $row ) {
376 $block = self
::newFromRow( $row );
378 # Don't use expired blocks
379 if ( $block->isExpired() ) {
383 # Don't use anon only blocks on users
384 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
388 if ( $block->getType() == self
::TYPE_RANGE
) {
389 # This is the number of bits that are allowed to vary in the block, give
390 # or take some floating point errors
392 $end = Wikimedia\base_convert
( ltrim( $block->getRangeEnd(), $prefix ), 16, 10 );
393 $start = Wikimedia\base_convert
( ltrim( $block->getRangeStart(), $prefix ), 16, 10 );
394 $size = log( $end - $start +
1, 2 );
396 # Rank a range block covering a single IP equally with a single-IP block
397 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
400 $score = $block->getType();
403 if ( $score < $bestBlockScore ) {
404 $bestBlockScore = $score;
409 if ( $bestRow !== null ) {
410 $this->initFromRow( $bestRow );
418 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
419 * @param string $start Hexadecimal IP representation
420 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
423 public static function getRangeCond( $start, $end = null ) {
424 if ( $end === null ) {
427 # Per T16634, we want to include relevant active rangeblocks; for
428 # rangeblocks, we want to include larger ranges which enclose the given
429 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
430 # so we can improve performance by filtering on a LIKE clause
431 $chunk = self
::getIpFragment( $start );
432 $dbr = wfGetDB( DB_REPLICA
);
433 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
435 # Fairly hard to make a malicious SQL statement out of hex characters,
436 # but stranger things have happened...
437 $safeStart = $dbr->addQuotes( $start );
438 $safeEnd = $dbr->addQuotes( $end );
440 return $dbr->makeList(
442 "ipb_range_start $like",
443 "ipb_range_start <= $safeStart",
444 "ipb_range_end >= $safeEnd",
451 * Get the component of an IP address which is certain to be the same between an IP
452 * address and a rangeblock containing that IP address.
453 * @param string $hex Hexadecimal IP representation
456 protected static function getIpFragment( $hex ) {
457 global $wgBlockCIDRLimit;
458 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
459 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
461 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
466 * Given a database row from the ipblocks table, initialize
468 * @param stdClass $row A row from the ipblocks table
470 protected function initFromRow( $row ) {
471 $this->setTarget( $row->ipb_address
);
472 $this->setBlocker( User
::newFromAnyId(
473 $row->ipb_by
, $row->ipb_by_text
, $row->ipb_by_actor ??
null
476 $this->setTimestamp( wfTimestamp( TS_MW
, $row->ipb_timestamp
) );
477 $this->mAuto
= $row->ipb_auto
;
478 $this->setHideName( $row->ipb_deleted
);
479 $this->mId
= (int)$row->ipb_id
;
480 $this->mParentBlockId
= $row->ipb_parent_block_id
;
482 // I wish I didn't have to do this
483 $db = wfGetDB( DB_REPLICA
);
484 $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry
) );
486 CommentStore
::getStore()
487 // Legacy because $row may have come from self::selectFields()
488 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
491 $this->isHardblock( !$row->ipb_anon_only
);
492 $this->isAutoblocking( $row->ipb_enable_autoblock
);
493 $this->isSitewide( (bool)$row->ipb_sitewide
);
495 $this->isCreateAccountBlocked( $row->ipb_create_account
);
496 $this->isEmailBlocked( $row->ipb_block_email
);
497 $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk
);
501 * Create a new Block object from a database row
502 * @param stdClass $row Row from the ipblocks table
505 public static function newFromRow( $row ) {
507 $block->initFromRow( $row );
512 * Delete the row from the IP blocks table.
514 * @throws MWException
517 public function delete() {
518 if ( wfReadOnly() ) {
522 if ( !$this->getId() ) {
523 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
526 $dbw = wfGetDB( DB_MASTER
);
528 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
529 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
531 $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
532 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
534 return $dbw->affectedRows() > 0;
538 * Insert a block into the block table. Will fail if there is a conflicting
539 * block (same name and options) already in the database.
541 * @param IDatabase|null $dbw If you have one available
542 * @return bool|array False on failure, assoc array on success:
543 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
545 public function insert( $dbw = null ) {
546 global $wgBlockDisablesLogin;
548 if ( $this->getSystemBlockType() !== null ) {
549 throw new MWException( 'Cannot insert a system block into the database' );
551 if ( !$this->getBlocker() ||
$this->getBlocker()->getName() === '' ) {
552 throw new MWException( 'Cannot insert a block without a blocker set' );
555 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
557 if ( $dbw === null ) {
558 $dbw = wfGetDB( DB_MASTER
);
561 self
::purgeExpired();
563 $row = $this->getDatabaseArray( $dbw );
565 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
566 $affected = $dbw->affectedRows();
568 $this->setId( $dbw->insertId() );
569 if ( $this->restrictions
) {
570 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
574 # Don't collide with expired blocks.
575 # Do this after trying to insert to avoid locking.
577 # T96428: The ipb_address index uses a prefix on a field, so
578 # use a standard SELECT + DELETE to avoid annoying gap locks.
579 $ids = $dbw->selectFieldValues( 'ipblocks',
582 'ipb_address' => $row['ipb_address'],
583 'ipb_user' => $row['ipb_user'],
584 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
589 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
590 $this->getBlockRestrictionStore()->deleteByBlockId( $ids );
591 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
592 $affected = $dbw->affectedRows();
593 $this->setId( $dbw->insertId() );
594 if ( $this->restrictions
) {
595 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
601 $auto_ipd_ids = $this->doRetroactiveAutoblock();
603 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
604 // Change user login token to force them to be logged out.
605 $this->target
->setToken();
606 $this->target
->saveSettings();
609 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
616 * Update a block in the DB with new parameters.
617 * The ID field needs to be loaded first.
619 * @return bool|array False on failure, array on success:
620 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
622 public function update() {
623 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
624 $dbw = wfGetDB( DB_MASTER
);
626 $dbw->startAtomic( __METHOD__
);
628 $result = $dbw->update(
630 $this->getDatabaseArray( $dbw ),
631 [ 'ipb_id' => $this->getId() ],
635 // Only update the restrictions if they have been modified.
636 if ( $this->restrictions
!== null ) {
637 // An empty array should remove all of the restrictions.
638 if ( empty( $this->restrictions
) ) {
639 $success = $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
641 $success = $this->getBlockRestrictionStore()->update( $this->restrictions
);
643 // Update the result. The first false is the result, otherwise, true.
644 $result = $result && $success;
647 if ( $this->isAutoblocking() ) {
648 // update corresponding autoblock(s) (T50813)
651 $this->getAutoblockUpdateArray( $dbw ),
652 [ 'ipb_parent_block_id' => $this->getId() ],
656 // Only update the restrictions if they have been modified.
657 if ( $this->restrictions
!== null ) {
658 $this->getBlockRestrictionStore()->updateByParentBlockId( $this->getId(), $this->restrictions
);
661 // autoblock no longer required, delete corresponding autoblock(s)
662 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
665 [ 'ipb_parent_block_id' => $this->getId() ],
670 $dbw->endAtomic( __METHOD__
);
673 $auto_ipd_ids = $this->doRetroactiveAutoblock();
674 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
681 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
682 * @param IDatabase $dbw
685 protected function getDatabaseArray( IDatabase
$dbw ) {
686 $expiry = $dbw->encodeExpiry( $this->getExpiry() );
688 if ( $this->forcedTargetID
) {
689 $uid = $this->forcedTargetID
;
691 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
695 'ipb_address' => (string)$this->target
,
697 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
698 'ipb_auto' => $this->mAuto
,
699 'ipb_anon_only' => !$this->isHardblock(),
700 'ipb_create_account' => $this->isCreateAccountBlocked(),
701 'ipb_enable_autoblock' => $this->isAutoblocking(),
702 'ipb_expiry' => $expiry,
703 'ipb_range_start' => $this->getRangeStart(),
704 'ipb_range_end' => $this->getRangeEnd(),
705 'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
706 'ipb_block_email' => $this->isEmailBlocked(),
707 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
708 'ipb_parent_block_id' => $this->mParentBlockId
,
709 'ipb_sitewide' => $this->isSitewide(),
710 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
711 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
717 * @param IDatabase $dbw
720 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
722 'ipb_create_account' => $this->isCreateAccountBlocked(),
723 'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
724 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
725 'ipb_sitewide' => $this->isSitewide(),
726 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
727 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
731 * Retroactively autoblocks the last IP used by the user (if it is a user)
732 * blocked by this Block.
734 * @return array Block IDs of retroactive autoblocks made
736 protected function doRetroactiveAutoblock() {
738 # If autoblock is enabled, autoblock the LAST IP(s) used
739 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
740 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
742 $continue = Hooks
::run(
743 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
746 self
::defaultRetroactiveAutoblock( $this, $blockIds );
753 * Retroactively autoblocks the last IP used by the user (if it is a user)
754 * blocked by this Block. This will use the recentchanges table.
756 * @param Block $block
757 * @param array &$blockIds
759 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
762 // No IPs are in recentchanges table, so nothing to select
763 if ( !$wgPutIPinRC ) {
767 // Autoblocks only apply to TYPE_USER
768 if ( $block->getType() !== self
::TYPE_USER
) {
771 $target = $block->getTarget(); // TYPE_USER => always a User object
773 $dbr = wfGetDB( DB_REPLICA
);
774 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
776 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
778 // Just the last IP used.
779 $options['LIMIT'] = 1;
782 [ 'recentchanges' ] +
$rcQuery['tables'],
790 if ( !$res->numRows() ) {
791 # No results, don't autoblock anything
792 wfDebug( "No IP found to retroactively autoblock\n" );
794 foreach ( $res as $row ) {
796 $id = $block->doAutoblock( $row->rc_ip
);
806 * Checks whether a given IP is on the autoblock whitelist.
807 * TODO: this probably belongs somewhere else, but not sure where...
809 * @param string $ip The IP to check
812 public static function isWhitelistedFromAutoblocks( $ip ) {
813 // Try to get the autoblock_whitelist from the cache, as it's faster
814 // than getting the msg raw and explode()'ing it.
815 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
816 $lines = $cache->getWithSetCallback(
817 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
819 function ( $curValue, &$ttl, array &$setOpts ) {
820 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
822 return explode( "\n",
823 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
827 wfDebug( "Checking the autoblock whitelist..\n" );
829 foreach ( $lines as $line ) {
831 if ( substr( $line, 0, 1 ) !== '*' ) {
835 $wlEntry = substr( $line, 1 );
836 $wlEntry = trim( $wlEntry );
838 wfDebug( "Checking $ip against $wlEntry..." );
840 # Is the IP in this range?
841 if ( IP
::isInRange( $ip, $wlEntry ) ) {
842 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
845 wfDebug( " No match\n" );
853 * Autoblocks the given IP, referring to this Block.
855 * @param string $autoblockIP The IP to autoblock.
856 * @return int|bool Block ID if an autoblock was inserted, false if not.
858 public function doAutoblock( $autoblockIP ) {
859 # If autoblocks are disabled, go away.
860 if ( !$this->isAutoblocking() ) {
864 # Don't autoblock for system blocks
865 if ( $this->getSystemBlockType() !== null ) {
866 throw new MWException( 'Cannot autoblock from a system block' );
869 # Check for presence on the autoblock whitelist.
870 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
874 // Avoid PHP 7.1 warning of passing $this by reference
876 # Allow hooks to cancel the autoblock.
877 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
878 wfDebug( "Autoblock aborted by hook.\n" );
882 # It's okay to autoblock. Go ahead and insert/update the block...
884 # Do not add a *new* block if the IP is already blocked.
885 $ipblock = self
::newFromTarget( $autoblockIP );
887 # Check if the block is an autoblock and would exceed the user block
888 # if renewed. If so, do nothing, otherwise prolong the block time...
889 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
890 $this->getExpiry() > self
::getAutoblockExpiry( $ipblock->getTimestamp() )
892 # Reset block timestamp to now and its expiry to
893 # $wgAutoblockExpiry in the future
894 $ipblock->updateTimestamp();
899 # Make a new block object with the desired properties.
900 $autoblock = new Block
;
901 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
902 $autoblock->setTarget( $autoblockIP );
903 $autoblock->setBlocker( $this->getBlocker() );
904 $autoblock->setReason(
905 wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
906 ->inContentLanguage()->plain()
908 $timestamp = wfTimestampNow();
909 $autoblock->setTimestamp( $timestamp );
910 $autoblock->mAuto
= 1;
911 $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
912 # Continue suppressing the name if needed
913 $autoblock->setHideName( $this->getHideName() );
914 $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
915 $autoblock->mParentBlockId
= $this->mId
;
916 $autoblock->isSitewide( $this->isSitewide() );
917 $autoblock->setRestrictions( $this->getRestrictions() );
919 if ( $this->getExpiry() == 'infinity' ) {
920 # Original block was indefinite, start an autoblock now
921 $autoblock->setExpiry( self
::getAutoblockExpiry( $timestamp ) );
923 # If the user is already blocked with an expiry date, we don't
924 # want to pile on top of that.
925 $autoblock->setExpiry( min( $this->getExpiry(), self
::getAutoblockExpiry( $timestamp ) ) );
928 # Insert the block...
929 $status = $autoblock->insert();
936 * Check if a block has expired. Delete it if it is.
939 public function deleteIfExpired() {
940 if ( $this->isExpired() ) {
941 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
945 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
953 * Has the block expired?
956 public function isExpired() {
957 $timestamp = wfTimestampNow();
958 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
960 if ( !$this->getExpiry() ) {
963 return $timestamp > $this->getExpiry();
968 * Is the block address valid (i.e. not a null string?)
970 * @deprecated since 1.33 No longer needed in core.
973 public function isValid() {
974 wfDeprecated( __METHOD__
, '1.33' );
975 return $this->getTarget() != null;
979 * Update the timestamp on autoblocks.
981 public function updateTimestamp() {
982 if ( $this->mAuto
) {
983 $this->setTimestamp( wfTimestamp() );
984 $this->setExpiry( self
::getAutoblockExpiry( $this->getTimestamp() ) );
986 $dbw = wfGetDB( DB_MASTER
);
987 $dbw->update( 'ipblocks',
989 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
990 'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
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 return $this->getBlocker()->getId();
1048 * Get the username of the blocking sysop
1052 public function getByName() {
1053 return $this->getBlocker()->getName();
1060 public function getId() {
1067 * @param int $blockId
1070 private function setId( $blockId ) {
1071 $this->mId
= (int)$blockId;
1073 if ( is_array( $this->restrictions
) ) {
1074 $this->restrictions
= $this->getBlockRestrictionStore()->setBlockId(
1075 $blockId, $this->restrictions
1083 * Get the reason given for creating the block
1088 public function getReason() {
1089 return $this->mReason
;
1093 * Set the reason for creating the block
1096 * @param string $reason
1098 public function setReason( $reason ) {
1099 $this->mReason
= $reason;
1103 * Get whether the block hides the target's username
1106 * @return bool The block hides the username
1108 public function getHideName() {
1109 return $this->mHideName
;
1113 * Set whether ths block hides the target's username
1116 * @param bool $hideName The block hides the username
1118 public function setHideName( $hideName ) {
1119 $this->mHideName
= $hideName;
1123 * Get the system block type, if any
1125 * @return string|null
1127 public function getSystemBlockType() {
1128 return $this->systemBlockType
;
1132 * Get/set a flag determining whether the master is used for reads
1134 * @param bool|null $x
1137 public function fromMaster( $x = null ) {
1138 return wfSetVar( $this->mFromMaster
, $x );
1142 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1143 * @param bool|null $x
1146 public function isHardblock( $x = null ) {
1147 wfSetVar( $this->isHardblock
, $x );
1149 # You can't *not* hardblock a user
1150 return $this->getType() == self
::TYPE_USER
1152 : $this->isHardblock
;
1156 * @param null|bool $x
1159 public function isAutoblocking( $x = null ) {
1160 wfSetVar( $this->isAutoblocking
, $x );
1162 # You can't put an autoblock on an IP or range as we don't have any history to
1163 # look over to get more IPs from
1164 return $this->getType() == self
::TYPE_USER
1165 ?
$this->isAutoblocking
1170 * Indicates that the block is a sitewide block. This means the user is
1171 * prohibited from editing any page on the site (other than their own talk
1175 * @param null|bool $x
1178 public function isSitewide( $x = null ) {
1179 return wfSetVar( $this->isSitewide
, $x );
1183 * Get or set the flag indicating whether this block blocks the target from
1184 * creating an account. (Note that the flag may be overridden depending on
1188 * @param null|bool $x Value to set (if null, just get the property value)
1189 * @return bool Value of the property
1191 public function isCreateAccountBlocked( $x = null ) {
1192 return wfSetVar( $this->blockCreateAccount
, $x );
1196 * Get or set the flag indicating whether this block blocks the target from
1197 * sending emails. (Note that the flag may be overridden depending on
1201 * @param null|bool $x Value to set (if null, just get the property value)
1202 * @return bool Value of the property
1204 public function isEmailBlocked( $x = null ) {
1205 return wfSetVar( $this->mBlockEmail
, $x );
1209 * Get or set the flag indicating whether this block blocks the target from
1210 * editing their own user talk page. (Note that the flag may be overridden
1211 * depending on global configs.)
1214 * @param null|bool $x Value to set (if null, just get the property value)
1215 * @return bool Value of the property
1217 public function isUsertalkEditAllowed( $x = null ) {
1218 return wfSetVar( $this->allowUsertalk
, $x );
1222 * Determine whether the Block prevents a given right. A right
1223 * may be blacklisted or whitelisted, or determined from a
1224 * property on the Block object. For certain rights, the property
1225 * may be overridden according to global configs.
1228 * @param string $right Right to check
1229 * @return bool|null null if unrecognized right or unset property
1231 public function appliesToRight( $right ) {
1232 $config = RequestContext
::getMain()->getConfig();
1233 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1238 // TODO: fix this case to return proper value
1241 case 'createaccount':
1242 $res = $this->isCreateAccountBlocked();
1245 $res = $this->isEmailBlocked();
1248 // Until T6995 is completed
1249 $res = $this->isSitewide();
1258 if ( !$res && $blockDisablesLogin ) {
1259 // If a block would disable login, then it should
1260 // prevent any right that all users cannot do
1262 $res = $anon->isAllowed( $right ) ?
$res : true;
1269 * Get/set whether the Block prevents a given action
1271 * @deprecated since 1.33, use appliesToRight to determine block
1272 * behaviour, and specific methods to get/set properties
1273 * @param string $action Action to check
1274 * @param bool|null $x Value for set, or null to just get value
1275 * @return bool|null Null for unrecognized rights.
1277 public function prevents( $action, $x = null ) {
1278 $config = RequestContext
::getMain()->getConfig();
1279 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1280 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1283 switch ( $action ) {
1285 # For now... <evil laugh>
1288 case 'createaccount':
1289 $res = wfSetVar( $this->blockCreateAccount
, $x );
1292 $res = wfSetVar( $this->mBlockEmail
, $x );
1295 // Until T6995 is completed
1296 $res = $this->isSitewide();
1298 case 'editownusertalk':
1299 // NOTE: this check is not reliable on partial blocks
1300 // since partially blocked users are always allowed to edit
1301 // their own talk page unless a restriction exists on the
1302 // page or User_talk: namespace
1303 wfSetVar( $this->allowUsertalk
, $x === null ?
null : !$x );
1304 $res = !$this->isUsertalkEditAllowed();
1306 // edit own user talk can be disabled by config
1307 if ( !$blockAllowsUTEdit ) {
1318 if ( !$res && $blockDisablesLogin ) {
1319 // If a block would disable login, then it should
1320 // prevent any action that all users cannot do
1322 $res = $anon->isAllowed( $action ) ?
$res : true;
1329 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1330 * @return string Text is escaped
1332 public function getRedactedName() {
1333 if ( $this->mAuto
) {
1334 return Html
::element(
1336 [ 'class' => 'mw-autoblockid' ],
1337 wfMessage( 'autoblockid', $this->mId
)->text()
1340 return htmlspecialchars( $this->getTarget() );
1345 * Get a timestamp of the expiry for autoblocks
1347 * @param string|int $timestamp
1350 public static function getAutoblockExpiry( $timestamp ) {
1351 global $wgAutoblockExpiry;
1353 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1357 * Purge expired blocks from the ipblocks table
1359 public static function purgeExpired() {
1360 if ( wfReadOnly() ) {
1364 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1365 wfGetDB( DB_MASTER
),
1367 function ( IDatabase
$dbw, $fname ) {
1368 $ids = $dbw->selectFieldValues( 'ipblocks',
1370 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1374 $blockRestrictionStore = MediaWikiServices
::getInstance()->getBlockRestrictionStore();
1375 $blockRestrictionStore->deleteByBlockId( $ids );
1377 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1384 * Given a target and the target's type, get an existing Block object if possible.
1385 * @param string|User|int $specificTarget A block target, which may be one of several types:
1386 * * A user to block, in which case $target will be a User
1387 * * An IP to block, in which case $target will be a User generated by using
1388 * User::newFromName( $ip, false ) to turn off name validation
1389 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1390 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1392 * Calling this with a user, IP address or range will not select autoblocks, and will
1393 * only select a block where the targets match exactly (so looking for blocks on
1394 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1395 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1396 * affects that target (so for an IP address, get ranges containing that IP; and also
1397 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1398 * @param bool $fromMaster Whether to use the DB_MASTER database
1399 * @return Block|null (null if no relevant block could be found). The target and type
1400 * of the returned Block will refer to the actual block which was found, which might
1401 * not be the same as the target you gave if you used $vagueTarget!
1403 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1404 list( $target, $type ) = self
::parseTarget( $specificTarget );
1405 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1406 return self
::newFromID( $target );
1408 } elseif ( $target === null && $vagueTarget == '' ) {
1409 # We're not going to find anything useful here
1410 # Be aware that the == '' check is explicit, since empty values will be
1411 # passed by some callers (T31116)
1414 } elseif ( in_array(
1416 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1418 $block = new Block();
1419 $block->fromMaster( $fromMaster );
1421 if ( $type !== null ) {
1422 $block->setTarget( $target );
1425 if ( $block->newLoad( $vagueTarget ) ) {
1433 * Get all blocks that match any IP from an array of IP addresses
1435 * @param array $ipChain List of IPs (strings), usually retrieved from the
1436 * X-Forwarded-For header of the request
1437 * @param bool $isAnon Exclude anonymous-only blocks if false
1438 * @param bool $fromMaster Whether to query the master or replica DB
1439 * @return array Array of Blocks
1442 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1443 if ( $ipChain === [] ) {
1448 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1449 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1450 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1451 # necessarily trust the header given to us, make sure that we are only
1452 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1453 # Do not treat private IP spaces as special as it may be desirable for wikis
1454 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1455 if ( !IP
::isValid( $ipaddr ) ) {
1458 # Don't check trusted IPs (includes local squids which will be in every request)
1459 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1462 # Check both the original IP (to check against single blocks), as well as build
1463 # the clause to check for rangeblocks for the given IP.
1464 $conds['ipb_address'][] = $ipaddr;
1465 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1468 if ( $conds === [] ) {
1472 if ( $fromMaster ) {
1473 $db = wfGetDB( DB_MASTER
);
1475 $db = wfGetDB( DB_REPLICA
);
1477 $conds = $db->makeList( $conds, LIST_OR
);
1479 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1481 $blockQuery = self
::getQueryInfo();
1482 $rows = $db->select(
1483 $blockQuery['tables'],
1484 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1488 $blockQuery['joins']
1492 foreach ( $rows as $row ) {
1493 $block = self
::newFromRow( $row );
1494 if ( !$block->isExpired() ) {
1503 * From a list of multiple blocks, find the most exact and strongest Block.
1505 * The logic for finding the "best" block is:
1506 * - Blocks that match the block's target IP are preferred over ones in a range
1507 * - Hardblocks are chosen over softblocks that prevent account creation
1508 * - Softblocks that prevent account creation are chosen over other softblocks
1509 * - Other softblocks are chosen over autoblocks
1510 * - If there are multiple exact or range blocks at the same level, the one chosen
1512 * This should be used when $blocks where retrieved from the user's IP address
1513 * and $ipChain is populated from the same IP address information.
1515 * @param array $blocks Array of Block objects
1516 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1517 * a block is to the server, and if a block matches exactly, or is in a range.
1518 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1520 * @throws MWException
1521 * @return Block|null The "best" block from the list
1523 public static function chooseBlock( array $blocks, array $ipChain ) {
1524 if ( $blocks === [] ) {
1526 } elseif ( count( $blocks ) == 1 ) {
1530 // Sort hard blocks before soft ones and secondarily sort blocks
1531 // that disable account creation before those that don't.
1532 usort( $blocks, function ( Block
$a, Block
$b ) {
1533 $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1534 $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1535 return strcmp( $bWeight, $aWeight ); // highest weight first
1538 $blocksListExact = [
1540 'disable_create' => false,
1544 $blocksListRange = [
1546 'disable_create' => false,
1550 $ipChain = array_reverse( $ipChain );
1552 /** @var Block $block */
1553 foreach ( $blocks as $block ) {
1554 // Stop searching if we have already have a "better" block. This
1555 // is why the order of the blocks matters
1556 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1558 } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1562 foreach ( $ipChain as $checkip ) {
1563 $checkipHex = IP
::toHex( $checkip );
1564 if ( (string)$block->getTarget() === $checkip ) {
1565 if ( $block->isHardblock() ) {
1566 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1567 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1568 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1569 } elseif ( $block->mAuto
) {
1570 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1572 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1574 // We found closest exact match in the ip list, so go to the next Block
1576 } elseif ( array_filter( $blocksListExact ) == []
1577 && $block->getRangeStart() <= $checkipHex
1578 && $block->getRangeEnd() >= $checkipHex
1580 if ( $block->isHardblock() ) {
1581 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1582 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1583 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1584 } elseif ( $block->mAuto
) {
1585 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1587 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1594 if ( array_filter( $blocksListExact ) == [] ) {
1595 $blocksList = &$blocksListRange;
1597 $blocksList = &$blocksListExact;
1600 $chosenBlock = null;
1601 if ( $blocksList['hard'] ) {
1602 $chosenBlock = $blocksList['hard'];
1603 } elseif ( $blocksList['disable_create'] ) {
1604 $chosenBlock = $blocksList['disable_create'];
1605 } elseif ( $blocksList['other'] ) {
1606 $chosenBlock = $blocksList['other'];
1607 } elseif ( $blocksList['auto'] ) {
1608 $chosenBlock = $blocksList['auto'];
1610 throw new MWException( "Proxy block found, but couldn't be classified." );
1613 return $chosenBlock;
1617 * From an existing Block, get the target and the type of target.
1618 * Note that, except for null, it is always safe to treat the target
1619 * as a string; for User objects this will return User::__toString()
1620 * which in turn gives User::getName().
1622 * @param string|int|User|null $target
1623 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1625 public static function parseTarget( $target ) {
1626 # We may have been through this before
1627 if ( $target instanceof User
) {
1628 if ( IP
::isValid( $target->getName() ) ) {
1629 return [ $target, self
::TYPE_IP
];
1631 return [ $target, self
::TYPE_USER
];
1633 } elseif ( $target === null ) {
1634 return [ null, null ];
1637 $target = trim( $target );
1639 if ( IP
::isValid( $target ) ) {
1640 # We can still create a User if it's an IP address, but we need to turn
1641 # off validation checking (which would exclude IP addresses)
1643 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1647 } elseif ( IP
::isValidRange( $target ) ) {
1648 # Can't create a User from an IP range
1649 return [ IP
::sanitizeRange( $target ), self
::TYPE_RANGE
];
1652 # Consider the possibility that this is not a username at all
1653 # but actually an old subpage (T31797)
1654 if ( strpos( $target, '/' ) !== false ) {
1655 # An old subpage, drill down to the user behind it
1656 $target = explode( '/', $target )[0];
1659 $userObj = User
::newFromName( $target );
1660 if ( $userObj instanceof User
) {
1661 # Note that since numbers are valid usernames, a $target of "12345" will be
1662 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1663 # since hash characters are not valid in usernames or titles generally.
1664 return [ $userObj, self
::TYPE_USER
];
1666 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1667 # Autoblock reference in the form "#12345"
1668 return [ substr( $target, 1 ), self
::TYPE_AUTO
];
1672 return [ null, null ];
1677 * Get the type of target for this particular block. Autoblocks have whichever type
1678 * corresponds to their target, so to detect if a block is an autoblock, we have to
1679 * check the mAuto property instead.
1680 * @return int Block::TYPE_ constant, will never be TYPE_ID
1682 public function getType() {
1689 * Get the target and target type for this particular Block. Note that for autoblocks,
1690 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1691 * in this situation.
1692 * @return array [ User|String, Block::TYPE_ constant ]
1693 * @todo FIXME: This should be an integral part of the Block member variables
1695 public function getTargetAndType() {
1696 return [ $this->getTarget(), $this->getType() ];
1700 * Get the target for this particular Block. Note that for autoblocks,
1701 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1702 * in this situation.
1703 * @return User|string
1705 public function getTarget() {
1706 return $this->target
;
1710 * Get the block expiry time
1715 public function getExpiry() {
1716 return $this->mExpiry
;
1720 * Set the block expiry time
1723 * @param string $expiry
1725 public function setExpiry( $expiry ) {
1726 $this->mExpiry
= $expiry;
1730 * Get the timestamp indicating when the block was created
1735 public function getTimestamp() {
1736 return $this->mTimestamp
;
1740 * Set the timestamp indicating when the block was created
1743 * @param string $timestamp
1745 public function setTimestamp( $timestamp ) {
1746 $this->mTimestamp
= $timestamp;
1750 * Set the target for this block, and update $this->type accordingly
1751 * @param mixed $target
1753 public function setTarget( $target ) {
1754 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1758 * Get the user who implemented this block
1759 * @return User User object. May name a foreign user.
1761 public function getBlocker() {
1762 return $this->blocker
;
1766 * Set the user who implemented (or will implement) this block
1767 * @param User|string $user Local User object or username string
1769 public function setBlocker( $user ) {
1770 if ( is_string( $user ) ) {
1771 $user = User
::newFromName( $user, false );
1774 if ( $user->isAnon() && User
::isUsableName( $user->getName() ) ) {
1775 throw new InvalidArgumentException(
1776 'Blocker must be a local user or a name that cannot be a local user'
1780 $this->blocker
= $user;
1784 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1785 * the same as the block's, to a maximum of 24 hours.
1789 * @param WebResponse $response The response on which to set the cookie.
1791 public function setCookie( WebResponse
$response ) {
1792 // Calculate the default expiry time.
1793 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1795 // Use the Block's expiry time only if it's less than the default.
1796 $expiryTime = $this->getExpiry();
1797 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1798 $expiryTime = $maxExpiryTime;
1801 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1802 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1803 $cookieOptions = [ 'httpOnly' => false ];
1804 $cookieValue = $this->getCookieValue();
1805 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1809 * Unset the 'BlockID' cookie.
1813 * @param WebResponse $response The response on which to unset the cookie.
1815 public static function clearCookie( WebResponse
$response ) {
1816 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1820 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1821 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1826 * @return string The block ID, probably concatenated with "!" and the HMAC.
1828 public function getCookieValue() {
1829 $config = RequestContext
::getMain()->getConfig();
1830 $id = $this->getId();
1831 $secretKey = $config->get( 'SecretKey' );
1832 if ( !$secretKey ) {
1833 // If there's no secret key, don't append a HMAC.
1836 $hmac = MWCryptHash
::hmac( $id, $secretKey, false );
1837 $cookieValue = $id . '!' . $hmac;
1838 return $cookieValue;
1842 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1843 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1847 * @param string $cookieValue The string in which to find the ID.
1849 * @return int|null The block ID, or null if the HMAC is present and invalid.
1851 public static function getIdFromCookieValue( $cookieValue ) {
1852 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1853 $bangPos = strpos( $cookieValue, '!' );
1854 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
1855 // Get the site-wide secret key.
1856 $config = RequestContext
::getMain()->getConfig();
1857 $secretKey = $config->get( 'SecretKey' );
1858 if ( !$secretKey ) {
1859 // If there's no secret key, just use the ID as given.
1862 $storedHmac = substr( $cookieValue, $bangPos +
1 );
1863 $calculatedHmac = MWCryptHash
::hmac( $id, $secretKey, false );
1864 if ( $calculatedHmac === $storedHmac ) {
1872 * Get the key and parameters for the corresponding error message.
1875 * @param IContextSource $context
1878 public function getPermissionsError( IContextSource
$context ) {
1879 $params = $this->getBlockErrorParams( $context );
1881 $msg = 'blockedtext';
1882 if ( $this->getSystemBlockType() !== null ) {
1883 $msg = 'systemblockedtext';
1884 } elseif ( $this->mAuto
) {
1885 $msg = 'autoblockedtext';
1886 } elseif ( !$this->isSitewide() ) {
1887 $msg = 'blockedtext-partial';
1890 array_unshift( $params, $msg );
1896 * Get block information used in different block error messages
1899 * @param IContextSource $context
1902 public function getBlockErrorParams( IContextSource
$context ) {
1903 $blocker = $this->getBlocker();
1904 if ( $blocker instanceof User
) { // local user
1905 $blockerUserpage = $blocker->getUserPage();
1906 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1907 } else { // foreign user
1911 $reason = $this->getReason();
1912 if ( $reason == '' ) {
1913 $reason = $context->msg( 'blockednoreason' )->text();
1916 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1917 * This could be a username, an IP range, or a single IP. */
1918 $intended = $this->getTarget();
1919 $systemBlockType = $this->getSystemBlockType();
1920 $lang = $context->getLanguage();
1925 $context->getRequest()->getIP(),
1927 $systemBlockType ??
$this->getId(),
1928 $lang->formatExpiry( $this->getExpiry() ),
1930 $lang->userTimeAndDate( $this->getTimestamp(), $context->getUser() ),
1937 * Getting the restrictions will perform a database query if the restrictions
1938 * are not already loaded.
1941 * @return Restriction[]
1943 public function getRestrictions() {
1944 if ( $this->restrictions
=== null ) {
1945 // If the block id has not been set, then do not attempt to load the
1947 if ( !$this->mId
) {
1950 $this->restrictions
= $this->getBlockRestrictionStore()->loadByBlockId( $this->mId
);
1953 return $this->restrictions
;
1960 * @param Restriction[] $restrictions
1963 public function setRestrictions( array $restrictions ) {
1964 $this->restrictions
= array_filter( $restrictions, function ( $restriction ) {
1965 return $restriction instanceof Restriction
;
1972 * Determine whether the block allows the user to edit their own
1973 * user talk page. This is done separately from Block::appliesToRight
1974 * because there is no right for editing one's own user talk page
1975 * and because the user's talk page needs to be passed into the
1976 * Block object, which is unaware of the user.
1978 * The ipb_allow_usertalk flag (which corresponds to the property
1979 * allowUsertalk) is used on sitewide blocks and partial blocks
1980 * that contain a namespace restriction on the user talk namespace,
1981 * but do not contain a page restriction on the user's talk page.
1982 * For all other (i.e. most) partial blocks, the flag is ignored,
1983 * and the user can always edit their user talk page unless there
1984 * is a page restriction on their user talk page, in which case
1985 * they can never edit it. (Ideally the flag would be stored as
1986 * null in these cases, but the database field isn't nullable.)
1988 * This method does not validate that the passed in talk page belongs to the
1989 * block target since the target (an IP) might not be the same as the user's
1990 * talk page (if they are logged in).
1993 * @param Title|null $usertalk The user's user talk page. If null,
1994 * and if the target is a User, the target's userpage is used
1995 * @return bool The user can edit their talk page
1997 public function appliesToUsertalk( Title
$usertalk = null ) {
1999 if ( $this->target
instanceof User
) {
2000 $usertalk = $this->target
->getTalkPage();
2002 throw new InvalidArgumentException(
2003 '$usertalk must be provided if block target is not a user/IP'
2008 if ( $usertalk->getNamespace() !== NS_USER_TALK
) {
2009 throw new InvalidArgumentException(
2010 '$usertalk must be a user talk page'
2014 if ( !$this->isSitewide() ) {
2015 if ( $this->appliesToPage( $usertalk->getArticleID() ) ) {
2018 if ( !$this->appliesToNamespace( NS_USER_TALK
) ) {
2023 // This is a type of block which uses the ipb_allow_usertalk
2024 // flag. The flag can still be overridden by global configs.
2025 $config = RequestContext
::getMain()->getConfig();
2026 if ( !$config->get( 'BlockAllowsUTEdit' ) ) {
2029 return !$this->isUsertalkEditAllowed();
2033 * Checks if a block applies to a particular title
2035 * This check does not consider whether `$this->isUsertalkEditAllowed`
2036 * returns false, as the identity of the user making the hypothetical edit
2037 * isn't known here (particularly in the case of IP hardblocks, range
2038 * blocks, and auto-blocks).
2040 * @param Title $title
2043 public function appliesToTitle( Title
$title ) {
2044 if ( $this->isSitewide() ) {
2048 $restrictions = $this->getRestrictions();
2049 foreach ( $restrictions as $restriction ) {
2050 if ( $restriction->matches( $title ) ) {
2059 * Checks if a block applies to a particular namespace
2066 public function appliesToNamespace( $ns ) {
2067 if ( $this->isSitewide() ) {
2071 // Blocks do not apply to virtual namespaces.
2076 $restriction = $this->findRestriction( NamespaceRestriction
::TYPE
, $ns );
2078 return (bool)$restriction;
2082 * Checks if a block applies to a particular page
2084 * This check does not consider whether `$this->isUsertalkEditAllowed`
2085 * returns false, as the identity of the user making the hypothetical edit
2086 * isn't known here (particularly in the case of IP hardblocks, range
2087 * blocks, and auto-blocks).
2091 * @param int $pageId
2094 public function appliesToPage( $pageId ) {
2095 if ( $this->isSitewide() ) {
2099 // If the pageId is not over zero, the block cannot apply to it.
2100 if ( $pageId <= 0 ) {
2104 $restriction = $this->findRestriction( PageRestriction
::TYPE
, $pageId );
2106 return (bool)$restriction;
2110 * Find Restriction by type and value.
2112 * @param string $type
2114 * @return Restriction|null
2116 private function findRestriction( $type, $value ) {
2117 $restrictions = $this->getRestrictions();
2118 foreach ( $restrictions as $restriction ) {
2119 if ( $restriction->getType() !== $type ) {
2123 if ( $restriction->getValue() === $value ) {
2124 return $restriction;
2132 * Check if the block should be tracked with a cookie.
2135 * @param bool $isAnon The user is logged out
2136 * @return bool The block should be tracked with a cookie
2138 public function shouldTrackWithCookie( $isAnon ) {
2139 $config = RequestContext
::getMain()->getConfig();
2140 switch ( $this->getType() ) {
2142 case self
::TYPE_RANGE
:
2143 return $isAnon && $config->get( 'CookieSetOnIpBlock' );
2144 case self
::TYPE_USER
:
2145 return !$isAnon && $config->get( 'CookieSetOnAutoblock' ) && $this->isAutoblocking();
2152 * Check if the block prevents a user from resetting their password
2155 * @return bool The block blocks password reset
2157 public function appliesToPasswordReset() {
2158 switch ( $this->getSystemBlockType() ) {
2160 case 'global-block':
2161 return $this->isCreateAccountBlocked();
2165 case 'wgSoftBlockRanges':
2173 * Get a BlockRestrictionStore instance
2175 * @return BlockRestrictionStore
2177 private function getBlockRestrictionStore() : BlockRestrictionStore
{
2178 return MediaWikiServices
::getInstance()->getBlockRestrictionStore();