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 $allowUsertalk;
63 private $blockCreateAccount;
65 /** @var User|string */
68 /** @var int Hack for foreign blocking (CentralAuth) */
69 private $forcedTargetID;
72 * @var int Block::TYPE_ constant. After the block has been loaded
73 * from the database, this can only be USER, IP or RANGE.
84 private $isAutoblocking;
86 /** @var string|null */
87 private $systemBlockType;
92 /** @var Restriction[] */
93 private $restrictions;
103 * Create a new block with specified parameters on a user, IP or IP range.
105 * @param array $options Parameters of the block:
106 * address string|User Target user name, User object, IP address or IP range
107 * user int Override target user ID (for foreign users)
108 * by int User ID of the blocker
109 * reason string Reason of the block
110 * timestamp string The time at which the block comes into effect
111 * auto bool Is this an automatic block?
112 * expiry string Timestamp of expiration of the block or 'infinity'
113 * anonOnly bool Only disallow anonymous actions
114 * createAccount bool Disallow creation of new accounts
115 * enableAutoblock bool Enable automatic blocking
116 * hideName bool Hide the target user name
117 * blockEmail bool Disallow sending emails
118 * allowUsertalk bool Allow the target to edit its own talk page
119 * byText string Username of the blocker (for foreign users)
120 * systemBlock string Indicate that this block is automatically
121 * created by MediaWiki rather than being stored
122 * in the database. Value is a string to return
123 * from self::getSystemBlockType().
124 * sitewide bool Disallow editing all pages and all contribution
125 * actions, except those specifically allowed by
128 * @since 1.26 accepts $options array instead of individual parameters; order
129 * of parameters above reflects the original order
131 function __construct( $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 && BlockRestriction
::equals( $this->getRestrictions(), $block->getRestrictions() )
313 * Load a block from the database which affects the already-set $this->target:
314 * 1) A block directly on the given user or IP
315 * 2) A rangeblock encompassing the given IP (smallest first)
316 * 3) An autoblock on the given IP
317 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
318 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
319 * @throws MWException
320 * @return bool Whether a relevant block was found
322 protected function newLoad( $vagueTarget = null ) {
323 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_REPLICA
);
325 if ( $this->type
!== null ) {
327 'ipb_address' => [ (string)$this->target
],
330 $conds = [ 'ipb_address' => [] ];
333 # Be aware that the != '' check is explicit, since empty values will be
334 # passed by some callers (T31116)
335 if ( $vagueTarget != '' ) {
336 list( $target, $type ) = self
::parseTarget( $vagueTarget );
338 case self
::TYPE_USER
:
339 # Slightly weird, but who are we to argue?
340 $conds['ipb_address'][] = (string)$target;
344 $conds['ipb_address'][] = (string)$target;
345 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
346 $conds = $db->makeList( $conds, LIST_OR
);
349 case self
::TYPE_RANGE
:
350 list( $start, $end ) = IP
::parseRange( $target );
351 $conds['ipb_address'][] = (string)$target;
352 $conds[] = self
::getRangeCond( $start, $end );
353 $conds = $db->makeList( $conds, LIST_OR
);
357 throw new MWException( "Tried to load block with invalid type" );
361 $blockQuery = self
::getQueryInfo();
363 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
366 # This result could contain a block on the user, a block on the IP, and a russian-doll
367 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
370 # Lower will be better
371 $bestBlockScore = 100;
373 foreach ( $res as $row ) {
374 $block = self
::newFromRow( $row );
376 # Don't use expired blocks
377 if ( $block->isExpired() ) {
381 # Don't use anon only blocks on users
382 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
386 if ( $block->getType() == self
::TYPE_RANGE
) {
387 # This is the number of bits that are allowed to vary in the block, give
388 # or take some floating point errors
389 $end = Wikimedia\base_convert
( $block->getRangeEnd(), 16, 10 );
390 $start = Wikimedia\base_convert
( $block->getRangeStart(), 16, 10 );
391 $size = log( $end - $start +
1, 2 );
393 # This has the nice property that a /32 block is ranked equally with a
394 # single-IP block, which is exactly what it is...
395 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
398 $score = $block->getType();
401 if ( $score < $bestBlockScore ) {
402 $bestBlockScore = $score;
407 if ( $bestRow !== null ) {
408 $this->initFromRow( $bestRow );
416 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
417 * @param string $start Hexadecimal IP representation
418 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
421 public static function getRangeCond( $start, $end = null ) {
422 if ( $end === null ) {
425 # Per T16634, we want to include relevant active rangeblocks; for
426 # rangeblocks, we want to include larger ranges which enclose the given
427 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
428 # so we can improve performance by filtering on a LIKE clause
429 $chunk = self
::getIpFragment( $start );
430 $dbr = wfGetDB( DB_REPLICA
);
431 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
433 # Fairly hard to make a malicious SQL statement out of hex characters,
434 # but stranger things have happened...
435 $safeStart = $dbr->addQuotes( $start );
436 $safeEnd = $dbr->addQuotes( $end );
438 return $dbr->makeList(
440 "ipb_range_start $like",
441 "ipb_range_start <= $safeStart",
442 "ipb_range_end >= $safeEnd",
449 * Get the component of an IP address which is certain to be the same between an IP
450 * address and a rangeblock containing that IP address.
451 * @param string $hex Hexadecimal IP representation
454 protected static function getIpFragment( $hex ) {
455 global $wgBlockCIDRLimit;
456 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
457 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
459 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
464 * Given a database row from the ipblocks table, initialize
466 * @param stdClass $row A row from the ipblocks table
468 protected function initFromRow( $row ) {
469 $this->setTarget( $row->ipb_address
);
470 $this->setBlocker( User
::newFromAnyId(
471 $row->ipb_by
, $row->ipb_by_text
, $row->ipb_by_actor ??
null
474 $this->setTimestamp( wfTimestamp( TS_MW
, $row->ipb_timestamp
) );
475 $this->mAuto
= $row->ipb_auto
;
476 $this->setHideName( $row->ipb_deleted
);
477 $this->mId
= (int)$row->ipb_id
;
478 $this->mParentBlockId
= $row->ipb_parent_block_id
;
480 // I wish I didn't have to do this
481 $db = wfGetDB( DB_REPLICA
);
482 $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry
) );
484 CommentStore
::getStore()
485 // Legacy because $row may have come from self::selectFields()
486 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
489 $this->isHardblock( !$row->ipb_anon_only
);
490 $this->isAutoblocking( $row->ipb_enable_autoblock
);
491 $this->isSitewide( (bool)$row->ipb_sitewide
);
493 $this->isCreateAccountBlocked( $row->ipb_create_account
);
494 $this->isEmailBlocked( $row->ipb_block_email
);
495 $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk
);
499 * Create a new Block object from a database row
500 * @param stdClass $row Row from the ipblocks table
503 public static function newFromRow( $row ) {
505 $block->initFromRow( $row );
510 * Delete the row from the IP blocks table.
512 * @throws MWException
515 public function delete() {
516 if ( wfReadOnly() ) {
520 if ( !$this->getId() ) {
521 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
524 $dbw = wfGetDB( DB_MASTER
);
526 BlockRestriction
::deleteByParentBlockId( $this->getId() );
527 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
529 BlockRestriction
::deleteByBlockId( $this->getId() );
530 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
532 return $dbw->affectedRows() > 0;
536 * Insert a block into the block table. Will fail if there is a conflicting
537 * block (same name and options) already in the database.
539 * @param IDatabase|null $dbw If you have one available
540 * @return bool|array False on failure, assoc array on success:
541 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
543 public function insert( $dbw = null ) {
544 global $wgBlockDisablesLogin;
546 if ( $this->getSystemBlockType() !== null ) {
547 throw new MWException( 'Cannot insert a system block into the database' );
549 if ( !$this->getBlocker() ||
$this->getBlocker()->getName() === '' ) {
550 throw new MWException( 'Cannot insert a block without a blocker set' );
553 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
555 if ( $dbw === null ) {
556 $dbw = wfGetDB( DB_MASTER
);
559 self
::purgeExpired();
561 $row = $this->getDatabaseArray( $dbw );
563 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
564 $affected = $dbw->affectedRows();
566 $this->setId( $dbw->insertId() );
567 if ( $this->restrictions
) {
568 BlockRestriction
::insert( $this->restrictions
);
572 # Don't collide with expired blocks.
573 # Do this after trying to insert to avoid locking.
575 # T96428: The ipb_address index uses a prefix on a field, so
576 # use a standard SELECT + DELETE to avoid annoying gap locks.
577 $ids = $dbw->selectFieldValues( 'ipblocks',
580 'ipb_address' => $row['ipb_address'],
581 'ipb_user' => $row['ipb_user'],
582 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
587 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
588 BlockRestriction
::deleteByBlockId( $ids );
589 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
590 $affected = $dbw->affectedRows();
591 $this->setId( $dbw->insertId() );
592 if ( $this->restrictions
) {
593 BlockRestriction
::insert( $this->restrictions
);
599 $auto_ipd_ids = $this->doRetroactiveAutoblock();
601 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
602 // Change user login token to force them to be logged out.
603 $this->target
->setToken();
604 $this->target
->saveSettings();
607 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
614 * Update a block in the DB with new parameters.
615 * The ID field needs to be loaded first.
617 * @return bool|array False on failure, array on success:
618 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
620 public function update() {
621 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
622 $dbw = wfGetDB( DB_MASTER
);
624 $dbw->startAtomic( __METHOD__
);
626 $result = $dbw->update(
628 $this->getDatabaseArray( $dbw ),
629 [ 'ipb_id' => $this->getId() ],
633 // Only update the restrictions if they have been modified.
634 if ( $this->restrictions
!== null ) {
635 // An empty array should remove all of the restrictions.
636 if ( empty( $this->restrictions
) ) {
637 $success = BlockRestriction
::deleteByBlockId( $this->getId() );
639 $success = BlockRestriction
::update( $this->restrictions
);
641 // Update the result. The first false is the result, otherwise, true.
642 $result = $result && $success;
645 if ( $this->isAutoblocking() ) {
646 // update corresponding autoblock(s) (T50813)
649 $this->getAutoblockUpdateArray( $dbw ),
650 [ 'ipb_parent_block_id' => $this->getId() ],
654 // Only update the restrictions if they have been modified.
655 if ( $this->restrictions
!== null ) {
656 BlockRestriction
::updateByParentBlockId( $this->getId(), $this->restrictions
);
659 // autoblock no longer required, delete corresponding autoblock(s)
660 BlockRestriction
::deleteByParentBlockId( $this->getId() );
663 [ 'ipb_parent_block_id' => $this->getId() ],
668 $dbw->endAtomic( __METHOD__
);
671 $auto_ipd_ids = $this->doRetroactiveAutoblock();
672 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
679 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
680 * @param IDatabase $dbw
683 protected function getDatabaseArray( IDatabase
$dbw ) {
684 $expiry = $dbw->encodeExpiry( $this->getExpiry() );
686 if ( $this->forcedTargetID
) {
687 $uid = $this->forcedTargetID
;
689 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
693 'ipb_address' => (string)$this->target
,
695 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
696 'ipb_auto' => $this->mAuto
,
697 'ipb_anon_only' => !$this->isHardblock(),
698 'ipb_create_account' => $this->isCreateAccountBlocked(),
699 'ipb_enable_autoblock' => $this->isAutoblocking(),
700 'ipb_expiry' => $expiry,
701 'ipb_range_start' => $this->getRangeStart(),
702 'ipb_range_end' => $this->getRangeEnd(),
703 'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
704 'ipb_block_email' => $this->isEmailBlocked(),
705 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
706 'ipb_parent_block_id' => $this->mParentBlockId
,
707 'ipb_sitewide' => $this->isSitewide(),
708 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
709 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
715 * @param IDatabase $dbw
718 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
720 'ipb_create_account' => $this->isCreateAccountBlocked(),
721 'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
722 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
723 'ipb_sitewide' => $this->isSitewide(),
724 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
725 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
729 * Retroactively autoblocks the last IP used by the user (if it is a user)
730 * blocked by this Block.
732 * @return array Block IDs of retroactive autoblocks made
734 protected function doRetroactiveAutoblock() {
736 # If autoblock is enabled, autoblock the LAST IP(s) used
737 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
738 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
740 $continue = Hooks
::run(
741 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
744 self
::defaultRetroactiveAutoblock( $this, $blockIds );
751 * Retroactively autoblocks the last IP used by the user (if it is a user)
752 * blocked by this Block. This will use the recentchanges table.
754 * @param Block $block
755 * @param array &$blockIds
757 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
760 // No IPs are in recentchanges table, so nothing to select
761 if ( !$wgPutIPinRC ) {
765 // Autoblocks only apply to TYPE_USER
766 if ( $block->getType() !== self
::TYPE_USER
) {
769 $target = $block->getTarget(); // TYPE_USER => always a User object
771 $dbr = wfGetDB( DB_REPLICA
);
772 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
774 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
776 // Just the last IP used.
777 $options['LIMIT'] = 1;
780 [ 'recentchanges' ] +
$rcQuery['tables'],
788 if ( !$res->numRows() ) {
789 # No results, don't autoblock anything
790 wfDebug( "No IP found to retroactively autoblock\n" );
792 foreach ( $res as $row ) {
794 $id = $block->doAutoblock( $row->rc_ip
);
804 * Checks whether a given IP is on the autoblock whitelist.
805 * TODO: this probably belongs somewhere else, but not sure where...
807 * @param string $ip The IP to check
810 public static function isWhitelistedFromAutoblocks( $ip ) {
811 // Try to get the autoblock_whitelist from the cache, as it's faster
812 // than getting the msg raw and explode()'ing it.
813 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
814 $lines = $cache->getWithSetCallback(
815 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
817 function ( $curValue, &$ttl, array &$setOpts ) {
818 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
820 return explode( "\n",
821 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
825 wfDebug( "Checking the autoblock whitelist..\n" );
827 foreach ( $lines as $line ) {
829 if ( substr( $line, 0, 1 ) !== '*' ) {
833 $wlEntry = substr( $line, 1 );
834 $wlEntry = trim( $wlEntry );
836 wfDebug( "Checking $ip against $wlEntry..." );
838 # Is the IP in this range?
839 if ( IP
::isInRange( $ip, $wlEntry ) ) {
840 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
843 wfDebug( " No match\n" );
851 * Autoblocks the given IP, referring to this Block.
853 * @param string $autoblockIP The IP to autoblock.
854 * @return int|bool Block ID if an autoblock was inserted, false if not.
856 public function doAutoblock( $autoblockIP ) {
857 # If autoblocks are disabled, go away.
858 if ( !$this->isAutoblocking() ) {
862 # Don't autoblock for system blocks
863 if ( $this->getSystemBlockType() !== null ) {
864 throw new MWException( 'Cannot autoblock from a system block' );
867 # Check for presence on the autoblock whitelist.
868 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
872 // Avoid PHP 7.1 warning of passing $this by reference
874 # Allow hooks to cancel the autoblock.
875 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
876 wfDebug( "Autoblock aborted by hook.\n" );
880 # It's okay to autoblock. Go ahead and insert/update the block...
882 # Do not add a *new* block if the IP is already blocked.
883 $ipblock = self
::newFromTarget( $autoblockIP );
885 # Check if the block is an autoblock and would exceed the user block
886 # if renewed. If so, do nothing, otherwise prolong the block time...
887 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
888 $this->getExpiry() > self
::getAutoblockExpiry( $ipblock->getTimestamp() )
890 # Reset block timestamp to now and its expiry to
891 # $wgAutoblockExpiry in the future
892 $ipblock->updateTimestamp();
897 # Make a new block object with the desired properties.
898 $autoblock = new Block
;
899 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
900 $autoblock->setTarget( $autoblockIP );
901 $autoblock->setBlocker( $this->getBlocker() );
902 $autoblock->setReason(
903 wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
904 ->inContentLanguage()->plain()
906 $timestamp = wfTimestampNow();
907 $autoblock->setTimestamp( $timestamp );
908 $autoblock->mAuto
= 1;
909 $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
910 # Continue suppressing the name if needed
911 $autoblock->setHideName( $this->getHideName() );
912 $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
913 $autoblock->mParentBlockId
= $this->mId
;
914 $autoblock->isSitewide( $this->isSitewide() );
915 $autoblock->setRestrictions( $this->getRestrictions() );
917 if ( $this->getExpiry() == 'infinity' ) {
918 # Original block was indefinite, start an autoblock now
919 $autoblock->setExpiry( self
::getAutoblockExpiry( $timestamp ) );
921 # If the user is already blocked with an expiry date, we don't
922 # want to pile on top of that.
923 $autoblock->setExpiry( min( $this->getExpiry(), self
::getAutoblockExpiry( $timestamp ) ) );
926 # Insert the block...
927 $status = $autoblock->insert();
934 * Check if a block has expired. Delete it if it is.
937 public function deleteIfExpired() {
938 if ( $this->isExpired() ) {
939 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
943 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
951 * Has the block expired?
954 public function isExpired() {
955 $timestamp = wfTimestampNow();
956 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
958 if ( !$this->getExpiry() ) {
961 return $timestamp > $this->getExpiry();
966 * Is the block address valid (i.e. not a null string?)
968 * @deprecated since 1.33 No longer needed in core.
971 public function isValid() {
972 wfDeprecated( __METHOD__
, '1.33' );
973 return $this->getTarget() != null;
977 * Update the timestamp on autoblocks.
979 public function updateTimestamp() {
980 if ( $this->mAuto
) {
981 $this->setTimestamp( wfTimestamp() );
982 $this->setExpiry( self
::getAutoblockExpiry( $this->getTimestamp() ) );
984 $dbw = wfGetDB( DB_MASTER
);
985 $dbw->update( 'ipblocks',
987 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
988 'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
991 'ipb_id' => $this->getId(),
999 * Get the IP address at the start of the range in Hex form
1000 * @throws MWException
1001 * @return string IP in Hex form
1003 public function getRangeStart() {
1004 switch ( $this->type
) {
1005 case self
::TYPE_USER
:
1008 return IP
::toHex( $this->target
);
1009 case self
::TYPE_RANGE
:
1010 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
1013 throw new MWException( "Block with invalid type" );
1018 * Get the IP address at the end of the range in Hex form
1019 * @throws MWException
1020 * @return string IP in Hex form
1022 public function getRangeEnd() {
1023 switch ( $this->type
) {
1024 case self
::TYPE_USER
:
1027 return IP
::toHex( $this->target
);
1028 case self
::TYPE_RANGE
:
1029 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
1032 throw new MWException( "Block with invalid type" );
1037 * Get the user id of the blocking sysop
1039 * @return int (0 for foreign users)
1041 public function getBy() {
1042 return $this->getBlocker()->getId();
1046 * Get the username of the blocking sysop
1050 public function getByName() {
1051 return $this->getBlocker()->getName();
1058 public function getId() {
1065 * @param int $blockId
1068 private function setId( $blockId ) {
1069 $this->mId
= (int)$blockId;
1071 if ( is_array( $this->restrictions
) ) {
1072 $this->restrictions
= BlockRestriction
::setBlockId( $blockId, $this->restrictions
);
1079 * Get the reason given for creating the block
1084 public function getReason() {
1085 return $this->mReason
;
1089 * Set the reason for creating the block
1092 * @param string $reason
1094 public function setReason( $reason ) {
1095 $this->mReason
= $reason;
1099 * Get whether the block hides the target's username
1102 * @return bool The block hides the username
1104 public function getHideName() {
1105 return $this->mHideName
;
1109 * Set whether ths block hides the target's username
1112 * @param bool $hideName The block hides the username
1114 public function setHideName( $hideName ) {
1115 $this->mHideName
= $hideName;
1119 * Get the system block type, if any
1121 * @return string|null
1123 public function getSystemBlockType() {
1124 return $this->systemBlockType
;
1128 * Get/set a flag determining whether the master is used for reads
1130 * @param bool|null $x
1133 public function fromMaster( $x = null ) {
1134 return wfSetVar( $this->mFromMaster
, $x );
1138 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1139 * @param bool|null $x
1142 public function isHardblock( $x = null ) {
1143 wfSetVar( $this->isHardblock
, $x );
1145 # You can't *not* hardblock a user
1146 return $this->getType() == self
::TYPE_USER
1148 : $this->isHardblock
;
1152 * @param null|bool $x
1155 public function isAutoblocking( $x = null ) {
1156 wfSetVar( $this->isAutoblocking
, $x );
1158 # You can't put an autoblock on an IP or range as we don't have any history to
1159 # look over to get more IPs from
1160 return $this->getType() == self
::TYPE_USER
1161 ?
$this->isAutoblocking
1166 * Indicates that the block is a sitewide block. This means the user is
1167 * prohibited from editing any page on the site (other than their own talk
1171 * @param null|bool $x
1174 public function isSitewide( $x = null ) {
1175 return wfSetVar( $this->isSitewide
, $x );
1179 * Get or set the flag indicating whether this block blocks the target from
1180 * creating an account. (Note that the flag may be overridden depending on
1184 * @param null|bool $x Value to set (if null, just get the property value)
1185 * @return bool Value of the property
1187 public function isCreateAccountBlocked( $x = null ) {
1188 return wfSetVar( $this->blockCreateAccount
, $x );
1192 * Get or set the flag indicating whether this block blocks the target from
1193 * sending emails. (Note that the flag may be overridden depending on
1197 * @param null|bool $x Value to set (if null, just get the property value)
1198 * @return bool Value of the property
1200 public function isEmailBlocked( $x = null ) {
1201 return wfSetVar( $this->mBlockEmail
, $x );
1205 * Get or set the flag indicating whether this block blocks the target from
1206 * editing their own user talk page. (Note that the flag may be overridden
1207 * depending on global configs.)
1210 * @param null|bool $x Value to set (if null, just get the property value)
1211 * @return bool Value of the property
1213 public function isUsertalkEditAllowed( $x = null ) {
1214 return wfSetVar( $this->allowUsertalk
, $x );
1218 * Determine whether the Block prevents a given right. A right
1219 * may be blacklisted or whitelisted, or determined from a
1220 * property on the Block object. For certain rights, the property
1221 * may be overridden according to global configs.
1224 * @param string $right Right to check
1225 * @return bool|null null if unrecognized right or unset property
1227 public function appliesToRight( $right ) {
1228 $config = RequestContext
::getMain()->getConfig();
1229 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1234 // TODO: fix this case to return proper value
1237 case 'createaccount':
1238 $res = $this->isCreateAccountBlocked();
1241 $res = $this->isEmailBlocked();
1244 // Until T6995 is completed
1245 $res = $this->isSitewide();
1254 if ( !$res && $blockDisablesLogin ) {
1255 // If a block would disable login, then it should
1256 // prevent any right that all users cannot do
1258 $res = $anon->isAllowed( $right ) ?
$res : true;
1265 * Get/set whether the Block prevents a given action
1267 * @deprecated since 1.33, use appliesToRight to determine block
1268 * behaviour, and specific methods to get/set properties
1269 * @param string $action Action to check
1270 * @param bool|null $x Value for set, or null to just get value
1271 * @return bool|null Null for unrecognized rights.
1273 public function prevents( $action, $x = null ) {
1274 $config = RequestContext
::getMain()->getConfig();
1275 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1276 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1279 switch ( $action ) {
1281 # For now... <evil laugh>
1284 case 'createaccount':
1285 $res = wfSetVar( $this->blockCreateAccount
, $x );
1288 $res = wfSetVar( $this->mBlockEmail
, $x );
1291 // Until T6995 is completed
1292 $res = $this->isSitewide();
1294 case 'editownusertalk':
1295 // NOTE: this check is not reliable on partial blocks
1296 // since partially blocked users are always allowed to edit
1297 // their own talk page unless a restriction exists on the
1298 // page or User_talk: namespace
1299 wfSetVar( $this->allowUsertalk
, $x === null ?
null : !$x );
1300 $res = !$this->isUserTalkEditAllowed();
1302 // edit own user talk can be disabled by config
1303 if ( !$blockAllowsUTEdit ) {
1314 if ( !$res && $blockDisablesLogin ) {
1315 // If a block would disable login, then it should
1316 // prevent any action that all users cannot do
1318 $res = $anon->isAllowed( $action ) ?
$res : true;
1325 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1326 * @return string Text is escaped
1328 public function getRedactedName() {
1329 if ( $this->mAuto
) {
1330 return Html
::element(
1332 [ 'class' => 'mw-autoblockid' ],
1333 wfMessage( 'autoblockid', $this->mId
)->text()
1336 return htmlspecialchars( $this->getTarget() );
1341 * Get a timestamp of the expiry for autoblocks
1343 * @param string|int $timestamp
1346 public static function getAutoblockExpiry( $timestamp ) {
1347 global $wgAutoblockExpiry;
1349 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1353 * Purge expired blocks from the ipblocks table
1355 public static function purgeExpired() {
1356 if ( wfReadOnly() ) {
1360 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1361 wfGetDB( DB_MASTER
),
1363 function ( IDatabase
$dbw, $fname ) {
1364 $ids = $dbw->selectFieldValues( 'ipblocks',
1366 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1370 BlockRestriction
::deleteByBlockId( $ids );
1371 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1378 * Given a target and the target's type, get an existing Block object if possible.
1379 * @param string|User|int $specificTarget A block target, which may be one of several types:
1380 * * A user to block, in which case $target will be a User
1381 * * An IP to block, in which case $target will be a User generated by using
1382 * User::newFromName( $ip, false ) to turn off name validation
1383 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1384 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1386 * Calling this with a user, IP address or range will not select autoblocks, and will
1387 * only select a block where the targets match exactly (so looking for blocks on
1388 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1389 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1390 * affects that target (so for an IP address, get ranges containing that IP; and also
1391 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1392 * @param bool $fromMaster Whether to use the DB_MASTER database
1393 * @return Block|null (null if no relevant block could be found). The target and type
1394 * of the returned Block will refer to the actual block which was found, which might
1395 * not be the same as the target you gave if you used $vagueTarget!
1397 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1398 list( $target, $type ) = self
::parseTarget( $specificTarget );
1399 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1400 return self
::newFromID( $target );
1402 } elseif ( $target === null && $vagueTarget == '' ) {
1403 # We're not going to find anything useful here
1404 # Be aware that the == '' check is explicit, since empty values will be
1405 # passed by some callers (T31116)
1408 } elseif ( in_array(
1410 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1412 $block = new Block();
1413 $block->fromMaster( $fromMaster );
1415 if ( $type !== null ) {
1416 $block->setTarget( $target );
1419 if ( $block->newLoad( $vagueTarget ) ) {
1427 * Get all blocks that match any IP from an array of IP addresses
1429 * @param array $ipChain List of IPs (strings), usually retrieved from the
1430 * X-Forwarded-For header of the request
1431 * @param bool $isAnon Exclude anonymous-only blocks if false
1432 * @param bool $fromMaster Whether to query the master or replica DB
1433 * @return array Array of Blocks
1436 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1437 if ( $ipChain === [] ) {
1442 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1443 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1444 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1445 # necessarily trust the header given to us, make sure that we are only
1446 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1447 # Do not treat private IP spaces as special as it may be desirable for wikis
1448 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1449 if ( !IP
::isValid( $ipaddr ) ) {
1452 # Don't check trusted IPs (includes local squids which will be in every request)
1453 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1456 # Check both the original IP (to check against single blocks), as well as build
1457 # the clause to check for rangeblocks for the given IP.
1458 $conds['ipb_address'][] = $ipaddr;
1459 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1462 if ( $conds === [] ) {
1466 if ( $fromMaster ) {
1467 $db = wfGetDB( DB_MASTER
);
1469 $db = wfGetDB( DB_REPLICA
);
1471 $conds = $db->makeList( $conds, LIST_OR
);
1473 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1475 $blockQuery = self
::getQueryInfo();
1476 $rows = $db->select(
1477 $blockQuery['tables'],
1478 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1482 $blockQuery['joins']
1486 foreach ( $rows as $row ) {
1487 $block = self
::newFromRow( $row );
1488 if ( !$block->isExpired() ) {
1497 * From a list of multiple blocks, find the most exact and strongest Block.
1499 * The logic for finding the "best" block is:
1500 * - Blocks that match the block's target IP are preferred over ones in a range
1501 * - Hardblocks are chosen over softblocks that prevent account creation
1502 * - Softblocks that prevent account creation are chosen over other softblocks
1503 * - Other softblocks are chosen over autoblocks
1504 * - If there are multiple exact or range blocks at the same level, the one chosen
1506 * This should be used when $blocks where retrieved from the user's IP address
1507 * and $ipChain is populated from the same IP address information.
1509 * @param array $blocks Array of Block objects
1510 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1511 * a block is to the server, and if a block matches exactly, or is in a range.
1512 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1514 * @throws MWException
1515 * @return Block|null The "best" block from the list
1517 public static function chooseBlock( array $blocks, array $ipChain ) {
1518 if ( $blocks === [] ) {
1520 } elseif ( count( $blocks ) == 1 ) {
1524 // Sort hard blocks before soft ones and secondarily sort blocks
1525 // that disable account creation before those that don't.
1526 usort( $blocks, function ( Block
$a, Block
$b ) {
1527 $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1528 $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1529 return strcmp( $bWeight, $aWeight ); // highest weight first
1532 $blocksListExact = [
1534 'disable_create' => false,
1538 $blocksListRange = [
1540 'disable_create' => false,
1544 $ipChain = array_reverse( $ipChain );
1546 /** @var Block $block */
1547 foreach ( $blocks as $block ) {
1548 // Stop searching if we have already have a "better" block. This
1549 // is why the order of the blocks matters
1550 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1552 } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1556 foreach ( $ipChain as $checkip ) {
1557 $checkipHex = IP
::toHex( $checkip );
1558 if ( (string)$block->getTarget() === $checkip ) {
1559 if ( $block->isHardblock() ) {
1560 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1561 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1562 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1563 } elseif ( $block->mAuto
) {
1564 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1566 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1568 // We found closest exact match in the ip list, so go to the next Block
1570 } elseif ( array_filter( $blocksListExact ) == []
1571 && $block->getRangeStart() <= $checkipHex
1572 && $block->getRangeEnd() >= $checkipHex
1574 if ( $block->isHardblock() ) {
1575 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1576 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1577 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1578 } elseif ( $block->mAuto
) {
1579 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1581 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1588 if ( array_filter( $blocksListExact ) == [] ) {
1589 $blocksList = &$blocksListRange;
1591 $blocksList = &$blocksListExact;
1594 $chosenBlock = null;
1595 if ( $blocksList['hard'] ) {
1596 $chosenBlock = $blocksList['hard'];
1597 } elseif ( $blocksList['disable_create'] ) {
1598 $chosenBlock = $blocksList['disable_create'];
1599 } elseif ( $blocksList['other'] ) {
1600 $chosenBlock = $blocksList['other'];
1601 } elseif ( $blocksList['auto'] ) {
1602 $chosenBlock = $blocksList['auto'];
1604 throw new MWException( "Proxy block found, but couldn't be classified." );
1607 return $chosenBlock;
1611 * From an existing Block, get the target and the type of target.
1612 * Note that, except for null, it is always safe to treat the target
1613 * as a string; for User objects this will return User::__toString()
1614 * which in turn gives User::getName().
1616 * @param string|int|User|null $target
1617 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1619 public static function parseTarget( $target ) {
1620 # We may have been through this before
1621 if ( $target instanceof User
) {
1622 if ( IP
::isValid( $target->getName() ) ) {
1623 return [ $target, self
::TYPE_IP
];
1625 return [ $target, self
::TYPE_USER
];
1627 } elseif ( $target === null ) {
1628 return [ null, null ];
1631 $target = trim( $target );
1633 if ( IP
::isValid( $target ) ) {
1634 # We can still create a User if it's an IP address, but we need to turn
1635 # off validation checking (which would exclude IP addresses)
1637 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1641 } elseif ( IP
::isValidRange( $target ) ) {
1642 # Can't create a User from an IP range
1643 return [ IP
::sanitizeRange( $target ), self
::TYPE_RANGE
];
1646 # Consider the possibility that this is not a username at all
1647 # but actually an old subpage (T31797)
1648 if ( strpos( $target, '/' ) !== false ) {
1649 # An old subpage, drill down to the user behind it
1650 $target = explode( '/', $target )[0];
1653 $userObj = User
::newFromName( $target );
1654 if ( $userObj instanceof User
) {
1655 # Note that since numbers are valid usernames, a $target of "12345" will be
1656 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1657 # since hash characters are not valid in usernames or titles generally.
1658 return [ $userObj, self
::TYPE_USER
];
1660 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1661 # Autoblock reference in the form "#12345"
1662 return [ substr( $target, 1 ), self
::TYPE_AUTO
];
1666 return [ null, null ];
1671 * Get the type of target for this particular block. Autoblocks have whichever type
1672 * corresponds to their target, so to detect if a block is an autoblock, we have to
1673 * check the mAuto property instead.
1674 * @return int Block::TYPE_ constant, will never be TYPE_ID
1676 public function getType() {
1683 * Get the target and target type for this particular Block. Note that for autoblocks,
1684 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1685 * in this situation.
1686 * @return array [ User|String, Block::TYPE_ constant ]
1687 * @todo FIXME: This should be an integral part of the Block member variables
1689 public function getTargetAndType() {
1690 return [ $this->getTarget(), $this->getType() ];
1694 * Get the target for this particular Block. Note that for autoblocks,
1695 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1696 * in this situation.
1697 * @return User|string
1699 public function getTarget() {
1700 return $this->target
;
1704 * Get the block expiry time
1709 public function getExpiry() {
1710 return $this->mExpiry
;
1714 * Set the block expiry time
1717 * @param string $expiry
1719 public function setExpiry( $expiry ) {
1720 $this->mExpiry
= $expiry;
1724 * Get the timestamp indicating when the block was created
1729 public function getTimestamp() {
1730 return $this->mTimestamp
;
1734 * Set the timestamp indicating when the block was created
1737 * @param string $timestamp
1739 public function setTimestamp( $timestamp ) {
1740 $this->mTimestamp
= $timestamp;
1744 * Set the target for this block, and update $this->type accordingly
1745 * @param mixed $target
1747 public function setTarget( $target ) {
1748 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1752 * Get the user who implemented this block
1753 * @return User User object. May name a foreign user.
1755 public function getBlocker() {
1756 return $this->blocker
;
1760 * Set the user who implemented (or will implement) this block
1761 * @param User|string $user Local User object or username string
1763 public function setBlocker( $user ) {
1764 if ( is_string( $user ) ) {
1765 $user = User
::newFromName( $user, false );
1768 if ( $user->isAnon() && User
::isUsableName( $user->getName() ) ) {
1769 throw new InvalidArgumentException(
1770 'Blocker must be a local user or a name that cannot be a local user'
1774 $this->blocker
= $user;
1778 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1779 * the same as the block's, to a maximum of 24 hours.
1783 * @param WebResponse $response The response on which to set the cookie.
1785 public function setCookie( WebResponse
$response ) {
1786 // Calculate the default expiry time.
1787 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1789 // Use the Block's expiry time only if it's less than the default.
1790 $expiryTime = $this->getExpiry();
1791 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1792 $expiryTime = $maxExpiryTime;
1795 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1796 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1797 $cookieOptions = [ 'httpOnly' => false ];
1798 $cookieValue = $this->getCookieValue();
1799 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1803 * Unset the 'BlockID' cookie.
1807 * @param WebResponse $response The response on which to unset the cookie.
1809 public static function clearCookie( WebResponse
$response ) {
1810 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1814 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1815 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1820 * @return string The block ID, probably concatenated with "!" and the HMAC.
1822 public function getCookieValue() {
1823 $config = RequestContext
::getMain()->getConfig();
1824 $id = $this->getId();
1825 $secretKey = $config->get( 'SecretKey' );
1826 if ( !$secretKey ) {
1827 // If there's no secret key, don't append a HMAC.
1830 $hmac = MWCryptHash
::hmac( $id, $secretKey, false );
1831 $cookieValue = $id . '!' . $hmac;
1832 return $cookieValue;
1836 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1837 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1841 * @param string $cookieValue The string in which to find the ID.
1843 * @return int|null The block ID, or null if the HMAC is present and invalid.
1845 public static function getIdFromCookieValue( $cookieValue ) {
1846 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1847 $bangPos = strpos( $cookieValue, '!' );
1848 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
1849 // Get the site-wide secret key.
1850 $config = RequestContext
::getMain()->getConfig();
1851 $secretKey = $config->get( 'SecretKey' );
1852 if ( !$secretKey ) {
1853 // If there's no secret key, just use the ID as given.
1856 $storedHmac = substr( $cookieValue, $bangPos +
1 );
1857 $calculatedHmac = MWCryptHash
::hmac( $id, $secretKey, false );
1858 if ( $calculatedHmac === $storedHmac ) {
1866 * Get the key and parameters for the corresponding error message.
1869 * @param IContextSource $context
1872 public function getPermissionsError( IContextSource
$context ) {
1873 $params = $this->getBlockErrorParams( $context );
1875 $msg = 'blockedtext';
1876 if ( $this->getSystemBlockType() !== null ) {
1877 $msg = 'systemblockedtext';
1878 } elseif ( $this->mAuto
) {
1879 $msg = 'autoblockedtext';
1880 } elseif ( !$this->isSitewide() ) {
1881 $msg = 'blockedtext-partial';
1884 array_unshift( $params, $msg );
1890 * Get block information used in different block error messages
1893 * @param IContextSource $context
1896 public function getBlockErrorParams( IContextSource
$context ) {
1897 $blocker = $this->getBlocker();
1898 if ( $blocker instanceof User
) { // local user
1899 $blockerUserpage = $blocker->getUserPage();
1900 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1901 } else { // foreign user
1905 $reason = $this->getReason();
1906 if ( $reason == '' ) {
1907 $reason = $context->msg( 'blockednoreason' )->text();
1910 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1911 * This could be a username, an IP range, or a single IP. */
1912 $intended = $this->getTarget();
1913 $systemBlockType = $this->getSystemBlockType();
1914 $lang = $context->getLanguage();
1919 $context->getRequest()->getIP(),
1921 $systemBlockType ??
$this->getId(),
1922 $lang->formatExpiry( $this->getExpiry() ),
1924 $lang->userTimeAndDate( $this->getTimestamp(), $context->getUser() ),
1931 * Getting the restrictions will perform a database query if the restrictions
1932 * are not already loaded.
1935 * @return Restriction[]
1937 public function getRestrictions() {
1938 if ( $this->restrictions
=== null ) {
1939 // If the block id has not been set, then do not attempt to load the
1941 if ( !$this->mId
) {
1944 $this->restrictions
= BlockRestriction
::loadByBlockId( $this->mId
);
1947 return $this->restrictions
;
1954 * @param Restriction[] $restrictions
1957 public function setRestrictions( array $restrictions ) {
1958 $this->restrictions
= array_filter( $restrictions, function ( $restriction ) {
1959 return $restriction instanceof Restriction
;
1966 * Determine whether the block allows the user to edit their own
1967 * user talk page. This is done separately from Block::appliesToRight
1968 * because there is no right for editing one's own user talk page
1969 * and because the user's talk page needs to be passed into the
1970 * Block object, which is unaware of the user.
1972 * The ipb_allow_usertalk flag (which corresponds to the property
1973 * allowUsertalk) is used on sitewide blocks and partial blocks
1974 * that contain a namespace restriction on the user talk namespace,
1975 * but do not contain a page restriction on the user's talk page.
1976 * For all other (i.e. most) partial blocks, the flag is ignored,
1977 * and the user can always edit their user talk page unless there
1978 * is a page restriction on their user talk page, in which case
1979 * they can never edit it. (Ideally the flag would be stored as
1980 * null in these cases, but the database field isn't nullable.)
1982 * This method does not validate that the passed in talk page belongs to the
1983 * block target since the target (an IP) might not be the same as the user's
1984 * talk page (if they are logged in).
1987 * @param Title|null $usertalk The user's user talk page. If null,
1988 * and if the target is a User, the target's userpage is used
1989 * @return bool The user can edit their talk page
1991 public function appliesToUsertalk( Title
$usertalk = null ) {
1993 if ( $this->target
instanceof User
) {
1994 $usertalk = $this->target
->getTalkPage();
1996 throw new InvalidArgumentException(
1997 '$usertalk must be provided if block target is not a user/IP'
2002 if ( $usertalk->getNamespace() !== NS_USER_TALK
) {
2003 throw new InvalidArgumentException(
2004 '$usertalk must be a user talk page'
2008 if ( !$this->isSitewide() ) {
2009 if ( $this->appliesToPage( $usertalk->getArticleID() ) ) {
2012 if ( !$this->appliesToNamespace( NS_USER_TALK
) ) {
2017 // This is a type of block which uses the ipb_allow_usertalk
2018 // flag. The flag can still be overridden by global configs.
2019 $config = RequestContext
::getMain()->getConfig();
2020 if ( !$config->get( 'BlockAllowsUTEdit' ) ) {
2023 return !$this->isUsertalkEditAllowed();
2027 * Checks if a block applies to a particular title
2029 * This check does not consider whether `$this->isUsertalkEditAllowed`
2030 * returns false, as the identity of the user making the hypothetical edit
2031 * isn't known here (particularly in the case of IP hardblocks, range
2032 * blocks, and auto-blocks).
2034 * @param Title $title
2037 public function appliesToTitle( Title
$title ) {
2038 if ( $this->isSitewide() ) {
2042 $restrictions = $this->getRestrictions();
2043 foreach ( $restrictions as $restriction ) {
2044 if ( $restriction->matches( $title ) ) {
2053 * Checks if a block applies to a particular namespace
2060 public function appliesToNamespace( $ns ) {
2061 if ( $this->isSitewide() ) {
2065 // Blocks do not apply to virtual namespaces.
2070 $restriction = $this->findRestriction( NamespaceRestriction
::TYPE
, $ns );
2072 return (bool)$restriction;
2076 * Checks if a block applies to a particular page
2078 * This check does not consider whether `$this->isUsertalkEditAllowed`
2079 * returns false, as the identity of the user making the hypothetical edit
2080 * isn't known here (particularly in the case of IP hardblocks, range
2081 * blocks, and auto-blocks).
2085 * @param int $pageId
2088 public function appliesToPage( $pageId ) {
2089 if ( $this->isSitewide() ) {
2093 // If the pageId is not over zero, the block cannot apply to it.
2094 if ( $pageId <= 0 ) {
2098 $restriction = $this->findRestriction( PageRestriction
::TYPE
, $pageId );
2100 return (bool)$restriction;
2104 * Find Restriction by type and value.
2106 * @param string $type
2108 * @return Restriction|null
2110 private function findRestriction( $type, $value ) {
2111 $restrictions = $this->getRestrictions();
2112 foreach ( $restrictions as $restriction ) {
2113 if ( $restriction->getType() !== $type ) {
2117 if ( $restriction->getValue() === $value ) {
2118 return $restriction;