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 wfDeprecated( __METHOD__
, '1.31' );
218 'ipb_create_account',
219 'ipb_enable_autoblock',
223 'ipb_allow_usertalk',
224 'ipb_parent_block_id',
225 ] + CommentStore
::newKey( 'ipb_reason' )->getFields();
229 * Return the tables, fields, and join conditions to be selected to create
230 * a new block object.
232 * @return array With three keys:
233 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
234 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
235 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
237 public static function getQueryInfo() {
238 $commentQuery = CommentStore
::newKey( 'ipb_reason' )->getJoin();
240 'tables' => [ 'ipblocks' ] +
$commentQuery['tables'],
249 'ipb_create_account',
250 'ipb_enable_autoblock',
254 'ipb_allow_usertalk',
255 'ipb_parent_block_id',
256 ] +
$commentQuery['fields'],
257 'joins' => $commentQuery['joins'],
262 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
263 * the blocking user or the block timestamp, only things which affect the blocked user
265 * @param Block $block
269 public function equals( Block
$block ) {
271 (string)$this->target
== (string)$block->target
272 && $this->type
== $block->type
273 && $this->mAuto
== $block->mAuto
274 && $this->isHardblock() == $block->isHardblock()
275 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
276 && $this->mExpiry
== $block->mExpiry
277 && $this->isAutoblocking() == $block->isAutoblocking()
278 && $this->mHideName
== $block->mHideName
279 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
280 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
281 && $this->mReason
== $block->mReason
286 * Load a block from the database which affects the already-set $this->target:
287 * 1) A block directly on the given user or IP
288 * 2) A rangeblock encompassing the given IP (smallest first)
289 * 3) An autoblock on the given IP
290 * @param User|string $vagueTarget Also search for blocks affecting this target. Doesn't
291 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
292 * @throws MWException
293 * @return bool Whether a relevant block was found
295 protected function newLoad( $vagueTarget = null ) {
296 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_REPLICA
);
298 if ( $this->type
!== null ) {
300 'ipb_address' => [ (string)$this->target
],
303 $conds = [ 'ipb_address' => [] ];
306 # Be aware that the != '' check is explicit, since empty values will be
307 # passed by some callers (T31116)
308 if ( $vagueTarget != '' ) {
309 list( $target, $type ) = self
::parseTarget( $vagueTarget );
311 case self
::TYPE_USER
:
312 # Slightly weird, but who are we to argue?
313 $conds['ipb_address'][] = (string)$target;
317 $conds['ipb_address'][] = (string)$target;
318 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
319 $conds = $db->makeList( $conds, LIST_OR
);
322 case self
::TYPE_RANGE
:
323 list( $start, $end ) = IP
::parseRange( $target );
324 $conds['ipb_address'][] = (string)$target;
325 $conds[] = self
::getRangeCond( $start, $end );
326 $conds = $db->makeList( $conds, LIST_OR
);
330 throw new MWException( "Tried to load block with invalid type" );
334 $blockQuery = self
::getQueryInfo();
336 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__
, [], $blockQuery['joins']
339 # This result could contain a block on the user, a block on the IP, and a russian-doll
340 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
343 # Lower will be better
344 $bestBlockScore = 100;
346 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
347 $bestBlockPreventsEdit = null;
349 foreach ( $res as $row ) {
350 $block = self
::newFromRow( $row );
352 # Don't use expired blocks
353 if ( $block->isExpired() ) {
357 # Don't use anon only blocks on users
358 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
362 if ( $block->getType() == self
::TYPE_RANGE
) {
363 # This is the number of bits that are allowed to vary in the block, give
364 # or take some floating point errors
365 $end = Wikimedia\base_convert
( $block->getRangeEnd(), 16, 10 );
366 $start = Wikimedia\base_convert
( $block->getRangeStart(), 16, 10 );
367 $size = log( $end - $start +
1, 2 );
369 # This has the nice property that a /32 block is ranked equally with a
370 # single-IP block, which is exactly what it is...
371 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
374 $score = $block->getType();
377 if ( $score < $bestBlockScore ) {
378 $bestBlockScore = $score;
380 $bestBlockPreventsEdit = $block->prevents( 'edit' );
384 if ( $bestRow !== null ) {
385 $this->initFromRow( $bestRow );
386 $this->prevents( 'edit', $bestBlockPreventsEdit );
394 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
395 * @param string $start Hexadecimal IP representation
396 * @param string $end Hexadecimal IP representation, or null to use $start = $end
399 public static function getRangeCond( $start, $end = null ) {
400 if ( $end === null ) {
403 # Per T16634, we want to include relevant active rangeblocks; for
404 # rangeblocks, we want to include larger ranges which enclose the given
405 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
406 # so we can improve performance by filtering on a LIKE clause
407 $chunk = self
::getIpFragment( $start );
408 $dbr = wfGetDB( DB_REPLICA
);
409 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
411 # Fairly hard to make a malicious SQL statement out of hex characters,
412 # but stranger things have happened...
413 $safeStart = $dbr->addQuotes( $start );
414 $safeEnd = $dbr->addQuotes( $end );
416 return $dbr->makeList(
418 "ipb_range_start $like",
419 "ipb_range_start <= $safeStart",
420 "ipb_range_end >= $safeEnd",
427 * Get the component of an IP address which is certain to be the same between an IP
428 * address and a rangeblock containing that IP address.
429 * @param string $hex Hexadecimal IP representation
432 protected static function getIpFragment( $hex ) {
433 global $wgBlockCIDRLimit;
434 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
435 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
437 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
442 * Given a database row from the ipblocks table, initialize
444 * @param stdClass $row A row from the ipblocks table
446 protected function initFromRow( $row ) {
447 $this->setTarget( $row->ipb_address
);
448 if ( $row->ipb_by
) { // local user
449 $this->setBlocker( User
::newFromId( $row->ipb_by
) );
450 } else { // foreign user
451 $this->setBlocker( $row->ipb_by_text
);
454 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
455 $this->mAuto
= $row->ipb_auto
;
456 $this->mHideName
= $row->ipb_deleted
;
457 $this->mId
= (int)$row->ipb_id
;
458 $this->mParentBlockId
= $row->ipb_parent_block_id
;
460 // I wish I didn't have to do this
461 $db = wfGetDB( DB_REPLICA
);
462 $this->mExpiry
= $db->decodeExpiry( $row->ipb_expiry
);
463 $this->mReason
= CommentStore
::newKey( 'ipb_reason' )
464 // Legacy because $row may have come from self::selectFields()
465 ->getCommentLegacy( $db, $row )->text
;
467 $this->isHardblock( !$row->ipb_anon_only
);
468 $this->isAutoblocking( $row->ipb_enable_autoblock
);
470 $this->prevents( 'createaccount', $row->ipb_create_account
);
471 $this->prevents( 'sendemail', $row->ipb_block_email
);
472 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
476 * Create a new Block object from a database row
477 * @param stdClass $row Row from the ipblocks table
480 public static function newFromRow( $row ) {
482 $block->initFromRow( $row );
487 * Delete the row from the IP blocks table.
489 * @throws MWException
492 public function delete() {
493 if ( wfReadOnly() ) {
497 if ( !$this->getId() ) {
498 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
501 $dbw = wfGetDB( DB_MASTER
);
502 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
503 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
505 return $dbw->affectedRows() > 0;
509 * Insert a block into the block table. Will fail if there is a conflicting
510 * block (same name and options) already in the database.
512 * @param IDatabase $dbw If you have one available
513 * @return bool|array False on failure, assoc array on success:
514 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
516 public function insert( $dbw = null ) {
517 global $wgBlockDisablesLogin;
519 if ( $this->getSystemBlockType() !== null ) {
520 throw new MWException( 'Cannot insert a system block into the database' );
523 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
525 if ( $dbw === null ) {
526 $dbw = wfGetDB( DB_MASTER
);
529 # Periodic purge via commit hooks
530 if ( mt_rand( 0, 9 ) == 0 ) {
531 self
::purgeExpired();
534 $row = $this->getDatabaseArray( $dbw );
536 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
537 $affected = $dbw->affectedRows();
538 $this->mId
= $dbw->insertId();
540 # Don't collide with expired blocks.
541 # Do this after trying to insert to avoid locking.
543 # T96428: The ipb_address index uses a prefix on a field, so
544 # use a standard SELECT + DELETE to avoid annoying gap locks.
545 $ids = $dbw->selectFieldValues( 'ipblocks',
548 'ipb_address' => $row['ipb_address'],
549 'ipb_user' => $row['ipb_user'],
550 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
555 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
556 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
557 $affected = $dbw->affectedRows();
558 $this->mId
= $dbw->insertId();
563 $auto_ipd_ids = $this->doRetroactiveAutoblock();
565 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
566 // Change user login token to force them to be logged out.
567 $this->target
->setToken();
568 $this->target
->saveSettings();
571 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
578 * Update a block in the DB with new parameters.
579 * The ID field needs to be loaded first.
581 * @return bool|array False on failure, array on success:
582 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
584 public function update() {
585 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
586 $dbw = wfGetDB( DB_MASTER
);
588 $dbw->startAtomic( __METHOD__
);
592 $this->getDatabaseArray( $dbw ),
593 [ 'ipb_id' => $this->getId() ],
597 $affected = $dbw->affectedRows();
599 if ( $this->isAutoblocking() ) {
600 // update corresponding autoblock(s) (T50813)
603 $this->getAutoblockUpdateArray( $dbw ),
604 [ 'ipb_parent_block_id' => $this->getId() ],
608 // autoblock no longer required, delete corresponding autoblock(s)
611 [ 'ipb_parent_block_id' => $this->getId() ],
616 $dbw->endAtomic( __METHOD__
);
619 $auto_ipd_ids = $this->doRetroactiveAutoblock();
620 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
627 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
628 * @param IDatabase $dbw
631 protected function getDatabaseArray( IDatabase
$dbw ) {
632 $expiry = $dbw->encodeExpiry( $this->mExpiry
);
634 if ( $this->forcedTargetID
) {
635 $uid = $this->forcedTargetID
;
637 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
641 'ipb_address' => (string)$this->target
,
643 'ipb_by' => $this->getBy(),
644 'ipb_by_text' => $this->getByName(),
645 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
646 'ipb_auto' => $this->mAuto
,
647 'ipb_anon_only' => !$this->isHardblock(),
648 'ipb_create_account' => $this->prevents( 'createaccount' ),
649 'ipb_enable_autoblock' => $this->isAutoblocking(),
650 'ipb_expiry' => $expiry,
651 'ipb_range_start' => $this->getRangeStart(),
652 'ipb_range_end' => $this->getRangeEnd(),
653 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
654 'ipb_block_email' => $this->prevents( 'sendemail' ),
655 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
656 'ipb_parent_block_id' => $this->mParentBlockId
657 ] + CommentStore
::newKey( 'ipb_reason' )->insert( $dbw, $this->mReason
);
663 * @param IDatabase $dbw
666 protected function getAutoblockUpdateArray( IDatabase
$dbw ) {
668 'ipb_by' => $this->getBy(),
669 'ipb_by_text' => $this->getByName(),
670 'ipb_create_account' => $this->prevents( 'createaccount' ),
671 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
672 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
673 ] + CommentStore
::newKey( 'ipb_reason' )->insert( $dbw, $this->mReason
);
677 * Retroactively autoblocks the last IP used by the user (if it is a user)
678 * blocked by this Block.
680 * @return array Block IDs of retroactive autoblocks made
682 protected function doRetroactiveAutoblock() {
684 # If autoblock is enabled, autoblock the LAST IP(s) used
685 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
686 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
688 $continue = Hooks
::run(
689 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
692 self
::defaultRetroactiveAutoblock( $this, $blockIds );
699 * Retroactively autoblocks the last IP used by the user (if it is a user)
700 * blocked by this Block. This will use the recentchanges table.
702 * @param Block $block
703 * @param array &$blockIds
705 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
708 // No IPs are in recentchanges table, so nothing to select
709 if ( !$wgPutIPinRC ) {
713 $dbr = wfGetDB( DB_REPLICA
);
715 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
716 $conds = [ 'rc_user_text' => (string)$block->getTarget() ];
718 // Just the last IP used.
719 $options['LIMIT'] = 1;
721 $res = $dbr->select( 'recentchanges', [ 'rc_ip' ], $conds,
722 __METHOD__
, $options );
724 if ( !$res->numRows() ) {
725 # No results, don't autoblock anything
726 wfDebug( "No IP found to retroactively autoblock\n" );
728 foreach ( $res as $row ) {
730 $id = $block->doAutoblock( $row->rc_ip
);
740 * Checks whether a given IP is on the autoblock whitelist.
741 * TODO: this probably belongs somewhere else, but not sure where...
743 * @param string $ip The IP to check
746 public static function isWhitelistedFromAutoblocks( $ip ) {
747 // Try to get the autoblock_whitelist from the cache, as it's faster
748 // than getting the msg raw and explode()'ing it.
749 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
750 $lines = $cache->getWithSetCallback(
751 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
753 function ( $curValue, &$ttl, array &$setOpts ) {
754 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
756 return explode( "\n",
757 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
761 wfDebug( "Checking the autoblock whitelist..\n" );
763 foreach ( $lines as $line ) {
765 if ( substr( $line, 0, 1 ) !== '*' ) {
769 $wlEntry = substr( $line, 1 );
770 $wlEntry = trim( $wlEntry );
772 wfDebug( "Checking $ip against $wlEntry..." );
774 # Is the IP in this range?
775 if ( IP
::isInRange( $ip, $wlEntry ) ) {
776 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
779 wfDebug( " No match\n" );
787 * Autoblocks the given IP, referring to this Block.
789 * @param string $autoblockIP The IP to autoblock.
790 * @return int|bool Block ID if an autoblock was inserted, false if not.
792 public function doAutoblock( $autoblockIP ) {
793 # If autoblocks are disabled, go away.
794 if ( !$this->isAutoblocking() ) {
798 # Don't autoblock for system blocks
799 if ( $this->getSystemBlockType() !== null ) {
800 throw new MWException( 'Cannot autoblock from a system block' );
803 # Check for presence on the autoblock whitelist.
804 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
808 // Avoid PHP 7.1 warning of passing $this by reference
810 # Allow hooks to cancel the autoblock.
811 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
812 wfDebug( "Autoblock aborted by hook.\n" );
816 # It's okay to autoblock. Go ahead and insert/update the block...
818 # Do not add a *new* block if the IP is already blocked.
819 $ipblock = self
::newFromTarget( $autoblockIP );
821 # Check if the block is an autoblock and would exceed the user block
822 # if renewed. If so, do nothing, otherwise prolong the block time...
823 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
824 $this->mExpiry
> self
::getAutoblockExpiry( $ipblock->mTimestamp
)
826 # Reset block timestamp to now and its expiry to
827 # $wgAutoblockExpiry in the future
828 $ipblock->updateTimestamp();
833 # Make a new block object with the desired properties.
834 $autoblock = new Block
;
835 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
836 $autoblock->setTarget( $autoblockIP );
837 $autoblock->setBlocker( $this->getBlocker() );
838 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
839 ->inContentLanguage()->plain();
840 $timestamp = wfTimestampNow();
841 $autoblock->mTimestamp
= $timestamp;
842 $autoblock->mAuto
= 1;
843 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
844 # Continue suppressing the name if needed
845 $autoblock->mHideName
= $this->mHideName
;
846 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
847 $autoblock->mParentBlockId
= $this->mId
;
849 if ( $this->mExpiry
== 'infinity' ) {
850 # Original block was indefinite, start an autoblock now
851 $autoblock->mExpiry
= self
::getAutoblockExpiry( $timestamp );
853 # If the user is already blocked with an expiry date, we don't
854 # want to pile on top of that.
855 $autoblock->mExpiry
= min( $this->mExpiry
, self
::getAutoblockExpiry( $timestamp ) );
858 # Insert the block...
859 $status = $autoblock->insert();
866 * Check if a block has expired. Delete it if it is.
869 public function deleteIfExpired() {
870 if ( $this->isExpired() ) {
871 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
875 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
883 * Has the block expired?
886 public function isExpired() {
887 $timestamp = wfTimestampNow();
888 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
890 if ( !$this->mExpiry
) {
893 return $timestamp > $this->mExpiry
;
898 * Is the block address valid (i.e. not a null string?)
901 public function isValid() {
902 return $this->getTarget() != null;
906 * Update the timestamp on autoblocks.
908 public function updateTimestamp() {
909 if ( $this->mAuto
) {
910 $this->mTimestamp
= wfTimestamp();
911 $this->mExpiry
= self
::getAutoblockExpiry( $this->mTimestamp
);
913 $dbw = wfGetDB( DB_MASTER
);
914 $dbw->update( 'ipblocks',
916 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
917 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
920 'ipb_id' => $this->getId(),
928 * Get the IP address at the start of the range in Hex form
929 * @throws MWException
930 * @return string IP in Hex form
932 public function getRangeStart() {
933 switch ( $this->type
) {
934 case self
::TYPE_USER
:
937 return IP
::toHex( $this->target
);
938 case self
::TYPE_RANGE
:
939 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
942 throw new MWException( "Block with invalid type" );
947 * Get the IP address at the end of the range in Hex form
948 * @throws MWException
949 * @return string IP in Hex form
951 public function getRangeEnd() {
952 switch ( $this->type
) {
953 case self
::TYPE_USER
:
956 return IP
::toHex( $this->target
);
957 case self
::TYPE_RANGE
:
958 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
961 throw new MWException( "Block with invalid type" );
966 * Get the user id of the blocking sysop
968 * @return int (0 for foreign users)
970 public function getBy() {
971 $blocker = $this->getBlocker();
972 return ( $blocker instanceof User
)
978 * Get the username of the blocking sysop
982 public function getByName() {
983 $blocker = $this->getBlocker();
984 return ( $blocker instanceof User
)
985 ?
$blocker->getName()
986 : (string)$blocker; // username
993 public function getId() {
998 * Get the system block type, if any
1000 * @return string|null
1002 public function getSystemBlockType() {
1003 return $this->systemBlockType
;
1007 * Get/set a flag determining whether the master is used for reads
1009 * @param bool|null $x
1012 public function fromMaster( $x = null ) {
1013 return wfSetVar( $this->mFromMaster
, $x );
1017 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1018 * @param bool|null $x
1021 public function isHardblock( $x = null ) {
1022 wfSetVar( $this->isHardblock
, $x );
1024 # You can't *not* hardblock a user
1025 return $this->getType() == self
::TYPE_USER
1027 : $this->isHardblock
;
1031 * @param null|bool $x
1034 public function isAutoblocking( $x = null ) {
1035 wfSetVar( $this->isAutoblocking
, $x );
1037 # You can't put an autoblock on an IP or range as we don't have any history to
1038 # look over to get more IPs from
1039 return $this->getType() == self
::TYPE_USER
1040 ?
$this->isAutoblocking
1045 * Get/set whether the Block prevents a given action
1047 * @param string $action Action to check
1048 * @param bool|null $x Value for set, or null to just get value
1049 * @return bool|null Null for unrecognized rights.
1051 public function prevents( $action, $x = null ) {
1052 global $wgBlockDisablesLogin;
1054 switch ( $action ) {
1056 # For now... <evil laugh>
1059 case 'createaccount':
1060 $res = wfSetVar( $this->mCreateAccount
, $x );
1063 $res = wfSetVar( $this->mBlockEmail
, $x );
1065 case 'editownusertalk':
1066 $res = wfSetVar( $this->mDisableUsertalk
, $x );
1072 if ( !$res && $wgBlockDisablesLogin ) {
1073 // If a block would disable login, then it should
1074 // prevent any action that all users cannot do
1076 $res = $anon->isAllowed( $action ) ?
$res : true;
1083 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1084 * @return string Text is escaped
1086 public function getRedactedName() {
1087 if ( $this->mAuto
) {
1088 return Html
::rawElement(
1090 [ 'class' => 'mw-autoblockid' ],
1091 wfMessage( 'autoblockid', $this->mId
)
1094 return htmlspecialchars( $this->getTarget() );
1099 * Get a timestamp of the expiry for autoblocks
1101 * @param string|int $timestamp
1104 public static function getAutoblockExpiry( $timestamp ) {
1105 global $wgAutoblockExpiry;
1107 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1111 * Purge expired blocks from the ipblocks table
1113 public static function purgeExpired() {
1114 if ( wfReadOnly() ) {
1118 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
1119 wfGetDB( DB_MASTER
),
1121 function ( IDatabase
$dbw, $fname ) {
1124 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1132 * Given a target and the target's type, get an existing Block object if possible.
1133 * @param string|User|int $specificTarget A block target, which may be one of several types:
1134 * * A user to block, in which case $target will be a User
1135 * * An IP to block, in which case $target will be a User generated by using
1136 * User::newFromName( $ip, false ) to turn off name validation
1137 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1138 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1140 * Calling this with a user, IP address or range will not select autoblocks, and will
1141 * only select a block where the targets match exactly (so looking for blocks on
1142 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1143 * @param string|User|int $vagueTarget As above, but we will search for *any* block which
1144 * affects that target (so for an IP address, get ranges containing that IP; and also
1145 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1146 * @param bool $fromMaster Whether to use the DB_MASTER database
1147 * @return Block|null (null if no relevant block could be found). The target and type
1148 * of the returned Block will refer to the actual block which was found, which might
1149 * not be the same as the target you gave if you used $vagueTarget!
1151 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1152 list( $target, $type ) = self
::parseTarget( $specificTarget );
1153 if ( $type == self
::TYPE_ID ||
$type == self
::TYPE_AUTO
) {
1154 return self
::newFromID( $target );
1156 } elseif ( $target === null && $vagueTarget == '' ) {
1157 # We're not going to find anything useful here
1158 # Be aware that the == '' check is explicit, since empty values will be
1159 # passed by some callers (T31116)
1162 } elseif ( in_array(
1164 [ self
::TYPE_USER
, self
::TYPE_IP
, self
::TYPE_RANGE
, null ] )
1166 $block = new Block();
1167 $block->fromMaster( $fromMaster );
1169 if ( $type !== null ) {
1170 $block->setTarget( $target );
1173 if ( $block->newLoad( $vagueTarget ) ) {
1181 * Get all blocks that match any IP from an array of IP addresses
1183 * @param array $ipChain List of IPs (strings), usually retrieved from the
1184 * X-Forwarded-For header of the request
1185 * @param bool $isAnon Exclude anonymous-only blocks if false
1186 * @param bool $fromMaster Whether to query the master or replica DB
1187 * @return array Array of Blocks
1190 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1191 if ( !count( $ipChain ) ) {
1196 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1197 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1198 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1199 # necessarily trust the header given to us, make sure that we are only
1200 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1201 # Do not treat private IP spaces as special as it may be desirable for wikis
1202 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1203 if ( !IP
::isValid( $ipaddr ) ) {
1206 # Don't check trusted IPs (includes local squids which will be in every request)
1207 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1210 # Check both the original IP (to check against single blocks), as well as build
1211 # the clause to check for rangeblocks for the given IP.
1212 $conds['ipb_address'][] = $ipaddr;
1213 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1216 if ( !count( $conds ) ) {
1220 if ( $fromMaster ) {
1221 $db = wfGetDB( DB_MASTER
);
1223 $db = wfGetDB( DB_REPLICA
);
1225 $conds = $db->makeList( $conds, LIST_OR
);
1227 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1229 $blockQuery = self
::getQueryInfo();
1230 $rows = $db->select(
1231 $blockQuery['tables'],
1232 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1236 $blockQuery['joins']
1240 foreach ( $rows as $row ) {
1241 $block = self
::newFromRow( $row );
1242 if ( !$block->isExpired() ) {
1251 * From a list of multiple blocks, find the most exact and strongest Block.
1253 * The logic for finding the "best" block is:
1254 * - Blocks that match the block's target IP are preferred over ones in a range
1255 * - Hardblocks are chosen over softblocks that prevent account creation
1256 * - Softblocks that prevent account creation are chosen over other softblocks
1257 * - Other softblocks are chosen over autoblocks
1258 * - If there are multiple exact or range blocks at the same level, the one chosen
1260 * This should be used when $blocks where retrieved from the user's IP address
1261 * and $ipChain is populated from the same IP address information.
1263 * @param array $blocks Array of Block objects
1264 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1265 * a block is to the server, and if a block matches exactly, or is in a range.
1266 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1268 * @throws MWException
1269 * @return Block|null The "best" block from the list
1271 public static function chooseBlock( array $blocks, array $ipChain ) {
1272 if ( !count( $blocks ) ) {
1274 } elseif ( count( $blocks ) == 1 ) {
1278 // Sort hard blocks before soft ones and secondarily sort blocks
1279 // that disable account creation before those that don't.
1280 usort( $blocks, function ( Block
$a, Block
$b ) {
1281 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1282 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1283 return strcmp( $bWeight, $aWeight ); // highest weight first
1286 $blocksListExact = [
1288 'disable_create' => false,
1292 $blocksListRange = [
1294 'disable_create' => false,
1298 $ipChain = array_reverse( $ipChain );
1300 /** @var Block $block */
1301 foreach ( $blocks as $block ) {
1302 // Stop searching if we have already have a "better" block. This
1303 // is why the order of the blocks matters
1304 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1306 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1310 foreach ( $ipChain as $checkip ) {
1311 $checkipHex = IP
::toHex( $checkip );
1312 if ( (string)$block->getTarget() === $checkip ) {
1313 if ( $block->isHardblock() ) {
1314 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1315 } elseif ( $block->prevents( 'createaccount' ) ) {
1316 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1317 } elseif ( $block->mAuto
) {
1318 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1320 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1322 // We found closest exact match in the ip list, so go to the next Block
1324 } elseif ( array_filter( $blocksListExact ) == []
1325 && $block->getRangeStart() <= $checkipHex
1326 && $block->getRangeEnd() >= $checkipHex
1328 if ( $block->isHardblock() ) {
1329 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1330 } elseif ( $block->prevents( 'createaccount' ) ) {
1331 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1332 } elseif ( $block->mAuto
) {
1333 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1335 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1342 if ( array_filter( $blocksListExact ) == [] ) {
1343 $blocksList = &$blocksListRange;
1345 $blocksList = &$blocksListExact;
1348 $chosenBlock = null;
1349 if ( $blocksList['hard'] ) {
1350 $chosenBlock = $blocksList['hard'];
1351 } elseif ( $blocksList['disable_create'] ) {
1352 $chosenBlock = $blocksList['disable_create'];
1353 } elseif ( $blocksList['other'] ) {
1354 $chosenBlock = $blocksList['other'];
1355 } elseif ( $blocksList['auto'] ) {
1356 $chosenBlock = $blocksList['auto'];
1358 throw new MWException( "Proxy block found, but couldn't be classified." );
1361 return $chosenBlock;
1365 * From an existing Block, get the target and the type of target.
1366 * Note that, except for null, it is always safe to treat the target
1367 * as a string; for User objects this will return User::__toString()
1368 * which in turn gives User::getName().
1370 * @param string|int|User|null $target
1371 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1373 public static function parseTarget( $target ) {
1374 # We may have been through this before
1375 if ( $target instanceof User
) {
1376 if ( IP
::isValid( $target->getName() ) ) {
1377 return [ $target, self
::TYPE_IP
];
1379 return [ $target, self
::TYPE_USER
];
1381 } elseif ( $target === null ) {
1382 return [ null, null ];
1385 $target = trim( $target );
1387 if ( IP
::isValid( $target ) ) {
1388 # We can still create a User if it's an IP address, but we need to turn
1389 # off validation checking (which would exclude IP addresses)
1391 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1395 } elseif ( IP
::isValidRange( $target ) ) {
1396 # Can't create a User from an IP range
1397 return [ IP
::sanitizeRange( $target ), self
::TYPE_RANGE
];
1400 # Consider the possibility that this is not a username at all
1401 # but actually an old subpage (bug #29797)
1402 if ( strpos( $target, '/' ) !== false ) {
1403 # An old subpage, drill down to the user behind it
1404 $target = explode( '/', $target )[0];
1407 $userObj = User
::newFromName( $target );
1408 if ( $userObj instanceof User
) {
1409 # Note that since numbers are valid usernames, a $target of "12345" will be
1410 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1411 # since hash characters are not valid in usernames or titles generally.
1412 return [ $userObj, self
::TYPE_USER
];
1414 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1415 # Autoblock reference in the form "#12345"
1416 return [ substr( $target, 1 ), self
::TYPE_AUTO
];
1420 return [ null, null ];
1425 * Get the type of target for this particular block
1426 * @return int Block::TYPE_ constant, will never be TYPE_ID
1428 public function getType() {
1435 * Get the target and target type for this particular Block. Note that for autoblocks,
1436 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1437 * in this situation.
1438 * @return array [ User|String, Block::TYPE_ constant ]
1439 * @todo FIXME: This should be an integral part of the Block member variables
1441 public function getTargetAndType() {
1442 return [ $this->getTarget(), $this->getType() ];
1446 * Get the target for this particular Block. Note that for autoblocks,
1447 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1448 * in this situation.
1449 * @return User|string
1451 public function getTarget() {
1452 return $this->target
;
1458 * @return mixed|string
1460 public function getExpiry() {
1461 return $this->mExpiry
;
1465 * Set the target for this block, and update $this->type accordingly
1466 * @param mixed $target
1468 public function setTarget( $target ) {
1469 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1473 * Get the user who implemented this block
1474 * @return User|string Local User object or string for a foreign user
1476 public function getBlocker() {
1477 return $this->blocker
;
1481 * Set the user who implemented (or will implement) this block
1482 * @param User|string $user Local User object or username string for foreign users
1484 public function setBlocker( $user ) {
1485 $this->blocker
= $user;
1489 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1490 * the same as the block's, to a maximum of 24 hours.
1494 * @param WebResponse $response The response on which to set the cookie.
1496 public function setCookie( WebResponse
$response ) {
1497 // Calculate the default expiry time.
1498 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1500 // Use the Block's expiry time only if it's less than the default.
1501 $expiryTime = $this->getExpiry();
1502 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1503 $expiryTime = $maxExpiryTime;
1506 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1507 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1508 $cookieOptions = [ 'httpOnly' => false ];
1509 $cookieValue = $this->getCookieValue();
1510 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1514 * Unset the 'BlockID' cookie.
1518 * @param WebResponse $response The response on which to unset the cookie.
1520 public static function clearCookie( WebResponse
$response ) {
1521 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1525 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1526 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1531 * @return string The block ID, probably concatenated with "!" and the HMAC.
1533 public function getCookieValue() {
1534 $config = RequestContext
::getMain()->getConfig();
1535 $id = $this->getId();
1536 $secretKey = $config->get( 'SecretKey' );
1537 if ( !$secretKey ) {
1538 // If there's no secret key, don't append a HMAC.
1541 $hmac = MWCryptHash
::hmac( $id, $secretKey, false );
1542 $cookieValue = $id . '!' . $hmac;
1543 return $cookieValue;
1547 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1548 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1552 * @param string $cookieValue The string in which to find the ID.
1554 * @return int|null The block ID, or null if the HMAC is present and invalid.
1556 public static function getIdFromCookieValue( $cookieValue ) {
1557 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1558 $bangPos = strpos( $cookieValue, '!' );
1559 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
1560 // Get the site-wide secret key.
1561 $config = RequestContext
::getMain()->getConfig();
1562 $secretKey = $config->get( 'SecretKey' );
1563 if ( !$secretKey ) {
1564 // If there's no secret key, just use the ID as given.
1567 $storedHmac = substr( $cookieValue, $bangPos +
1 );
1568 $calculatedHmac = MWCryptHash
::hmac( $id, $secretKey, false );
1569 if ( $calculatedHmac === $storedHmac ) {
1577 * Get the key and parameters for the corresponding error message.
1580 * @param IContextSource $context
1583 public function getPermissionsError( IContextSource
$context ) {
1584 $blocker = $this->getBlocker();
1585 if ( $blocker instanceof User
) { // local user
1586 $blockerUserpage = $blocker->getUserPage();
1587 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1588 } else { // foreign user
1592 $reason = $this->mReason
;
1593 if ( $reason == '' ) {
1594 $reason = $context->msg( 'blockednoreason' )->text();
1597 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1598 * This could be a username, an IP range, or a single IP. */
1599 $intended = $this->getTarget();
1601 $systemBlockType = $this->getSystemBlockType();
1603 $lang = $context->getLanguage();
1605 $systemBlockType !== null
1606 ?
'systemblockedtext'
1607 : ( $this->mAuto ?
'autoblockedtext' : 'blockedtext' ),
1610 $context->getRequest()->getIP(),
1612 $systemBlockType !== null ?
$systemBlockType : $this->getId(),
1613 $lang->formatExpiry( $this->mExpiry
),
1615 $lang->userTimeAndDate( $this->mTimestamp
, $context->getUser() ),