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\BlockRestrictionStore
;
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 && $this->getBlockRestrictionStore()->equals(
309 $this->getRestrictions(), $block->getRestrictions()
315 * Load a block from the database which affects the already-set $this->target:
316 * 1) A block directly on the given user or IP
317 * 2) A rangeblock encompassing the given IP (smallest first)
318 * 3) An autoblock on the given IP
319 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
320 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
321 * @throws MWException
322 * @return bool Whether a relevant block was found
324 protected function newLoad( $vagueTarget = null ) {
325 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_REPLICA
);
327 if ( $this->type
!== null ) {
329 'ipb_address' => [ (string)$this->target
],
332 $conds = [ 'ipb_address' => [] ];
335 # Be aware that the != '' check is explicit, since empty values will be
336 # passed by some callers (T31116)
337 if ( $vagueTarget != '' ) {
338 list( $target, $type ) = self
::parseTarget( $vagueTarget );
340 case self
::TYPE_USER
:
341 # Slightly weird, but who are we to argue?
342 $conds['ipb_address'][] = (string)$target;
346 $conds['ipb_address'][] = (string)$target;
347 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
348 $conds = $db->makeList( $conds, LIST_OR
);
351 case self
::TYPE_RANGE
:
352 list( $start, $end ) = IP
::parseRange( $target );
353 $conds['ipb_address'][] = (string)$target;
354 $conds[] = self
::getRangeCond( $start, $end );
355 $conds = $db->makeList( $conds, LIST_OR
);
359 throw new MWException( "Tried to load block with invalid type" );
363 $blockQuery = self
::getQueryInfo();
365 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
368 # This result could contain a block on the user, a block on the IP, and a russian-doll
369 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
372 # Lower will be better
373 $bestBlockScore = 100;
375 foreach ( $res as $row ) {
376 $block = self
::newFromRow( $row );
378 # Don't use expired blocks
379 if ( $block->isExpired() ) {
383 # Don't use anon only blocks on users
384 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
388 if ( $block->getType() == self
::TYPE_RANGE
) {
389 # This is the number of bits that are allowed to vary in the block, give
390 # or take some floating point errors
392 $end = Wikimedia\base_convert
( ltrim( $block->getRangeEnd(), $prefix ), 16, 10 );
393 $start = Wikimedia\base_convert
( ltrim( $block->getRangeStart(), $prefix ), 16, 10 );
394 $size = log( $end - $start +
1, 2 );
396 # This has the nice property that a /32 block is ranked equally with a
397 # single-IP block, which is exactly what it is...
398 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
401 $score = $block->getType();
404 if ( $score < $bestBlockScore ) {
405 $bestBlockScore = $score;
410 if ( $bestRow !== null ) {
411 $this->initFromRow( $bestRow );
419 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
420 * @param string $start Hexadecimal IP representation
421 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
424 public static function getRangeCond( $start, $end = null ) {
425 if ( $end === null ) {
428 # Per T16634, we want to include relevant active rangeblocks; for
429 # rangeblocks, we want to include larger ranges which enclose the given
430 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
431 # so we can improve performance by filtering on a LIKE clause
432 $chunk = self
::getIpFragment( $start );
433 $dbr = wfGetDB( DB_REPLICA
);
434 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
436 # Fairly hard to make a malicious SQL statement out of hex characters,
437 # but stranger things have happened...
438 $safeStart = $dbr->addQuotes( $start );
439 $safeEnd = $dbr->addQuotes( $end );
441 return $dbr->makeList(
443 "ipb_range_start $like",
444 "ipb_range_start <= $safeStart",
445 "ipb_range_end >= $safeEnd",
452 * Get the component of an IP address which is certain to be the same between an IP
453 * address and a rangeblock containing that IP address.
454 * @param string $hex Hexadecimal IP representation
457 protected static function getIpFragment( $hex ) {
458 global $wgBlockCIDRLimit;
459 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
460 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
462 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
467 * Given a database row from the ipblocks table, initialize
469 * @param stdClass $row A row from the ipblocks table
471 protected function initFromRow( $row ) {
472 $this->setTarget( $row->ipb_address
);
473 $this->setBlocker( User
::newFromAnyId(
474 $row->ipb_by
, $row->ipb_by_text
, $row->ipb_by_actor ??
null
477 $this->setTimestamp( wfTimestamp( TS_MW
, $row->ipb_timestamp
) );
478 $this->mAuto
= $row->ipb_auto
;
479 $this->setHideName( $row->ipb_deleted
);
480 $this->mId
= (int)$row->ipb_id
;
481 $this->mParentBlockId
= $row->ipb_parent_block_id
;
483 // I wish I didn't have to do this
484 $db = wfGetDB( DB_REPLICA
);
485 $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry
) );
487 CommentStore
::getStore()
488 // Legacy because $row may have come from self::selectFields()
489 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
492 $this->isHardblock( !$row->ipb_anon_only
);
493 $this->isAutoblocking( $row->ipb_enable_autoblock
);
494 $this->isSitewide( (bool)$row->ipb_sitewide
);
496 $this->isCreateAccountBlocked( $row->ipb_create_account
);
497 $this->isEmailBlocked( $row->ipb_block_email
);
498 $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk
);
502 * Create a new Block object from a database row
503 * @param stdClass $row Row from the ipblocks table
506 public static function newFromRow( $row ) {
508 $block->initFromRow( $row );
513 * Delete the row from the IP blocks table.
515 * @throws MWException
518 public function delete() {
519 if ( wfReadOnly() ) {
523 if ( !$this->getId() ) {
524 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
527 $dbw = wfGetDB( DB_MASTER
);
529 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
530 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
532 $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
533 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
535 return $dbw->affectedRows() > 0;
539 * Insert a block into the block table. Will fail if there is a conflicting
540 * block (same name and options) already in the database.
542 * @param IDatabase|null $dbw If you have one available
543 * @return bool|array False on failure, assoc array on success:
544 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
546 public function insert( $dbw = null ) {
547 global $wgBlockDisablesLogin;
549 if ( $this->getSystemBlockType() !== null ) {
550 throw new MWException( 'Cannot insert a system block into the database' );
552 if ( !$this->getBlocker() ||
$this->getBlocker()->getName() === '' ) {
553 throw new MWException( 'Cannot insert a block without a blocker set' );
556 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
558 if ( $dbw === null ) {
559 $dbw = wfGetDB( DB_MASTER
);
562 self
::purgeExpired();
564 $row = $this->getDatabaseArray( $dbw );
566 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
567 $affected = $dbw->affectedRows();
569 $this->setId( $dbw->insertId() );
570 if ( $this->restrictions
) {
571 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
575 # Don't collide with expired blocks.
576 # Do this after trying to insert to avoid locking.
578 # T96428: The ipb_address index uses a prefix on a field, so
579 # use a standard SELECT + DELETE to avoid annoying gap locks.
580 $ids = $dbw->selectFieldValues( 'ipblocks',
583 'ipb_address' => $row['ipb_address'],
584 'ipb_user' => $row['ipb_user'],
585 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
590 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
591 $this->getBlockRestrictionStore()->deleteByBlockId( $ids );
592 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
593 $affected = $dbw->affectedRows();
594 $this->setId( $dbw->insertId() );
595 if ( $this->restrictions
) {
596 $this->getBlockRestrictionStore()->insert( $this->restrictions
);
602 $auto_ipd_ids = $this->doRetroactiveAutoblock();
604 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
605 // Change user login token to force them to be logged out.
606 $this->target
->setToken();
607 $this->target
->saveSettings();
610 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
617 * Update a block in the DB with new parameters.
618 * The ID field needs to be loaded first.
620 * @return bool|array False on failure, array on success:
621 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
623 public function update() {
624 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
625 $dbw = wfGetDB( DB_MASTER
);
627 $dbw->startAtomic( __METHOD__
);
629 $result = $dbw->update(
631 $this->getDatabaseArray( $dbw ),
632 [ 'ipb_id' => $this->getId() ],
636 // Only update the restrictions if they have been modified.
637 if ( $this->restrictions
!== null ) {
638 // An empty array should remove all of the restrictions.
639 if ( empty( $this->restrictions
) ) {
640 $success = $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
642 $success = $this->getBlockRestrictionStore()->update( $this->restrictions
);
644 // Update the result. The first false is the result, otherwise, true.
645 $result = $result && $success;
648 if ( $this->isAutoblocking() ) {
649 // update corresponding autoblock(s) (T50813)
652 $this->getAutoblockUpdateArray( $dbw ),
653 [ 'ipb_parent_block_id' => $this->getId() ],
657 // Only update the restrictions if they have been modified.
658 if ( $this->restrictions
!== null ) {
659 $this->getBlockRestrictionStore()->updateByParentBlockId( $this->getId(), $this->restrictions
);
662 // autoblock no longer required, delete corresponding autoblock(s)
663 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
666 [ 'ipb_parent_block_id' => $this->getId() ],
671 $dbw->endAtomic( __METHOD__
);
674 $auto_ipd_ids = $this->doRetroactiveAutoblock();
675 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
682 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
683 * @param IDatabase $dbw
686 protected function getDatabaseArray( IDatabase
$dbw ) {
687 $expiry = $dbw->encodeExpiry( $this->getExpiry() );
689 if ( $this->forcedTargetID
) {
690 $uid = $this->forcedTargetID
;
692 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
696 'ipb_address' => (string)$this->target
,
698 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
699 'ipb_auto' => $this->mAuto
,
700 'ipb_anon_only' => !$this->isHardblock(),
701 'ipb_create_account' => $this->isCreateAccountBlocked(),
702 'ipb_enable_autoblock' => $this->isAutoblocking(),
703 'ipb_expiry' => $expiry,
704 'ipb_range_start' => $this->getRangeStart(),
705 'ipb_range_end' => $this->getRangeEnd(),
706 'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
707 'ipb_block_email' => $this->isEmailBlocked(),
708 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
709 'ipb_parent_block_id' => $this->mParentBlockId
,
710 'ipb_sitewide' => $this->isSitewide(),
711 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
712 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
718 * @param IDatabase $dbw
721 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
723 'ipb_create_account' => $this->isCreateAccountBlocked(),
724 'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
725 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
726 'ipb_sitewide' => $this->isSitewide(),
727 ] + CommentStore
::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
728 + ActorMigration
::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
732 * Retroactively autoblocks the last IP used by the user (if it is a user)
733 * blocked by this Block.
735 * @return array Block IDs of retroactive autoblocks made
737 protected function doRetroactiveAutoblock() {
739 # If autoblock is enabled, autoblock the LAST IP(s) used
740 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
741 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
743 $continue = Hooks
::run(
744 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
747 self
::defaultRetroactiveAutoblock( $this, $blockIds );
754 * Retroactively autoblocks the last IP used by the user (if it is a user)
755 * blocked by this Block. This will use the recentchanges table.
757 * @param Block $block
758 * @param array &$blockIds
760 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
763 // No IPs are in recentchanges table, so nothing to select
764 if ( !$wgPutIPinRC ) {
768 // Autoblocks only apply to TYPE_USER
769 if ( $block->getType() !== self
::TYPE_USER
) {
772 $target = $block->getTarget(); // TYPE_USER => always a User object
774 $dbr = wfGetDB( DB_REPLICA
);
775 $rcQuery = ActorMigration
::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
777 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
779 // Just the last IP used.
780 $options['LIMIT'] = 1;
783 [ 'recentchanges' ] +
$rcQuery['tables'],
791 if ( !$res->numRows() ) {
792 # No results, don't autoblock anything
793 wfDebug( "No IP found to retroactively autoblock\n" );
795 foreach ( $res as $row ) {
797 $id = $block->doAutoblock( $row->rc_ip
);
807 * Checks whether a given IP is on the autoblock whitelist.
808 * TODO: this probably belongs somewhere else, but not sure where...
810 * @param string $ip The IP to check
813 public static function isWhitelistedFromAutoblocks( $ip ) {
814 // Try to get the autoblock_whitelist from the cache, as it's faster
815 // than getting the msg raw and explode()'ing it.
816 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
817 $lines = $cache->getWithSetCallback(
818 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
820 function ( $curValue, &$ttl, array &$setOpts ) {
821 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
823 return explode( "\n",
824 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
828 wfDebug( "Checking the autoblock whitelist..\n" );
830 foreach ( $lines as $line ) {
832 if ( substr( $line, 0, 1 ) !== '*' ) {
836 $wlEntry = substr( $line, 1 );
837 $wlEntry = trim( $wlEntry );
839 wfDebug( "Checking $ip against $wlEntry..." );
841 # Is the IP in this range?
842 if ( IP
::isInRange( $ip, $wlEntry ) ) {
843 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
846 wfDebug( " No match\n" );
854 * Autoblocks the given IP, referring to this Block.
856 * @param string $autoblockIP The IP to autoblock.
857 * @return int|bool Block ID if an autoblock was inserted, false if not.
859 public function doAutoblock( $autoblockIP ) {
860 # If autoblocks are disabled, go away.
861 if ( !$this->isAutoblocking() ) {
865 # Don't autoblock for system blocks
866 if ( $this->getSystemBlockType() !== null ) {
867 throw new MWException( 'Cannot autoblock from a system block' );
870 # Check for presence on the autoblock whitelist.
871 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
875 // Avoid PHP 7.1 warning of passing $this by reference
877 # Allow hooks to cancel the autoblock.
878 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
879 wfDebug( "Autoblock aborted by hook.\n" );
883 # It's okay to autoblock. Go ahead and insert/update the block...
885 # Do not add a *new* block if the IP is already blocked.
886 $ipblock = self
::newFromTarget( $autoblockIP );
888 # Check if the block is an autoblock and would exceed the user block
889 # if renewed. If so, do nothing, otherwise prolong the block time...
890 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
891 $this->getExpiry() > self
::getAutoblockExpiry( $ipblock->getTimestamp() )
893 # Reset block timestamp to now and its expiry to
894 # $wgAutoblockExpiry in the future
895 $ipblock->updateTimestamp();
900 # Make a new block object with the desired properties.
901 $autoblock = new Block
;
902 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
903 $autoblock->setTarget( $autoblockIP );
904 $autoblock->setBlocker( $this->getBlocker() );
905 $autoblock->setReason(
906 wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
907 ->inContentLanguage()->plain()
909 $timestamp = wfTimestampNow();
910 $autoblock->setTimestamp( $timestamp );
911 $autoblock->mAuto
= 1;
912 $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
913 # Continue suppressing the name if needed
914 $autoblock->setHideName( $this->getHideName() );
915 $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
916 $autoblock->mParentBlockId
= $this->mId
;
917 $autoblock->isSitewide( $this->isSitewide() );
918 $autoblock->setRestrictions( $this->getRestrictions() );
920 if ( $this->getExpiry() == 'infinity' ) {
921 # Original block was indefinite, start an autoblock now
922 $autoblock->setExpiry( self
::getAutoblockExpiry( $timestamp ) );
924 # If the user is already blocked with an expiry date, we don't
925 # want to pile on top of that.
926 $autoblock->setExpiry( min( $this->getExpiry(), self
::getAutoblockExpiry( $timestamp ) ) );
929 # Insert the block...
930 $status = $autoblock->insert();
937 * Check if a block has expired. Delete it if it is.
940 public function deleteIfExpired() {
941 if ( $this->isExpired() ) {
942 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
946 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
954 * Has the block expired?
957 public function isExpired() {
958 $timestamp = wfTimestampNow();
959 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
961 if ( !$this->getExpiry() ) {
964 return $timestamp > $this->getExpiry();
969 * Is the block address valid (i.e. not a null string?)
971 * @deprecated since 1.33 No longer needed in core.
974 public function isValid() {
975 wfDeprecated( __METHOD__
, '1.33' );
976 return $this->getTarget() != null;
980 * Update the timestamp on autoblocks.
982 public function updateTimestamp() {
983 if ( $this->mAuto
) {
984 $this->setTimestamp( wfTimestamp() );
985 $this->setExpiry( self
::getAutoblockExpiry( $this->getTimestamp() ) );
987 $dbw = wfGetDB( DB_MASTER
);
988 $dbw->update( 'ipblocks',
990 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
991 'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
994 'ipb_id' => $this->getId(),
1002 * Get the IP address at the start of the range in Hex form
1003 * @throws MWException
1004 * @return string IP in Hex form
1006 public function getRangeStart() {
1007 switch ( $this->type
) {
1008 case self
::TYPE_USER
:
1011 return IP
::toHex( $this->target
);
1012 case self
::TYPE_RANGE
:
1013 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
1016 throw new MWException( "Block with invalid type" );
1021 * Get the IP address at the end of the range in Hex form
1022 * @throws MWException
1023 * @return string IP in Hex form
1025 public function getRangeEnd() {
1026 switch ( $this->type
) {
1027 case self
::TYPE_USER
:
1030 return IP
::toHex( $this->target
);
1031 case self
::TYPE_RANGE
:
1032 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
1035 throw new MWException( "Block with invalid type" );
1040 * Get the user id of the blocking sysop
1042 * @return int (0 for foreign users)
1044 public function getBy() {
1045 return $this->getBlocker()->getId();
1049 * Get the username of the blocking sysop
1053 public function getByName() {
1054 return $this->getBlocker()->getName();
1061 public function getId() {
1068 * @param int $blockId
1071 private function setId( $blockId ) {
1072 $this->mId
= (int)$blockId;
1074 if ( is_array( $this->restrictions
) ) {
1075 $this->restrictions
= $this->getBlockRestrictionStore()->setBlockId(
1076 $blockId, $this->restrictions
1084 * Get the reason given for creating the block
1089 public function getReason() {
1090 return $this->mReason
;
1094 * Set the reason for creating the block
1097 * @param string $reason
1099 public function setReason( $reason ) {
1100 $this->mReason
= $reason;
1104 * Get whether the block hides the target's username
1107 * @return bool The block hides the username
1109 public function getHideName() {
1110 return $this->mHideName
;
1114 * Set whether ths block hides the target's username
1117 * @param bool $hideName The block hides the username
1119 public function setHideName( $hideName ) {
1120 $this->mHideName
= $hideName;
1124 * Get the system block type, if any
1126 * @return string|null
1128 public function getSystemBlockType() {
1129 return $this->systemBlockType
;
1133 * Get/set a flag determining whether the master is used for reads
1135 * @param bool|null $x
1138 public function fromMaster( $x = null ) {
1139 return wfSetVar( $this->mFromMaster
, $x );
1143 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1144 * @param bool|null $x
1147 public function isHardblock( $x = null ) {
1148 wfSetVar( $this->isHardblock
, $x );
1150 # You can't *not* hardblock a user
1151 return $this->getType() == self
::TYPE_USER
1153 : $this->isHardblock
;
1157 * @param null|bool $x
1160 public function isAutoblocking( $x = null ) {
1161 wfSetVar( $this->isAutoblocking
, $x );
1163 # You can't put an autoblock on an IP or range as we don't have any history to
1164 # look over to get more IPs from
1165 return $this->getType() == self
::TYPE_USER
1166 ?
$this->isAutoblocking
1171 * Indicates that the block is a sitewide block. This means the user is
1172 * prohibited from editing any page on the site (other than their own talk
1176 * @param null|bool $x
1179 public function isSitewide( $x = null ) {
1180 return wfSetVar( $this->isSitewide
, $x );
1184 * Get or set the flag indicating whether this block blocks the target from
1185 * creating an account. (Note that the flag may be overridden depending on
1189 * @param null|bool $x Value to set (if null, just get the property value)
1190 * @return bool Value of the property
1192 public function isCreateAccountBlocked( $x = null ) {
1193 return wfSetVar( $this->blockCreateAccount
, $x );
1197 * Get or set the flag indicating whether this block blocks the target from
1198 * sending emails. (Note that the flag may be overridden depending on
1202 * @param null|bool $x Value to set (if null, just get the property value)
1203 * @return bool Value of the property
1205 public function isEmailBlocked( $x = null ) {
1206 return wfSetVar( $this->mBlockEmail
, $x );
1210 * Get or set the flag indicating whether this block blocks the target from
1211 * editing their own user talk page. (Note that the flag may be overridden
1212 * depending on global configs.)
1215 * @param null|bool $x Value to set (if null, just get the property value)
1216 * @return bool Value of the property
1218 public function isUsertalkEditAllowed( $x = null ) {
1219 return wfSetVar( $this->allowUsertalk
, $x );
1223 * Determine whether the Block prevents a given right. A right
1224 * may be blacklisted or whitelisted, or determined from a
1225 * property on the Block object. For certain rights, the property
1226 * may be overridden according to global configs.
1229 * @param string $right Right to check
1230 * @return bool|null null if unrecognized right or unset property
1232 public function appliesToRight( $right ) {
1233 $config = RequestContext
::getMain()->getConfig();
1234 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1239 // TODO: fix this case to return proper value
1242 case 'createaccount':
1243 $res = $this->isCreateAccountBlocked();
1246 $res = $this->isEmailBlocked();
1249 // Until T6995 is completed
1250 $res = $this->isSitewide();
1259 if ( !$res && $blockDisablesLogin ) {
1260 // If a block would disable login, then it should
1261 // prevent any right that all users cannot do
1263 $res = $anon->isAllowed( $right ) ?
$res : true;
1270 * Get/set whether the Block prevents a given action
1272 * @deprecated since 1.33, use appliesToRight to determine block
1273 * behaviour, and specific methods to get/set properties
1274 * @param string $action Action to check
1275 * @param bool|null $x Value for set, or null to just get value
1276 * @return bool|null Null for unrecognized rights.
1278 public function prevents( $action, $x = null ) {
1279 $config = RequestContext
::getMain()->getConfig();
1280 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1281 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1284 switch ( $action ) {
1286 # For now... <evil laugh>
1289 case 'createaccount':
1290 $res = wfSetVar( $this->blockCreateAccount
, $x );
1293 $res = wfSetVar( $this->mBlockEmail
, $x );
1296 // Until T6995 is completed
1297 $res = $this->isSitewide();
1299 case 'editownusertalk':
1300 // NOTE: this check is not reliable on partial blocks
1301 // since partially blocked users are always allowed to edit
1302 // their own talk page unless a restriction exists on the
1303 // page or User_talk: namespace
1304 wfSetVar( $this->allowUsertalk
, $x === null ?
null : !$x );
1305 $res = !$this->isUsertalkEditAllowed();
1307 // edit own user talk can be disabled by config
1308 if ( !$blockAllowsUTEdit ) {
1319 if ( !$res && $blockDisablesLogin ) {
1320 // If a block would disable login, then it should
1321 // prevent any action that all users cannot do
1323 $res = $anon->isAllowed( $action ) ?
$res : true;
1330 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1331 * @return string Text is escaped
1333 public function getRedactedName() {
1334 if ( $this->mAuto
) {
1335 return Html
::element(
1337 [ 'class' => 'mw-autoblockid' ],
1338 wfMessage( 'autoblockid', $this->mId
)->text()
1341 return htmlspecialchars( $this->getTarget() );
1346 * Get a timestamp of the expiry for autoblocks
1348 * @param string|int $timestamp
1351 public static function getAutoblockExpiry( $timestamp ) {
1352 global $wgAutoblockExpiry;
1354 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1358 * Purge expired blocks from the ipblocks table
1360 public static function purgeExpired() {
1361 if ( wfReadOnly() ) {
1365 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
1366 wfGetDB( DB_MASTER
),
1368 function ( IDatabase
$dbw, $fname ) {
1369 $ids = $dbw->selectFieldValues( 'ipblocks',
1371 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1375 $blockRestrictionStore = MediaWikiServices
::getInstance()->getBlockRestrictionStore();
1376 $blockRestrictionStore->deleteByBlockId( $ids );
1378 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1385 * Given a target and the target's type, get an existing Block object if possible.
1386 * @param string|User|int $specificTarget A block target, which may be one of several types:
1387 * * A user to block, in which case $target will be a User
1388 * * An IP to block, in which case $target will be a User generated by using
1389 * User::newFromName( $ip, false ) to turn off name validation
1390 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1391 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1393 * Calling this with a user, IP address or range will not select autoblocks, and will
1394 * only select a block where the targets match exactly (so looking for blocks on
1395 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1396 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1397 * affects that target (so for an IP address, get ranges containing that IP; and also
1398 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1399 * @param bool $fromMaster Whether to use the DB_MASTER database
1400 * @return Block|null (null if no relevant block could be found). The target and type
1401 * of the returned Block will refer to the actual block which was found, which might
1402 * not be the same as the target you gave if you used $vagueTarget!
1404 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1405 list( $target, $type ) = self
::parseTarget( $specificTarget );
1406 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1407 return self
::newFromID( $target );
1409 } elseif ( $target === null && $vagueTarget == '' ) {
1410 # We're not going to find anything useful here
1411 # Be aware that the == '' check is explicit, since empty values will be
1412 # passed by some callers (T31116)
1415 } elseif ( in_array(
1417 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1419 $block = new Block();
1420 $block->fromMaster( $fromMaster );
1422 if ( $type !== null ) {
1423 $block->setTarget( $target );
1426 if ( $block->newLoad( $vagueTarget ) ) {
1434 * Get all blocks that match any IP from an array of IP addresses
1436 * @param array $ipChain List of IPs (strings), usually retrieved from the
1437 * X-Forwarded-For header of the request
1438 * @param bool $isAnon Exclude anonymous-only blocks if false
1439 * @param bool $fromMaster Whether to query the master or replica DB
1440 * @return array Array of Blocks
1443 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1444 if ( $ipChain === [] ) {
1449 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1450 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1451 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1452 # necessarily trust the header given to us, make sure that we are only
1453 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1454 # Do not treat private IP spaces as special as it may be desirable for wikis
1455 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1456 if ( !IP
::isValid( $ipaddr ) ) {
1459 # Don't check trusted IPs (includes local squids which will be in every request)
1460 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1463 # Check both the original IP (to check against single blocks), as well as build
1464 # the clause to check for rangeblocks for the given IP.
1465 $conds['ipb_address'][] = $ipaddr;
1466 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1469 if ( $conds === [] ) {
1473 if ( $fromMaster ) {
1474 $db = wfGetDB( DB_MASTER
);
1476 $db = wfGetDB( DB_REPLICA
);
1478 $conds = $db->makeList( $conds, LIST_OR
);
1480 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1482 $blockQuery = self
::getQueryInfo();
1483 $rows = $db->select(
1484 $blockQuery['tables'],
1485 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1489 $blockQuery['joins']
1493 foreach ( $rows as $row ) {
1494 $block = self
::newFromRow( $row );
1495 if ( !$block->isExpired() ) {
1504 * From a list of multiple blocks, find the most exact and strongest Block.
1506 * The logic for finding the "best" block is:
1507 * - Blocks that match the block's target IP are preferred over ones in a range
1508 * - Hardblocks are chosen over softblocks that prevent account creation
1509 * - Softblocks that prevent account creation are chosen over other softblocks
1510 * - Other softblocks are chosen over autoblocks
1511 * - If there are multiple exact or range blocks at the same level, the one chosen
1513 * This should be used when $blocks where retrieved from the user's IP address
1514 * and $ipChain is populated from the same IP address information.
1516 * @param array $blocks Array of Block objects
1517 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1518 * a block is to the server, and if a block matches exactly, or is in a range.
1519 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1521 * @throws MWException
1522 * @return Block|null The "best" block from the list
1524 public static function chooseBlock( array $blocks, array $ipChain ) {
1525 if ( $blocks === [] ) {
1527 } elseif ( count( $blocks ) == 1 ) {
1531 // Sort hard blocks before soft ones and secondarily sort blocks
1532 // that disable account creation before those that don't.
1533 usort( $blocks, function ( Block
$a, Block
$b ) {
1534 $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1535 $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1536 return strcmp( $bWeight, $aWeight ); // highest weight first
1539 $blocksListExact = [
1541 'disable_create' => false,
1545 $blocksListRange = [
1547 'disable_create' => false,
1551 $ipChain = array_reverse( $ipChain );
1553 /** @var Block $block */
1554 foreach ( $blocks as $block ) {
1555 // Stop searching if we have already have a "better" block. This
1556 // is why the order of the blocks matters
1557 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1559 } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1563 foreach ( $ipChain as $checkip ) {
1564 $checkipHex = IP
::toHex( $checkip );
1565 if ( (string)$block->getTarget() === $checkip ) {
1566 if ( $block->isHardblock() ) {
1567 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1568 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1569 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1570 } elseif ( $block->mAuto
) {
1571 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1573 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1575 // We found closest exact match in the ip list, so go to the next Block
1577 } elseif ( array_filter( $blocksListExact ) == []
1578 && $block->getRangeStart() <= $checkipHex
1579 && $block->getRangeEnd() >= $checkipHex
1581 if ( $block->isHardblock() ) {
1582 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1583 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1584 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1585 } elseif ( $block->mAuto
) {
1586 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1588 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1595 if ( array_filter( $blocksListExact ) == [] ) {
1596 $blocksList = &$blocksListRange;
1598 $blocksList = &$blocksListExact;
1601 $chosenBlock = null;
1602 if ( $blocksList['hard'] ) {
1603 $chosenBlock = $blocksList['hard'];
1604 } elseif ( $blocksList['disable_create'] ) {
1605 $chosenBlock = $blocksList['disable_create'];
1606 } elseif ( $blocksList['other'] ) {
1607 $chosenBlock = $blocksList['other'];
1608 } elseif ( $blocksList['auto'] ) {
1609 $chosenBlock = $blocksList['auto'];
1611 throw new MWException( "Proxy block found, but couldn't be classified." );
1614 return $chosenBlock;
1618 * From an existing Block, get the target and the type of target.
1619 * Note that, except for null, it is always safe to treat the target
1620 * as a string; for User objects this will return User::__toString()
1621 * which in turn gives User::getName().
1623 * @param string|int|User|null $target
1624 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1626 public static function parseTarget( $target ) {
1627 # We may have been through this before
1628 if ( $target instanceof User
) {
1629 if ( IP
::isValid( $target->getName() ) ) {
1630 return [ $target, self
::TYPE_IP
];
1632 return [ $target, self
::TYPE_USER
];
1634 } elseif ( $target === null ) {
1635 return [ null, null ];
1638 $target = trim( $target );
1640 if ( IP
::isValid( $target ) ) {
1641 # We can still create a User if it's an IP address, but we need to turn
1642 # off validation checking (which would exclude IP addresses)
1644 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1648 } elseif ( IP
::isValidRange( $target ) ) {
1649 # Can't create a User from an IP range
1650 return [ IP
::sanitizeRange( $target ), self
::TYPE_RANGE
];
1653 # Consider the possibility that this is not a username at all
1654 # but actually an old subpage (T31797)
1655 if ( strpos( $target, '/' ) !== false ) {
1656 # An old subpage, drill down to the user behind it
1657 $target = explode( '/', $target )[0];
1660 $userObj = User
::newFromName( $target );
1661 if ( $userObj instanceof User
) {
1662 # Note that since numbers are valid usernames, a $target of "12345" will be
1663 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1664 # since hash characters are not valid in usernames or titles generally.
1665 return [ $userObj, self
::TYPE_USER
];
1667 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1668 # Autoblock reference in the form "#12345"
1669 return [ substr( $target, 1 ), self
::TYPE_AUTO
];
1673 return [ null, null ];
1678 * Get the type of target for this particular block. Autoblocks have whichever type
1679 * corresponds to their target, so to detect if a block is an autoblock, we have to
1680 * check the mAuto property instead.
1681 * @return int Block::TYPE_ constant, will never be TYPE_ID
1683 public function getType() {
1690 * Get the target and target type for this particular Block. Note that for autoblocks,
1691 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1692 * in this situation.
1693 * @return array [ User|String, Block::TYPE_ constant ]
1694 * @todo FIXME: This should be an integral part of the Block member variables
1696 public function getTargetAndType() {
1697 return [ $this->getTarget(), $this->getType() ];
1701 * Get the target for this particular Block. Note that for autoblocks,
1702 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1703 * in this situation.
1704 * @return User|string
1706 public function getTarget() {
1707 return $this->target
;
1711 * Get the block expiry time
1716 public function getExpiry() {
1717 return $this->mExpiry
;
1721 * Set the block expiry time
1724 * @param string $expiry
1726 public function setExpiry( $expiry ) {
1727 $this->mExpiry
= $expiry;
1731 * Get the timestamp indicating when the block was created
1736 public function getTimestamp() {
1737 return $this->mTimestamp
;
1741 * Set the timestamp indicating when the block was created
1744 * @param string $timestamp
1746 public function setTimestamp( $timestamp ) {
1747 $this->mTimestamp
= $timestamp;
1751 * Set the target for this block, and update $this->type accordingly
1752 * @param mixed $target
1754 public function setTarget( $target ) {
1755 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1759 * Get the user who implemented this block
1760 * @return User User object. May name a foreign user.
1762 public function getBlocker() {
1763 return $this->blocker
;
1767 * Set the user who implemented (or will implement) this block
1768 * @param User|string $user Local User object or username string
1770 public function setBlocker( $user ) {
1771 if ( is_string( $user ) ) {
1772 $user = User
::newFromName( $user, false );
1775 if ( $user->isAnon() && User
::isUsableName( $user->getName() ) ) {
1776 throw new InvalidArgumentException(
1777 'Blocker must be a local user or a name that cannot be a local user'
1781 $this->blocker
= $user;
1785 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1786 * the same as the block's, to a maximum of 24 hours.
1790 * @param WebResponse $response The response on which to set the cookie.
1792 public function setCookie( WebResponse
$response ) {
1793 // Calculate the default expiry time.
1794 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1796 // Use the Block's expiry time only if it's less than the default.
1797 $expiryTime = $this->getExpiry();
1798 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1799 $expiryTime = $maxExpiryTime;
1802 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1803 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1804 $cookieOptions = [ 'httpOnly' => false ];
1805 $cookieValue = $this->getCookieValue();
1806 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1810 * Unset the 'BlockID' cookie.
1814 * @param WebResponse $response The response on which to unset the cookie.
1816 public static function clearCookie( WebResponse
$response ) {
1817 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1821 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1822 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1827 * @return string The block ID, probably concatenated with "!" and the HMAC.
1829 public function getCookieValue() {
1830 $config = RequestContext
::getMain()->getConfig();
1831 $id = $this->getId();
1832 $secretKey = $config->get( 'SecretKey' );
1833 if ( !$secretKey ) {
1834 // If there's no secret key, don't append a HMAC.
1837 $hmac = MWCryptHash
::hmac( $id, $secretKey, false );
1838 $cookieValue = $id . '!' . $hmac;
1839 return $cookieValue;
1843 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1844 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1848 * @param string $cookieValue The string in which to find the ID.
1850 * @return int|null The block ID, or null if the HMAC is present and invalid.
1852 public static function getIdFromCookieValue( $cookieValue ) {
1853 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1854 $bangPos = strpos( $cookieValue, '!' );
1855 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
1856 // Get the site-wide secret key.
1857 $config = RequestContext
::getMain()->getConfig();
1858 $secretKey = $config->get( 'SecretKey' );
1859 if ( !$secretKey ) {
1860 // If there's no secret key, just use the ID as given.
1863 $storedHmac = substr( $cookieValue, $bangPos +
1 );
1864 $calculatedHmac = MWCryptHash
::hmac( $id, $secretKey, false );
1865 if ( $calculatedHmac === $storedHmac ) {
1873 * Get the key and parameters for the corresponding error message.
1876 * @param IContextSource $context
1879 public function getPermissionsError( IContextSource
$context ) {
1880 $params = $this->getBlockErrorParams( $context );
1882 $msg = 'blockedtext';
1883 if ( $this->getSystemBlockType() !== null ) {
1884 $msg = 'systemblockedtext';
1885 } elseif ( $this->mAuto
) {
1886 $msg = 'autoblockedtext';
1887 } elseif ( !$this->isSitewide() ) {
1888 $msg = 'blockedtext-partial';
1891 array_unshift( $params, $msg );
1897 * Get block information used in different block error messages
1900 * @param IContextSource $context
1903 public function getBlockErrorParams( IContextSource
$context ) {
1904 $blocker = $this->getBlocker();
1905 if ( $blocker instanceof User
) { // local user
1906 $blockerUserpage = $blocker->getUserPage();
1907 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1908 } else { // foreign user
1912 $reason = $this->getReason();
1913 if ( $reason == '' ) {
1914 $reason = $context->msg( 'blockednoreason' )->text();
1917 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1918 * This could be a username, an IP range, or a single IP. */
1919 $intended = $this->getTarget();
1920 $systemBlockType = $this->getSystemBlockType();
1921 $lang = $context->getLanguage();
1926 $context->getRequest()->getIP(),
1928 $systemBlockType ??
$this->getId(),
1929 $lang->formatExpiry( $this->getExpiry() ),
1931 $lang->userTimeAndDate( $this->getTimestamp(), $context->getUser() ),
1938 * Getting the restrictions will perform a database query if the restrictions
1939 * are not already loaded.
1942 * @return Restriction[]
1944 public function getRestrictions() {
1945 if ( $this->restrictions
=== null ) {
1946 // If the block id has not been set, then do not attempt to load the
1948 if ( !$this->mId
) {
1951 $this->restrictions
= $this->getBlockRestrictionStore()->loadByBlockId( $this->mId
);
1954 return $this->restrictions
;
1961 * @param Restriction[] $restrictions
1964 public function setRestrictions( array $restrictions ) {
1965 $this->restrictions
= array_filter( $restrictions, function ( $restriction ) {
1966 return $restriction instanceof Restriction
;
1973 * Determine whether the block allows the user to edit their own
1974 * user talk page. This is done separately from Block::appliesToRight
1975 * because there is no right for editing one's own user talk page
1976 * and because the user's talk page needs to be passed into the
1977 * Block object, which is unaware of the user.
1979 * The ipb_allow_usertalk flag (which corresponds to the property
1980 * allowUsertalk) is used on sitewide blocks and partial blocks
1981 * that contain a namespace restriction on the user talk namespace,
1982 * but do not contain a page restriction on the user's talk page.
1983 * For all other (i.e. most) partial blocks, the flag is ignored,
1984 * and the user can always edit their user talk page unless there
1985 * is a page restriction on their user talk page, in which case
1986 * they can never edit it. (Ideally the flag would be stored as
1987 * null in these cases, but the database field isn't nullable.)
1989 * This method does not validate that the passed in talk page belongs to the
1990 * block target since the target (an IP) might not be the same as the user's
1991 * talk page (if they are logged in).
1994 * @param Title|null $usertalk The user's user talk page. If null,
1995 * and if the target is a User, the target's userpage is used
1996 * @return bool The user can edit their talk page
1998 public function appliesToUsertalk( Title
$usertalk = null ) {
2000 if ( $this->target
instanceof User
) {
2001 $usertalk = $this->target
->getTalkPage();
2003 throw new InvalidArgumentException(
2004 '$usertalk must be provided if block target is not a user/IP'
2009 if ( $usertalk->getNamespace() !== NS_USER_TALK
) {
2010 throw new InvalidArgumentException(
2011 '$usertalk must be a user talk page'
2015 if ( !$this->isSitewide() ) {
2016 if ( $this->appliesToPage( $usertalk->getArticleID() ) ) {
2019 if ( !$this->appliesToNamespace( NS_USER_TALK
) ) {
2024 // This is a type of block which uses the ipb_allow_usertalk
2025 // flag. The flag can still be overridden by global configs.
2026 $config = RequestContext
::getMain()->getConfig();
2027 if ( !$config->get( 'BlockAllowsUTEdit' ) ) {
2030 return !$this->isUsertalkEditAllowed();
2034 * Checks if a block applies to a particular title
2036 * This check does not consider whether `$this->isUsertalkEditAllowed`
2037 * returns false, as the identity of the user making the hypothetical edit
2038 * isn't known here (particularly in the case of IP hardblocks, range
2039 * blocks, and auto-blocks).
2041 * @param Title $title
2044 public function appliesToTitle( Title
$title ) {
2045 if ( $this->isSitewide() ) {
2049 $restrictions = $this->getRestrictions();
2050 foreach ( $restrictions as $restriction ) {
2051 if ( $restriction->matches( $title ) ) {
2060 * Checks if a block applies to a particular namespace
2067 public function appliesToNamespace( $ns ) {
2068 if ( $this->isSitewide() ) {
2072 // Blocks do not apply to virtual namespaces.
2077 $restriction = $this->findRestriction( NamespaceRestriction
::TYPE
, $ns );
2079 return (bool)$restriction;
2083 * Checks if a block applies to a particular page
2085 * This check does not consider whether `$this->isUsertalkEditAllowed`
2086 * returns false, as the identity of the user making the hypothetical edit
2087 * isn't known here (particularly in the case of IP hardblocks, range
2088 * blocks, and auto-blocks).
2092 * @param int $pageId
2095 public function appliesToPage( $pageId ) {
2096 if ( $this->isSitewide() ) {
2100 // If the pageId is not over zero, the block cannot apply to it.
2101 if ( $pageId <= 0 ) {
2105 $restriction = $this->findRestriction( PageRestriction
::TYPE
, $pageId );
2107 return (bool)$restriction;
2111 * Find Restriction by type and value.
2113 * @param string $type
2115 * @return Restriction|null
2117 private function findRestriction( $type, $value ) {
2118 $restrictions = $this->getRestrictions();
2119 foreach ( $restrictions as $restriction ) {
2120 if ( $restriction->getType() !== $type ) {
2124 if ( $restriction->getValue() === $value ) {
2125 return $restriction;
2133 * Check if the block should be tracked with a cookie.
2136 * @param bool $isAnon The user is logged out
2137 * @return bool The block should be tracked with a cookie
2139 public function shouldTrackWithCookie( $isAnon ) {
2140 $config = RequestContext
::getMain()->getConfig();
2141 switch ( $this->getType() ) {
2143 case self
::TYPE_RANGE
:
2144 return $isAnon && $config->get( 'CookieSetOnIpBlock' );
2145 case self
::TYPE_USER
:
2146 return !$isAnon && $config->get( 'CookieSetOnAutoblock' ) && $this->isAutoblocking();
2153 * Check if the block prevents a user from resetting their password
2156 * @return bool The block blocks password reset
2158 public function appliesToPasswordReset() {
2159 switch ( $this->getSystemBlockType() ) {
2161 case 'global-block':
2162 return $this->isCreateAccountBlocked();
2166 case 'wgSoftBlockRanges':
2174 * Get a BlockRestrictionStore instance
2176 * @return BlockRestrictionStore
2178 private function getBlockRestrictionStore() : BlockRestrictionStore
{
2179 return MediaWikiServices
::getInstance()->getBlockRestrictionStore();