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\MediaWikiServices
;
44 public $mParentBlockId;
56 private $mDisableUsertalk;
59 private $mCreateAccount;
61 /** @var User|string */
64 /** @var int Hack for foreign blocking (CentralAuth) */
65 private $forcedTargetID;
67 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
77 private $isAutoblocking;
79 /** @var string|null */
80 private $systemBlockType;
90 * Create a new block with specified parameters on a user, IP or IP range.
92 * @param array $options Parameters of the block:
93 * address string|User Target user name, User object, IP address or IP range
94 * user int Override target user ID (for foreign users)
95 * by int User ID of the blocker
96 * reason string Reason of the block
97 * timestamp string The time at which the block comes into effect
98 * auto bool Is this an automatic block?
99 * expiry string Timestamp of expiration of the block or 'infinity'
100 * anonOnly bool Only disallow anonymous actions
101 * createAccount bool Disallow creation of new accounts
102 * enableAutoblock bool Enable automatic blocking
103 * hideName bool Hide the target user name
104 * blockEmail bool Disallow sending emails
105 * allowUsertalk bool Allow the target to edit its own talk page
106 * byText string Username of the blocker (for foreign users)
107 * systemBlock string Indicate that this block is automatically
108 * created by MediaWiki rather than being stored
109 * in the database. Value is a string to return
110 * from self::getSystemBlockType().
112 * @since 1.26 accepts $options array instead of individual parameters; order
113 * of parameters above reflects the original order
115 function __construct( $options = [] ) {
125 'createAccount' => false,
126 'enableAutoblock' => false,
128 'blockEmail' => false,
129 'allowUsertalk' => false,
131 'systemBlock' => null,
134 if ( func_num_args() > 1 ||
!is_array( $options ) ) {
135 $options = array_combine(
136 array_slice( array_keys( $defaults ), 0, func_num_args() ),
139 wfDeprecated( __METHOD__
. ' with multiple arguments', '1.26' );
142 $options +
= $defaults;
144 $this->setTarget( $options['address'] );
146 if ( $this->target
instanceof User
&& $options['user'] ) {
147 # Needed for foreign users
148 $this->forcedTargetID
= $options['user'];
151 if ( $options['by'] ) {
153 $this->setBlocker( User
::newFromId( $options['by'] ) );
156 $this->setBlocker( $options['byText'] );
159 $this->mReason
= $options['reason'];
160 $this->mTimestamp
= wfTimestamp( TS_MW
, $options['timestamp'] );
161 $this->mExpiry
= wfGetDB( DB_REPLICA
)->decodeExpiry( $options['expiry'] );
164 $this->mAuto
= (bool)$options['auto'];
165 $this->mHideName
= (bool)$options['hideName'];
166 $this->isHardblock( !$options['anonOnly'] );
167 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
169 # Prevention measures
170 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
171 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
172 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
174 $this->mFromMaster
= false;
175 $this->systemBlockType
= $options['systemBlock'];
179 * Load a blocked user from their block id.
181 * @param int $id Block id to search for
184 public static function newFromID( $id ) {
185 $dbr = wfGetDB( DB_REPLICA
);
186 $blockQuery = self
::getQueryInfo();
187 $res = $dbr->selectRow(
188 $blockQuery['tables'],
189 $blockQuery['fields'],
196 return self
::newFromRow( $res );
203 * Return the list of ipblocks fields that should be selected to create
205 * @deprecated since 1.31, use self::getQueryInfo() instead.
208 public static function selectFields() {
209 global $wgActorTableSchemaMigrationStage;
211 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
212 // If code is using this instead of self::getQueryInfo(), there's a
213 // decent chance it's going to try to directly access
214 // $row->ipb_by or $row->ipb_by_text and we can't give it
215 // useful values here once those aren't being used anymore.
216 throw new BadMethodCallException(
217 'Cannot use ' . __METHOD__
218 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
222 wfDeprecated( __METHOD__
, '1.31' );
228 'ipb_by_actor' => 'NULL',
232 'ipb_create_account',
233 'ipb_enable_autoblock',
237 'ipb_allow_usertalk',
238 'ipb_parent_block_id',
239 ] + CommentStore
::getStore()->getFields( 'ipb_reason' );
243 * Return the tables, fields, and join conditions to be selected to create
244 * a new block object.
246 * @return array With three keys:
247 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
248 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
249 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
251 public static function getQueryInfo() {
252 $commentQuery = CommentStore
::getStore()->getJoin( 'ipb_reason' );
253 $actorQuery = ActorMigration
::newMigration()->getJoin( 'ipb_by' );
255 'tables' => [ 'ipblocks' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
262 'ipb_create_account',
263 'ipb_enable_autoblock',
267 'ipb_allow_usertalk',
268 'ipb_parent_block_id',
269 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
270 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
275 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
276 * the blocking user or the block timestamp, only things which affect the blocked user
278 * @param Block $block
282 public function equals( Block
$block ) {
284 (string)$this->target
== (string)$block->target
285 && $this->type
== $block->type
286 && $this->mAuto
== $block->mAuto
287 && $this->isHardblock() == $block->isHardblock()
288 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
289 && $this->mExpiry
== $block->mExpiry
290 && $this->isAutoblocking() == $block->isAutoblocking()
291 && $this->mHideName
== $block->mHideName
292 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
293 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
294 && $this->mReason
== $block->mReason
299 * Load a block from the database which affects the already-set $this->target:
300 * 1) A block directly on the given user or IP
301 * 2) A rangeblock encompassing the given IP (smallest first)
302 * 3) An autoblock on the given IP
303 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
304 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
305 * @throws MWException
306 * @return bool Whether a relevant block was found
308 protected function newLoad( $vagueTarget = null ) {
309 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_REPLICA
);
311 if ( $this->type
!== null ) {
313 'ipb_address' => [ (string)$this->target
],
316 $conds = [ 'ipb_address' => [] ];
319 # Be aware that the != '' check is explicit, since empty values will be
320 # passed by some callers (T31116)
321 if ( $vagueTarget != '' ) {
322 list( $target, $type ) = self
::parseTarget( $vagueTarget );
324 case self
::TYPE_USER
:
325 # Slightly weird, but who are we to argue?
326 $conds['ipb_address'][] = (string)$target;
330 $conds['ipb_address'][] = (string)$target;
331 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
332 $conds = $db->makeList( $conds, LIST_OR
);
335 case self
::TYPE_RANGE
:
336 list( $start, $end ) = IP
::parseRange( $target );
337 $conds['ipb_address'][] = (string)$target;
338 $conds[] = self
::getRangeCond( $start, $end );
339 $conds = $db->makeList( $conds, LIST_OR
);
343 throw new MWException( "Tried to load block with invalid type" );
347 $blockQuery = self
::getQueryInfo();
349 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
352 # This result could contain a block on the user, a block on the IP, and a russian-doll
353 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
356 # Lower will be better
357 $bestBlockScore = 100;
359 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
360 $bestBlockPreventsEdit = null;
362 foreach ( $res as $row ) {
363 $block = self
::newFromRow( $row );
365 # Don't use expired blocks
366 if ( $block->isExpired() ) {
370 # Don't use anon only blocks on users
371 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
375 if ( $block->getType() == self
::TYPE_RANGE
) {
376 # This is the number of bits that are allowed to vary in the block, give
377 # or take some floating point errors
378 $end = Wikimedia\base_convert
( $block->getRangeEnd(), 16, 10 );
379 $start = Wikimedia\base_convert
( $block->getRangeStart(), 16, 10 );
380 $size = log( $end - $start +
1, 2 );
382 # This has the nice property that a /32 block is ranked equally with a
383 # single-IP block, which is exactly what it is...
384 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
387 $score = $block->getType();
390 if ( $score < $bestBlockScore ) {
391 $bestBlockScore = $score;
393 $bestBlockPreventsEdit = $block->prevents( 'edit' );
397 if ( $bestRow !== null ) {
398 $this->initFromRow( $bestRow );
399 $this->prevents( 'edit', $bestBlockPreventsEdit );
407 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
408 * @param string $start Hexadecimal IP representation
409 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
412 public static function getRangeCond( $start, $end = null ) {
413 if ( $end === null ) {
416 # Per T16634, we want to include relevant active rangeblocks; for
417 # rangeblocks, we want to include larger ranges which enclose the given
418 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
419 # so we can improve performance by filtering on a LIKE clause
420 $chunk = self
::getIpFragment( $start );
421 $dbr = wfGetDB( DB_REPLICA
);
422 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
424 # Fairly hard to make a malicious SQL statement out of hex characters,
425 # but stranger things have happened...
426 $safeStart = $dbr->addQuotes( $start );
427 $safeEnd = $dbr->addQuotes( $end );
429 return $dbr->makeList(
431 "ipb_range_start $like",
432 "ipb_range_start <= $safeStart",
433 "ipb_range_end >= $safeEnd",
440 * Get the component of an IP address which is certain to be the same between an IP
441 * address and a rangeblock containing that IP address.
442 * @param string $hex Hexadecimal IP representation
445 protected static function getIpFragment( $hex ) {
446 global $wgBlockCIDRLimit;
447 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
448 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
450 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
455 * Given a database row from the ipblocks table, initialize
457 * @param stdClass $row A row from the ipblocks table
459 protected function initFromRow( $row ) {
460 $this->setTarget( $row->ipb_address
);
461 $this->setBlocker( User
::newFromAnyId(
462 $row->ipb_by
, $row->ipb_by_text
, $row->ipb_by_actor ??
null
465 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
466 $this->mAuto
= $row->ipb_auto
;
467 $this->mHideName
= $row->ipb_deleted
;
468 $this->mId
= (int)$row->ipb_id
;
469 $this->mParentBlockId
= $row->ipb_parent_block_id
;
471 // I wish I didn't have to do this
472 $db = wfGetDB( DB_REPLICA
);
473 $this->mExpiry
= $db->decodeExpiry( $row->ipb_expiry
);
474 $this->mReason
= CommentStore
::getStore()
475 // Legacy because $row may have come from self::selectFields()
476 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
;
478 $this->isHardblock( !$row->ipb_anon_only
);
479 $this->isAutoblocking( $row->ipb_enable_autoblock
);
481 $this->prevents( 'createaccount', $row->ipb_create_account
);
482 $this->prevents( 'sendemail', $row->ipb_block_email
);
483 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
487 * Create a new Block object from a database row
488 * @param stdClass $row Row from the ipblocks table
491 public static function newFromRow( $row ) {
493 $block->initFromRow( $row );
498 * Delete the row from the IP blocks table.
500 * @throws MWException
503 public function delete() {
504 if ( wfReadOnly() ) {
508 if ( !$this->getId() ) {
509 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
512 $dbw = wfGetDB( DB_MASTER
);
513 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
514 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
516 return $dbw->affectedRows() > 0;
520 * Insert a block into the block table. Will fail if there is a conflicting
521 * block (same name and options) already in the database.
523 * @param IDatabase|null $dbw If you have one available
524 * @return bool|array False on failure, assoc array on success:
525 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
527 public function insert( $dbw = null ) {
528 global $wgBlockDisablesLogin;
530 if ( $this->getSystemBlockType() !== null ) {
531 throw new MWException( 'Cannot insert a system block into the database' );
533 if ( !$this->getBlocker() ||
$this->getBlocker()->getName() === '' ) {
534 throw new MWException( 'Cannot insert a block without a blocker set' );
537 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
539 if ( $dbw === null ) {
540 $dbw = wfGetDB( DB_MASTER
);
543 self
::purgeExpired();
545 $row = $this->getDatabaseArray( $dbw );
547 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
548 $affected = $dbw->affectedRows();
549 $this->mId
= $dbw->insertId();
551 # Don't collide with expired blocks.
552 # Do this after trying to insert to avoid locking.
554 # T96428: The ipb_address index uses a prefix on a field, so
555 # use a standard SELECT + DELETE to avoid annoying gap locks.
556 $ids = $dbw->selectFieldValues( 'ipblocks',
559 'ipb_address' => $row['ipb_address'],
560 'ipb_user' => $row['ipb_user'],
561 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
566 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
567 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
568 $affected = $dbw->affectedRows();
569 $this->mId
= $dbw->insertId();
574 $auto_ipd_ids = $this->doRetroactiveAutoblock();
576 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
577 // Change user login token to force them to be logged out.
578 $this->target
->setToken();
579 $this->target
->saveSettings();
582 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
589 * Update a block in the DB with new parameters.
590 * The ID field needs to be loaded first.
592 * @return bool|array False on failure, array on success:
593 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
595 public function update() {
596 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
597 $dbw = wfGetDB( DB_MASTER
);
599 $dbw->startAtomic( __METHOD__
);
603 $this->getDatabaseArray( $dbw ),
604 [ 'ipb_id' => $this->getId() ],
608 $affected = $dbw->affectedRows();
610 if ( $this->isAutoblocking() ) {
611 // update corresponding autoblock(s) (T50813)
614 $this->getAutoblockUpdateArray( $dbw ),
615 [ 'ipb_parent_block_id' => $this->getId() ],
619 // autoblock no longer required, delete corresponding autoblock(s)
622 [ 'ipb_parent_block_id' => $this->getId() ],
627 $dbw->endAtomic( __METHOD__
);
630 $auto_ipd_ids = $this->doRetroactiveAutoblock();
631 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
638 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
639 * @param IDatabase $dbw
642 protected function getDatabaseArray( IDatabase
$dbw ) {
643 $expiry = $dbw->encodeExpiry( $this->mExpiry
);
645 if ( $this->forcedTargetID
) {
646 $uid = $this->forcedTargetID
;
648 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
652 'ipb_address' => (string)$this->target
,
654 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
655 'ipb_auto' => $this->mAuto
,
656 'ipb_anon_only' => !$this->isHardblock(),
657 'ipb_create_account' => $this->prevents( 'createaccount' ),
658 'ipb_enable_autoblock' => $this->isAutoblocking(),
659 'ipb_expiry' => $expiry,
660 'ipb_range_start' => $this->getRangeStart(),
661 'ipb_range_end' => $this->getRangeEnd(),
662 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
663 'ipb_block_email' => $this->prevents( 'sendemail' ),
664 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
665 'ipb_parent_block_id' => $this->mParentBlockId
666 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->mReason
)
667 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
673 * @param IDatabase $dbw
676 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
678 'ipb_create_account' => $this->prevents( 'createaccount' ),
679 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
680 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
681 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->mReason
)
682 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
686 * Retroactively autoblocks the last IP used by the user (if it is a user)
687 * blocked by this Block.
689 * @return array Block IDs of retroactive autoblocks made
691 protected function doRetroactiveAutoblock() {
693 # If autoblock is enabled, autoblock the LAST IP(s) used
694 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
695 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
697 $continue = Hooks
::run(
698 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
701 self
::defaultRetroactiveAutoblock( $this, $blockIds );
708 * Retroactively autoblocks the last IP used by the user (if it is a user)
709 * blocked by this Block. This will use the recentchanges table.
711 * @param Block $block
712 * @param array &$blockIds
714 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
717 // No IPs are in recentchanges table, so nothing to select
718 if ( !$wgPutIPinRC ) {
722 $target = $block->getTarget();
723 if ( is_string( $target ) ) {
724 $target = User
::newFromName( $target, false );
727 $dbr = wfGetDB( DB_REPLICA
);
728 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
730 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
732 // Just the last IP used.
733 $options['LIMIT'] = 1;
736 [ 'recentchanges' ] +
$rcQuery['tables'],
744 if ( !$res->numRows() ) {
745 # No results, don't autoblock anything
746 wfDebug( "No IP found to retroactively autoblock\n" );
748 foreach ( $res as $row ) {
750 $id = $block->doAutoblock( $row->rc_ip
);
760 * Checks whether a given IP is on the autoblock whitelist.
761 * TODO: this probably belongs somewhere else, but not sure where...
763 * @param string $ip The IP to check
766 public static function isWhitelistedFromAutoblocks( $ip ) {
767 // Try to get the autoblock_whitelist from the cache, as it's faster
768 // than getting the msg raw and explode()'ing it.
769 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
770 $lines = $cache->getWithSetCallback(
771 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
773 function ( $curValue, &$ttl, array &$setOpts ) {
774 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
776 return explode( "\n",
777 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
781 wfDebug( "Checking the autoblock whitelist..\n" );
783 foreach ( $lines as $line ) {
785 if ( substr( $line, 0, 1 ) !== '*' ) {
789 $wlEntry = substr( $line, 1 );
790 $wlEntry = trim( $wlEntry );
792 wfDebug( "Checking $ip against $wlEntry..." );
794 # Is the IP in this range?
795 if ( IP
::isInRange( $ip, $wlEntry ) ) {
796 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
799 wfDebug( " No match\n" );
807 * Autoblocks the given IP, referring to this Block.
809 * @param string $autoblockIP The IP to autoblock.
810 * @return int|bool Block ID if an autoblock was inserted, false if not.
812 public function doAutoblock( $autoblockIP ) {
813 # If autoblocks are disabled, go away.
814 if ( !$this->isAutoblocking() ) {
818 # Don't autoblock for system blocks
819 if ( $this->getSystemBlockType() !== null ) {
820 throw new MWException( 'Cannot autoblock from a system block' );
823 # Check for presence on the autoblock whitelist.
824 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
828 // Avoid PHP 7.1 warning of passing $this by reference
830 # Allow hooks to cancel the autoblock.
831 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
832 wfDebug( "Autoblock aborted by hook.\n" );
836 # It's okay to autoblock. Go ahead and insert/update the block...
838 # Do not add a *new* block if the IP is already blocked.
839 $ipblock = self
::newFromTarget( $autoblockIP );
841 # Check if the block is an autoblock and would exceed the user block
842 # if renewed. If so, do nothing, otherwise prolong the block time...
843 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
844 $this->mExpiry
> self
::getAutoblockExpiry( $ipblock->mTimestamp
)
846 # Reset block timestamp to now and its expiry to
847 # $wgAutoblockExpiry in the future
848 $ipblock->updateTimestamp();
853 # Make a new block object with the desired properties.
854 $autoblock = new Block
;
855 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
856 $autoblock->setTarget( $autoblockIP );
857 $autoblock->setBlocker( $this->getBlocker() );
858 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
859 ->inContentLanguage()->plain();
860 $timestamp = wfTimestampNow();
861 $autoblock->mTimestamp
= $timestamp;
862 $autoblock->mAuto
= 1;
863 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
864 # Continue suppressing the name if needed
865 $autoblock->mHideName
= $this->mHideName
;
866 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
867 $autoblock->mParentBlockId
= $this->mId
;
869 if ( $this->mExpiry
== 'infinity' ) {
870 # Original block was indefinite, start an autoblock now
871 $autoblock->mExpiry
= self
::getAutoblockExpiry( $timestamp );
873 # If the user is already blocked with an expiry date, we don't
874 # want to pile on top of that.
875 $autoblock->mExpiry
= min( $this->mExpiry
, self
::getAutoblockExpiry( $timestamp ) );
878 # Insert the block...
879 $status = $autoblock->insert();
886 * Check if a block has expired. Delete it if it is.
889 public function deleteIfExpired() {
890 if ( $this->isExpired() ) {
891 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
895 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
903 * Has the block expired?
906 public function isExpired() {
907 $timestamp = wfTimestampNow();
908 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
910 if ( !$this->mExpiry
) {
913 return $timestamp > $this->mExpiry
;
918 * Is the block address valid (i.e. not a null string?)
921 public function isValid() {
922 return $this->getTarget() != null;
926 * Update the timestamp on autoblocks.
928 public function updateTimestamp() {
929 if ( $this->mAuto
) {
930 $this->mTimestamp
= wfTimestamp();
931 $this->mExpiry
= self
::getAutoblockExpiry( $this->mTimestamp
);
933 $dbw = wfGetDB( DB_MASTER
);
934 $dbw->update( 'ipblocks',
936 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
937 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
940 'ipb_id' => $this->getId(),
948 * Get the IP address at the start of the range in Hex form
949 * @throws MWException
950 * @return string IP in Hex form
952 public function getRangeStart() {
953 switch ( $this->type
) {
954 case self
::TYPE_USER
:
957 return IP
::toHex( $this->target
);
958 case self
::TYPE_RANGE
:
959 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
962 throw new MWException( "Block with invalid type" );
967 * Get the IP address at the end of the range in Hex form
968 * @throws MWException
969 * @return string IP in Hex form
971 public function getRangeEnd() {
972 switch ( $this->type
) {
973 case self
::TYPE_USER
:
976 return IP
::toHex( $this->target
);
977 case self
::TYPE_RANGE
:
978 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
981 throw new MWException( "Block with invalid type" );
986 * Get the user id of the blocking sysop
988 * @return int (0 for foreign users)
990 public function getBy() {
991 $blocker = $this->getBlocker();
992 return ( $blocker instanceof User
)
998 * Get the username of the blocking sysop
1002 public function getByName() {
1003 $blocker = $this->getBlocker();
1004 return ( $blocker instanceof User
)
1005 ?
$blocker->getName()
1006 : (string)$blocker; // username
1013 public function getId() {
1018 * Get the system block type, if any
1020 * @return string|null
1022 public function getSystemBlockType() {
1023 return $this->systemBlockType
;
1027 * Get/set a flag determining whether the master is used for reads
1029 * @param bool|null $x
1032 public function fromMaster( $x = null ) {
1033 return wfSetVar( $this->mFromMaster
, $x );
1037 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1038 * @param bool|null $x
1041 public function isHardblock( $x = null ) {
1042 wfSetVar( $this->isHardblock
, $x );
1044 # You can't *not* hardblock a user
1045 return $this->getType() == self
::TYPE_USER
1047 : $this->isHardblock
;
1051 * @param null|bool $x
1054 public function isAutoblocking( $x = null ) {
1055 wfSetVar( $this->isAutoblocking
, $x );
1057 # You can't put an autoblock on an IP or range as we don't have any history to
1058 # look over to get more IPs from
1059 return $this->getType() == self
::TYPE_USER
1060 ?
$this->isAutoblocking
1065 * Get/set whether the Block prevents a given action
1067 * @param string $action Action to check
1068 * @param bool|null $x Value for set, or null to just get value
1069 * @return bool|null Null for unrecognized rights.
1071 public function prevents( $action, $x = null ) {
1072 global $wgBlockDisablesLogin;
1074 switch ( $action ) {
1076 # For now... <evil laugh>
1079 case 'createaccount':
1080 $res = wfSetVar( $this->mCreateAccount
, $x );
1083 $res = wfSetVar( $this->mBlockEmail
, $x );
1085 case 'editownusertalk':
1086 $res = wfSetVar( $this->mDisableUsertalk
, $x );
1092 if ( !$res && $wgBlockDisablesLogin ) {
1093 // If a block would disable login, then it should
1094 // prevent any action that all users cannot do
1096 $res = $anon->isAllowed( $action ) ?
$res : true;
1103 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1104 * @return string Text is escaped
1106 public function getRedactedName() {
1107 if ( $this->mAuto
) {
1108 return Html
::rawElement(
1110 [ 'class' => 'mw-autoblockid' ],
1111 wfMessage( 'autoblockid', $this->mId
)
1114 return htmlspecialchars( $this->getTarget() );
1119 * Get a timestamp of the expiry for autoblocks
1121 * @param string|int $timestamp
1124 public static function getAutoblockExpiry( $timestamp ) {
1125 global $wgAutoblockExpiry;
1127 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1131 * Purge expired blocks from the ipblocks table
1133 public static function purgeExpired() {
1134 if ( wfReadOnly() ) {
1138 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1139 wfGetDB( DB_MASTER
),
1141 function ( IDatabase
$dbw, $fname ) {
1142 $ids = $dbw->selectFieldValues( 'ipblocks',
1144 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1148 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1155 * Given a target and the target's type, get an existing Block object if possible.
1156 * @param string|User|int $specificTarget A block target, which may be one of several types:
1157 * * A user to block, in which case $target will be a User
1158 * * An IP to block, in which case $target will be a User generated by using
1159 * User::newFromName( $ip, false ) to turn off name validation
1160 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1161 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1163 * Calling this with a user, IP address or range will not select autoblocks, and will
1164 * only select a block where the targets match exactly (so looking for blocks on
1165 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1166 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1167 * affects that target (so for an IP address, get ranges containing that IP; and also
1168 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1169 * @param bool $fromMaster Whether to use the DB_MASTER database
1170 * @return Block|null (null if no relevant block could be found). The target and type
1171 * of the returned Block will refer to the actual block which was found, which might
1172 * not be the same as the target you gave if you used $vagueTarget!
1174 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1175 list( $target, $type ) = self
::parseTarget( $specificTarget );
1176 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1177 return self
::newFromID( $target );
1179 } elseif ( $target === null && $vagueTarget == '' ) {
1180 # We're not going to find anything useful here
1181 # Be aware that the == '' check is explicit, since empty values will be
1182 # passed by some callers (T31116)
1185 } elseif ( in_array(
1187 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1189 $block = new Block();
1190 $block->fromMaster( $fromMaster );
1192 if ( $type !== null ) {
1193 $block->setTarget( $target );
1196 if ( $block->newLoad( $vagueTarget ) ) {
1204 * Get all blocks that match any IP from an array of IP addresses
1206 * @param array $ipChain List of IPs (strings), usually retrieved from the
1207 * X-Forwarded-For header of the request
1208 * @param bool $isAnon Exclude anonymous-only blocks if false
1209 * @param bool $fromMaster Whether to query the master or replica DB
1210 * @return array Array of Blocks
1213 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1214 if ( !count( $ipChain ) ) {
1219 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1220 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1221 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1222 # necessarily trust the header given to us, make sure that we are only
1223 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1224 # Do not treat private IP spaces as special as it may be desirable for wikis
1225 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1226 if ( !IP
::isValid( $ipaddr ) ) {
1229 # Don't check trusted IPs (includes local squids which will be in every request)
1230 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1233 # Check both the original IP (to check against single blocks), as well as build
1234 # the clause to check for rangeblocks for the given IP.
1235 $conds['ipb_address'][] = $ipaddr;
1236 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1239 if ( !count( $conds ) ) {
1243 if ( $fromMaster ) {
1244 $db = wfGetDB( DB_MASTER
);
1246 $db = wfGetDB( DB_REPLICA
);
1248 $conds = $db->makeList( $conds, LIST_OR
);
1250 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1252 $blockQuery = self
::getQueryInfo();
1253 $rows = $db->select(
1254 $blockQuery['tables'],
1255 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1259 $blockQuery['joins']
1263 foreach ( $rows as $row ) {
1264 $block = self
::newFromRow( $row );
1265 if ( !$block->isExpired() ) {
1274 * From a list of multiple blocks, find the most exact and strongest Block.
1276 * The logic for finding the "best" block is:
1277 * - Blocks that match the block's target IP are preferred over ones in a range
1278 * - Hardblocks are chosen over softblocks that prevent account creation
1279 * - Softblocks that prevent account creation are chosen over other softblocks
1280 * - Other softblocks are chosen over autoblocks
1281 * - If there are multiple exact or range blocks at the same level, the one chosen
1283 * This should be used when $blocks where retrieved from the user's IP address
1284 * and $ipChain is populated from the same IP address information.
1286 * @param array $blocks Array of Block objects
1287 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1288 * a block is to the server, and if a block matches exactly, or is in a range.
1289 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1291 * @throws MWException
1292 * @return Block|null The "best" block from the list
1294 public static function chooseBlock( array $blocks, array $ipChain ) {
1295 if ( !count( $blocks ) ) {
1297 } elseif ( count( $blocks ) == 1 ) {
1301 // Sort hard blocks before soft ones and secondarily sort blocks
1302 // that disable account creation before those that don't.
1303 usort( $blocks, function ( Block
$a, Block
$b ) {
1304 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1305 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1306 return strcmp( $bWeight, $aWeight ); // highest weight first
1309 $blocksListExact = [
1311 'disable_create' => false,
1315 $blocksListRange = [
1317 'disable_create' => false,
1321 $ipChain = array_reverse( $ipChain );
1323 /** @var Block $block */
1324 foreach ( $blocks as $block ) {
1325 // Stop searching if we have already have a "better" block. This
1326 // is why the order of the blocks matters
1327 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1329 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1333 foreach ( $ipChain as $checkip ) {
1334 $checkipHex = IP
::toHex( $checkip );
1335 if ( (string)$block->getTarget() === $checkip ) {
1336 if ( $block->isHardblock() ) {
1337 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1338 } elseif ( $block->prevents( 'createaccount' ) ) {
1339 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1340 } elseif ( $block->mAuto
) {
1341 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1343 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1345 // We found closest exact match in the ip list, so go to the next Block
1347 } elseif ( array_filter( $blocksListExact ) == []
1348 && $block->getRangeStart() <= $checkipHex
1349 && $block->getRangeEnd() >= $checkipHex
1351 if ( $block->isHardblock() ) {
1352 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1353 } elseif ( $block->prevents( 'createaccount' ) ) {
1354 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1355 } elseif ( $block->mAuto
) {
1356 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1358 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1365 if ( array_filter( $blocksListExact ) == [] ) {
1366 $blocksList = &$blocksListRange;
1368 $blocksList = &$blocksListExact;
1371 $chosenBlock = null;
1372 if ( $blocksList['hard'] ) {
1373 $chosenBlock = $blocksList['hard'];
1374 } elseif ( $blocksList['disable_create'] ) {
1375 $chosenBlock = $blocksList['disable_create'];
1376 } elseif ( $blocksList['other'] ) {
1377 $chosenBlock = $blocksList['other'];
1378 } elseif ( $blocksList['auto'] ) {
1379 $chosenBlock = $blocksList['auto'];
1381 throw new MWException( "Proxy block found, but couldn't be classified." );
1384 return $chosenBlock;
1388 * From an existing Block, get the target and the type of target.
1389 * Note that, except for null, it is always safe to treat the target
1390 * as a string; for User objects this will return User::__toString()
1391 * which in turn gives User::getName().
1393 * @param string|int|User|null $target
1394 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1396 public static function parseTarget( $target ) {
1397 # We may have been through this before
1398 if ( $target instanceof User
) {
1399 if ( IP
::isValid( $target->getName() ) ) {
1400 return [ $target, self
::TYPE_IP
];
1402 return [ $target, self
::TYPE_USER
];
1404 } elseif ( $target === null ) {
1405 return [ null, null ];
1408 $target = trim( $target );
1410 if ( IP
::isValid( $target ) ) {
1411 # We can still create a User if it's an IP address, but we need to turn
1412 # off validation checking (which would exclude IP addresses)
1414 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1418 } elseif ( IP
::isValidRange( $target ) ) {
1419 # Can't create a User from an IP range
1420 return [ IP
::sanitizeRange( $target ), self
::TYPE_RANGE
];
1423 # Consider the possibility that this is not a username at all
1424 # but actually an old subpage (T31797)
1425 if ( strpos( $target, '/' ) !== false ) {
1426 # An old subpage, drill down to the user behind it
1427 $target = explode( '/', $target )[0];
1430 $userObj = User
::newFromName( $target );
1431 if ( $userObj instanceof User
) {
1432 # Note that since numbers are valid usernames, a $target of "12345" will be
1433 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1434 # since hash characters are not valid in usernames or titles generally.
1435 return [ $userObj, self
::TYPE_USER
];
1437 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1438 # Autoblock reference in the form "#12345"
1439 return [ substr( $target, 1 ), self
::TYPE_AUTO
];
1443 return [ null, null ];
1448 * Get the type of target for this particular block
1449 * @return int Block::TYPE_ constant, will never be TYPE_ID
1451 public function getType() {
1458 * Get the target and target type for this particular Block. Note that for autoblocks,
1459 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1460 * in this situation.
1461 * @return array [ User|String, Block::TYPE_ constant ]
1462 * @todo FIXME: This should be an integral part of the Block member variables
1464 public function getTargetAndType() {
1465 return [ $this->getTarget(), $this->getType() ];
1469 * Get the target for this particular Block. Note that for autoblocks,
1470 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1471 * in this situation.
1472 * @return User|string
1474 public function getTarget() {
1475 return $this->target
;
1481 * @return mixed|string
1483 public function getExpiry() {
1484 return $this->mExpiry
;
1488 * Set the target for this block, and update $this->type accordingly
1489 * @param mixed $target
1491 public function setTarget( $target ) {
1492 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1496 * Get the user who implemented this block
1497 * @return User User object. May name a foreign user.
1499 public function getBlocker() {
1500 return $this->blocker
;
1504 * Set the user who implemented (or will implement) this block
1505 * @param User|string $user Local User object or username string
1507 public function setBlocker( $user ) {
1508 if ( is_string( $user ) ) {
1509 $user = User
::newFromName( $user, false );
1512 if ( $user->isAnon() && User
::isUsableName( $user->getName() ) ) {
1513 throw new InvalidArgumentException(
1514 'Blocker must be a local user or a name that cannot be a local user'
1518 $this->blocker
= $user;
1522 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1523 * the same as the block's, to a maximum of 24 hours.
1527 * @param WebResponse $response The response on which to set the cookie.
1529 public function setCookie( WebResponse
$response ) {
1530 // Calculate the default expiry time.
1531 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1533 // Use the Block's expiry time only if it's less than the default.
1534 $expiryTime = $this->getExpiry();
1535 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1536 $expiryTime = $maxExpiryTime;
1539 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1540 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1541 $cookieOptions = [ 'httpOnly' => false ];
1542 $cookieValue = $this->getCookieValue();
1543 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1547 * Unset the 'BlockID' cookie.
1551 * @param WebResponse $response The response on which to unset the cookie.
1553 public static function clearCookie( WebResponse
$response ) {
1554 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1558 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1559 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1564 * @return string The block ID, probably concatenated with "!" and the HMAC.
1566 public function getCookieValue() {
1567 $config = RequestContext
::getMain()->getConfig();
1568 $id = $this->getId();
1569 $secretKey = $config->get( 'SecretKey' );
1570 if ( !$secretKey ) {
1571 // If there's no secret key, don't append a HMAC.
1574 $hmac = MWCryptHash
::hmac( $id, $secretKey, false );
1575 $cookieValue = $id . '!' . $hmac;
1576 return $cookieValue;
1580 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1581 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1585 * @param string $cookieValue The string in which to find the ID.
1587 * @return int|null The block ID, or null if the HMAC is present and invalid.
1589 public static function getIdFromCookieValue( $cookieValue ) {
1590 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1591 $bangPos = strpos( $cookieValue, '!' );
1592 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
1593 // Get the site-wide secret key.
1594 $config = RequestContext
::getMain()->getConfig();
1595 $secretKey = $config->get( 'SecretKey' );
1596 if ( !$secretKey ) {
1597 // If there's no secret key, just use the ID as given.
1600 $storedHmac = substr( $cookieValue, $bangPos +
1 );
1601 $calculatedHmac = MWCryptHash
::hmac( $id, $secretKey, false );
1602 if ( $calculatedHmac === $storedHmac ) {
1610 * Get the key and parameters for the corresponding error message.
1613 * @param IContextSource $context
1616 public function getPermissionsError( IContextSource
$context ) {
1617 $blocker = $this->getBlocker();
1618 if ( $blocker instanceof User
) { // local user
1619 $blockerUserpage = $blocker->getUserPage();
1620 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1621 } else { // foreign user
1625 $reason = $this->mReason
;
1626 if ( $reason == '' ) {
1627 $reason = $context->msg( 'blockednoreason' )->text();
1630 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1631 * This could be a username, an IP range, or a single IP. */
1632 $intended = $this->getTarget();
1634 $systemBlockType = $this->getSystemBlockType();
1636 $lang = $context->getLanguage();
1638 $systemBlockType !== null
1639 ?
'systemblockedtext'
1640 : ( $this->mAuto ?
'autoblockedtext' : 'blockedtext' ),
1643 $context->getRequest()->getIP(),
1645 $systemBlockType ??
$this->getId(),
1646 $lang->formatExpiry( $this->mExpiry
),
1648 $lang->userTimeAndDate( $this->mTimestamp
, $context->getUser() ),