Move ILoadBalancer to Rdbms namespace
[mediawiki.git] / includes / Block.php
blob9d3a2f935c6998dfeed409850424b311421dbcdf
1 <?php
2 /**
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
20 * @file
23 use MediaWiki\MediaWikiServices;
25 class Block {
26 /** @var string */
27 public $mReason;
29 /** @var string */
30 public $mTimestamp;
32 /** @var bool */
33 public $mAuto;
35 /** @var string */
36 public $mExpiry;
38 /** @var bool */
39 public $mHideName;
41 /** @var int */
42 public $mParentBlockId;
44 /** @var int */
45 protected $mId;
47 /** @var bool */
48 protected $mFromMaster;
50 /** @var bool */
51 protected $mBlockEmail;
53 /** @var bool */
54 protected $mDisableUsertalk;
56 /** @var bool */
57 protected $mCreateAccount;
59 /** @var User|string */
60 protected $target;
62 /** @var int Hack for foreign blocking (CentralAuth) */
63 protected $forcedTargetID;
65 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
66 protected $type;
68 /** @var User */
69 protected $blocker;
71 /** @var bool */
72 protected $isHardblock;
74 /** @var bool */
75 protected $isAutoblocking;
77 /** @var string|null */
78 protected $systemBlockType;
80 # TYPE constants
81 const TYPE_USER = 1;
82 const TYPE_IP = 2;
83 const TYPE_RANGE = 3;
84 const TYPE_AUTO = 4;
85 const TYPE_ID = 5;
87 /**
88 * Create a new block with specified parameters on a user, IP or IP range.
90 * @param array $options Parameters of the block:
91 * address string|User Target user name, User object, IP address or IP range
92 * user int Override target user ID (for foreign users)
93 * by int User ID of the blocker
94 * reason string Reason of the block
95 * timestamp string The time at which the block comes into effect
96 * auto bool Is this an automatic block?
97 * expiry string Timestamp of expiration of the block or 'infinity'
98 * anonOnly bool Only disallow anonymous actions
99 * createAccount bool Disallow creation of new accounts
100 * enableAutoblock bool Enable automatic blocking
101 * hideName bool Hide the target user name
102 * blockEmail bool Disallow sending emails
103 * allowUsertalk bool Allow the target to edit its own talk page
104 * byText string Username of the blocker (for foreign users)
105 * systemBlock string Indicate that this block is automatically
106 * created by MediaWiki rather than being stored
107 * in the database. Value is a string to return
108 * from self::getSystemBlockType().
110 * @since 1.26 accepts $options array instead of individual parameters; order
111 * of parameters above reflects the original order
113 function __construct( $options = [] ) {
114 $defaults = [
115 'address' => '',
116 'user' => null,
117 'by' => null,
118 'reason' => '',
119 'timestamp' => '',
120 'auto' => false,
121 'expiry' => '',
122 'anonOnly' => false,
123 'createAccount' => false,
124 'enableAutoblock' => false,
125 'hideName' => false,
126 'blockEmail' => false,
127 'allowUsertalk' => false,
128 'byText' => '',
129 'systemBlock' => null,
132 if ( func_num_args() > 1 || !is_array( $options ) ) {
133 $options = array_combine(
134 array_slice( array_keys( $defaults ), 0, func_num_args() ),
135 func_get_args()
137 wfDeprecated( __METHOD__ . ' with multiple arguments', '1.26' );
140 $options += $defaults;
142 $this->setTarget( $options['address'] );
144 if ( $this->target instanceof User && $options['user'] ) {
145 # Needed for foreign users
146 $this->forcedTargetID = $options['user'];
149 if ( $options['by'] ) {
150 # Local user
151 $this->setBlocker( User::newFromId( $options['by'] ) );
152 } else {
153 # Foreign user
154 $this->setBlocker( $options['byText'] );
157 $this->mReason = $options['reason'];
158 $this->mTimestamp = wfTimestamp( TS_MW, $options['timestamp'] );
159 $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] );
161 # Boolean settings
162 $this->mAuto = (bool)$options['auto'];
163 $this->mHideName = (bool)$options['hideName'];
164 $this->isHardblock( !$options['anonOnly'] );
165 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
167 # Prevention measures
168 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
169 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
170 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
172 $this->mFromMaster = false;
173 $this->systemBlockType = $options['systemBlock'];
177 * Load a blocked user from their block id.
179 * @param int $id Block id to search for
180 * @return Block|null
182 public static function newFromID( $id ) {
183 $dbr = wfGetDB( DB_REPLICA );
184 $res = $dbr->selectRow(
185 'ipblocks',
186 self::selectFields(),
187 [ 'ipb_id' => $id ],
188 __METHOD__
190 if ( $res ) {
191 return self::newFromRow( $res );
192 } else {
193 return null;
198 * Return the list of ipblocks fields that should be selected to create
199 * a new block.
200 * @return array
202 public static function selectFields() {
203 return [
204 'ipb_id',
205 'ipb_address',
206 'ipb_by',
207 'ipb_by_text',
208 'ipb_reason',
209 'ipb_timestamp',
210 'ipb_auto',
211 'ipb_anon_only',
212 'ipb_create_account',
213 'ipb_enable_autoblock',
214 'ipb_expiry',
215 'ipb_deleted',
216 'ipb_block_email',
217 'ipb_allow_usertalk',
218 'ipb_parent_block_id',
223 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
224 * the blocking user or the block timestamp, only things which affect the blocked user
226 * @param Block $block
228 * @return bool
230 public function equals( Block $block ) {
231 return (
232 (string)$this->target == (string)$block->target
233 && $this->type == $block->type
234 && $this->mAuto == $block->mAuto
235 && $this->isHardblock() == $block->isHardblock()
236 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
237 && $this->mExpiry == $block->mExpiry
238 && $this->isAutoblocking() == $block->isAutoblocking()
239 && $this->mHideName == $block->mHideName
240 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
241 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
242 && $this->mReason == $block->mReason
247 * Load a block from the database which affects the already-set $this->target:
248 * 1) A block directly on the given user or IP
249 * 2) A rangeblock encompassing the given IP (smallest first)
250 * 3) An autoblock on the given IP
251 * @param User|string $vagueTarget Also search for blocks affecting this target. Doesn't
252 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
253 * @throws MWException
254 * @return bool Whether a relevant block was found
256 protected function newLoad( $vagueTarget = null ) {
257 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
259 if ( $this->type !== null ) {
260 $conds = [
261 'ipb_address' => [ (string)$this->target ],
263 } else {
264 $conds = [ 'ipb_address' => [] ];
267 # Be aware that the != '' check is explicit, since empty values will be
268 # passed by some callers (bug 29116)
269 if ( $vagueTarget != '' ) {
270 list( $target, $type ) = self::parseTarget( $vagueTarget );
271 switch ( $type ) {
272 case self::TYPE_USER:
273 # Slightly weird, but who are we to argue?
274 $conds['ipb_address'][] = (string)$target;
275 break;
277 case self::TYPE_IP:
278 $conds['ipb_address'][] = (string)$target;
279 $conds[] = self::getRangeCond( IP::toHex( $target ) );
280 $conds = $db->makeList( $conds, LIST_OR );
281 break;
283 case self::TYPE_RANGE:
284 list( $start, $end ) = IP::parseRange( $target );
285 $conds['ipb_address'][] = (string)$target;
286 $conds[] = self::getRangeCond( $start, $end );
287 $conds = $db->makeList( $conds, LIST_OR );
288 break;
290 default:
291 throw new MWException( "Tried to load block with invalid type" );
295 $res = $db->select( 'ipblocks', self::selectFields(), $conds, __METHOD__ );
297 # This result could contain a block on the user, a block on the IP, and a russian-doll
298 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
299 $bestRow = null;
301 # Lower will be better
302 $bestBlockScore = 100;
304 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
305 $bestBlockPreventsEdit = null;
307 foreach ( $res as $row ) {
308 $block = self::newFromRow( $row );
310 # Don't use expired blocks
311 if ( $block->isExpired() ) {
312 continue;
315 # Don't use anon only blocks on users
316 if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
317 continue;
320 if ( $block->getType() == self::TYPE_RANGE ) {
321 # This is the number of bits that are allowed to vary in the block, give
322 # or take some floating point errors
323 $end = Wikimedia\base_convert( $block->getRangeEnd(), 16, 10 );
324 $start = Wikimedia\base_convert( $block->getRangeStart(), 16, 10 );
325 $size = log( $end - $start + 1, 2 );
327 # This has the nice property that a /32 block is ranked equally with a
328 # single-IP block, which is exactly what it is...
329 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
331 } else {
332 $score = $block->getType();
335 if ( $score < $bestBlockScore ) {
336 $bestBlockScore = $score;
337 $bestRow = $row;
338 $bestBlockPreventsEdit = $block->prevents( 'edit' );
342 if ( $bestRow !== null ) {
343 $this->initFromRow( $bestRow );
344 $this->prevents( 'edit', $bestBlockPreventsEdit );
345 return true;
346 } else {
347 return false;
352 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
353 * @param string $start Hexadecimal IP representation
354 * @param string $end Hexadecimal IP representation, or null to use $start = $end
355 * @return string
357 public static function getRangeCond( $start, $end = null ) {
358 if ( $end === null ) {
359 $end = $start;
361 # Per bug 14634, we want to include relevant active rangeblocks; for
362 # rangeblocks, we want to include larger ranges which enclose the given
363 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
364 # so we can improve performance by filtering on a LIKE clause
365 $chunk = self::getIpFragment( $start );
366 $dbr = wfGetDB( DB_REPLICA );
367 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
369 # Fairly hard to make a malicious SQL statement out of hex characters,
370 # but stranger things have happened...
371 $safeStart = $dbr->addQuotes( $start );
372 $safeEnd = $dbr->addQuotes( $end );
374 return $dbr->makeList(
376 "ipb_range_start $like",
377 "ipb_range_start <= $safeStart",
378 "ipb_range_end >= $safeEnd",
380 LIST_AND
385 * Get the component of an IP address which is certain to be the same between an IP
386 * address and a rangeblock containing that IP address.
387 * @param string $hex Hexadecimal IP representation
388 * @return string
390 protected static function getIpFragment( $hex ) {
391 global $wgBlockCIDRLimit;
392 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
393 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
394 } else {
395 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
400 * Given a database row from the ipblocks table, initialize
401 * member variables
402 * @param stdClass $row A row from the ipblocks table
404 protected function initFromRow( $row ) {
405 $this->setTarget( $row->ipb_address );
406 if ( $row->ipb_by ) { // local user
407 $this->setBlocker( User::newFromId( $row->ipb_by ) );
408 } else { // foreign user
409 $this->setBlocker( $row->ipb_by_text );
412 $this->mReason = $row->ipb_reason;
413 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
414 $this->mAuto = $row->ipb_auto;
415 $this->mHideName = $row->ipb_deleted;
416 $this->mId = (int)$row->ipb_id;
417 $this->mParentBlockId = $row->ipb_parent_block_id;
419 // I wish I didn't have to do this
420 $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $row->ipb_expiry );
422 $this->isHardblock( !$row->ipb_anon_only );
423 $this->isAutoblocking( $row->ipb_enable_autoblock );
425 $this->prevents( 'createaccount', $row->ipb_create_account );
426 $this->prevents( 'sendemail', $row->ipb_block_email );
427 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
431 * Create a new Block object from a database row
432 * @param stdClass $row Row from the ipblocks table
433 * @return Block
435 public static function newFromRow( $row ) {
436 $block = new Block;
437 $block->initFromRow( $row );
438 return $block;
442 * Delete the row from the IP blocks table.
444 * @throws MWException
445 * @return bool
447 public function delete() {
448 if ( wfReadOnly() ) {
449 return false;
452 if ( !$this->getId() ) {
453 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
456 $dbw = wfGetDB( DB_MASTER );
457 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
458 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
460 return $dbw->affectedRows() > 0;
464 * Insert a block into the block table. Will fail if there is a conflicting
465 * block (same name and options) already in the database.
467 * @param IDatabase $dbw If you have one available
468 * @return bool|array False on failure, assoc array on success:
469 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
471 public function insert( $dbw = null ) {
472 global $wgBlockDisablesLogin;
474 if ( $this->getSystemBlockType() !== null ) {
475 throw new MWException( 'Cannot insert a system block into the database' );
478 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
480 if ( $dbw === null ) {
481 $dbw = wfGetDB( DB_MASTER );
484 # Periodic purge via commit hooks
485 if ( mt_rand( 0, 9 ) == 0 ) {
486 Block::purgeExpired();
489 $row = $this->getDatabaseArray();
490 $row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );
492 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
493 $affected = $dbw->affectedRows();
494 $this->mId = $dbw->insertId();
496 # Don't collide with expired blocks.
497 # Do this after trying to insert to avoid locking.
498 if ( !$affected ) {
499 # T96428: The ipb_address index uses a prefix on a field, so
500 # use a standard SELECT + DELETE to avoid annoying gap locks.
501 $ids = $dbw->selectFieldValues( 'ipblocks',
502 'ipb_id',
504 'ipb_address' => $row['ipb_address'],
505 'ipb_user' => $row['ipb_user'],
506 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
508 __METHOD__
510 if ( $ids ) {
511 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
512 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
513 $affected = $dbw->affectedRows();
514 $this->mId = $dbw->insertId();
518 if ( $affected ) {
519 $auto_ipd_ids = $this->doRetroactiveAutoblock();
521 if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
522 // Change user login token to force them to be logged out.
523 $this->target->setToken();
524 $this->target->saveSettings();
527 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
530 return false;
534 * Update a block in the DB with new parameters.
535 * The ID field needs to be loaded first.
537 * @return bool|array False on failure, array on success:
538 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
540 public function update() {
541 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
542 $dbw = wfGetDB( DB_MASTER );
544 $dbw->startAtomic( __METHOD__ );
546 $dbw->update(
547 'ipblocks',
548 $this->getDatabaseArray( $dbw ),
549 [ 'ipb_id' => $this->getId() ],
550 __METHOD__
553 $affected = $dbw->affectedRows();
555 if ( $this->isAutoblocking() ) {
556 // update corresponding autoblock(s) (bug 48813)
557 $dbw->update(
558 'ipblocks',
559 $this->getAutoblockUpdateArray(),
560 [ 'ipb_parent_block_id' => $this->getId() ],
561 __METHOD__
563 } else {
564 // autoblock no longer required, delete corresponding autoblock(s)
565 $dbw->delete(
566 'ipblocks',
567 [ 'ipb_parent_block_id' => $this->getId() ],
568 __METHOD__
572 $dbw->endAtomic( __METHOD__ );
574 if ( $affected ) {
575 $auto_ipd_ids = $this->doRetroactiveAutoblock();
576 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
579 return false;
583 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
584 * @param IDatabase $db
585 * @return array
587 protected function getDatabaseArray( $db = null ) {
588 if ( !$db ) {
589 $db = wfGetDB( DB_REPLICA );
591 $expiry = $db->encodeExpiry( $this->mExpiry );
593 if ( $this->forcedTargetID ) {
594 $uid = $this->forcedTargetID;
595 } else {
596 $uid = $this->target instanceof User ? $this->target->getId() : 0;
599 $a = [
600 'ipb_address' => (string)$this->target,
601 'ipb_user' => $uid,
602 'ipb_by' => $this->getBy(),
603 'ipb_by_text' => $this->getByName(),
604 'ipb_reason' => $this->mReason,
605 'ipb_timestamp' => $db->timestamp( $this->mTimestamp ),
606 'ipb_auto' => $this->mAuto,
607 'ipb_anon_only' => !$this->isHardblock(),
608 'ipb_create_account' => $this->prevents( 'createaccount' ),
609 'ipb_enable_autoblock' => $this->isAutoblocking(),
610 'ipb_expiry' => $expiry,
611 'ipb_range_start' => $this->getRangeStart(),
612 'ipb_range_end' => $this->getRangeEnd(),
613 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
614 'ipb_block_email' => $this->prevents( 'sendemail' ),
615 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
616 'ipb_parent_block_id' => $this->mParentBlockId
619 return $a;
623 * @return array
625 protected function getAutoblockUpdateArray() {
626 return [
627 'ipb_by' => $this->getBy(),
628 'ipb_by_text' => $this->getByName(),
629 'ipb_reason' => $this->mReason,
630 'ipb_create_account' => $this->prevents( 'createaccount' ),
631 'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
632 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
637 * Retroactively autoblocks the last IP used by the user (if it is a user)
638 * blocked by this Block.
640 * @return array Block IDs of retroactive autoblocks made
642 protected function doRetroactiveAutoblock() {
643 $blockIds = [];
644 # If autoblock is enabled, autoblock the LAST IP(s) used
645 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
646 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
648 $continue = Hooks::run(
649 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
651 if ( $continue ) {
652 self::defaultRetroactiveAutoblock( $this, $blockIds );
655 return $blockIds;
659 * Retroactively autoblocks the last IP used by the user (if it is a user)
660 * blocked by this Block. This will use the recentchanges table.
662 * @param Block $block
663 * @param array &$blockIds
665 protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
666 global $wgPutIPinRC;
668 // No IPs are in recentchanges table, so nothing to select
669 if ( !$wgPutIPinRC ) {
670 return;
673 $dbr = wfGetDB( DB_REPLICA );
675 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
676 $conds = [ 'rc_user_text' => (string)$block->getTarget() ];
678 // Just the last IP used.
679 $options['LIMIT'] = 1;
681 $res = $dbr->select( 'recentchanges', [ 'rc_ip' ], $conds,
682 __METHOD__, $options );
684 if ( !$res->numRows() ) {
685 # No results, don't autoblock anything
686 wfDebug( "No IP found to retroactively autoblock\n" );
687 } else {
688 foreach ( $res as $row ) {
689 if ( $row->rc_ip ) {
690 $id = $block->doAutoblock( $row->rc_ip );
691 if ( $id ) {
692 $blockIds[] = $id;
700 * Checks whether a given IP is on the autoblock whitelist.
701 * TODO: this probably belongs somewhere else, but not sure where...
703 * @param string $ip The IP to check
704 * @return bool
706 public static function isWhitelistedFromAutoblocks( $ip ) {
707 // Try to get the autoblock_whitelist from the cache, as it's faster
708 // than getting the msg raw and explode()'ing it.
709 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
710 $lines = $cache->getWithSetCallback(
711 wfMemcKey( 'ipb', 'autoblock', 'whitelist' ),
712 $cache::TTL_DAY,
713 function ( $curValue, &$ttl, array &$setOpts ) {
714 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
716 return explode( "\n",
717 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
721 wfDebug( "Checking the autoblock whitelist..\n" );
723 foreach ( $lines as $line ) {
724 # List items only
725 if ( substr( $line, 0, 1 ) !== '*' ) {
726 continue;
729 $wlEntry = substr( $line, 1 );
730 $wlEntry = trim( $wlEntry );
732 wfDebug( "Checking $ip against $wlEntry..." );
734 # Is the IP in this range?
735 if ( IP::isInRange( $ip, $wlEntry ) ) {
736 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
737 return true;
738 } else {
739 wfDebug( " No match\n" );
743 return false;
747 * Autoblocks the given IP, referring to this Block.
749 * @param string $autoblockIP The IP to autoblock.
750 * @return int|bool Block ID if an autoblock was inserted, false if not.
752 public function doAutoblock( $autoblockIP ) {
753 # If autoblocks are disabled, go away.
754 if ( !$this->isAutoblocking() ) {
755 return false;
758 # Don't autoblock for system blocks
759 if ( $this->getSystemBlockType() !== null ) {
760 throw new MWException( 'Cannot autoblock from a system block' );
763 # Check for presence on the autoblock whitelist.
764 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
765 return false;
768 // Avoid PHP 7.1 warning of passing $this by reference
769 $block = $this;
770 # Allow hooks to cancel the autoblock.
771 if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
772 wfDebug( "Autoblock aborted by hook.\n" );
773 return false;
776 # It's okay to autoblock. Go ahead and insert/update the block...
778 # Do not add a *new* block if the IP is already blocked.
779 $ipblock = Block::newFromTarget( $autoblockIP );
780 if ( $ipblock ) {
781 # Check if the block is an autoblock and would exceed the user block
782 # if renewed. If so, do nothing, otherwise prolong the block time...
783 if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
784 $this->mExpiry > Block::getAutoblockExpiry( $ipblock->mTimestamp )
786 # Reset block timestamp to now and its expiry to
787 # $wgAutoblockExpiry in the future
788 $ipblock->updateTimestamp();
790 return false;
793 # Make a new block object with the desired properties.
794 $autoblock = new Block;
795 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
796 $autoblock->setTarget( $autoblockIP );
797 $autoblock->setBlocker( $this->getBlocker() );
798 $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )
799 ->inContentLanguage()->plain();
800 $timestamp = wfTimestampNow();
801 $autoblock->mTimestamp = $timestamp;
802 $autoblock->mAuto = 1;
803 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
804 # Continue suppressing the name if needed
805 $autoblock->mHideName = $this->mHideName;
806 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
807 $autoblock->mParentBlockId = $this->mId;
809 if ( $this->mExpiry == 'infinity' ) {
810 # Original block was indefinite, start an autoblock now
811 $autoblock->mExpiry = Block::getAutoblockExpiry( $timestamp );
812 } else {
813 # If the user is already blocked with an expiry date, we don't
814 # want to pile on top of that.
815 $autoblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $timestamp ) );
818 # Insert the block...
819 $status = $autoblock->insert();
820 return $status
821 ? $status['id']
822 : false;
826 * Check if a block has expired. Delete it if it is.
827 * @return bool
829 public function deleteIfExpired() {
831 if ( $this->isExpired() ) {
832 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
833 $this->delete();
834 $retVal = true;
835 } else {
836 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
837 $retVal = false;
840 return $retVal;
844 * Has the block expired?
845 * @return bool
847 public function isExpired() {
848 $timestamp = wfTimestampNow();
849 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
851 if ( !$this->mExpiry ) {
852 return false;
853 } else {
854 return $timestamp > $this->mExpiry;
859 * Is the block address valid (i.e. not a null string?)
860 * @return bool
862 public function isValid() {
863 return $this->getTarget() != null;
867 * Update the timestamp on autoblocks.
869 public function updateTimestamp() {
870 if ( $this->mAuto ) {
871 $this->mTimestamp = wfTimestamp();
872 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
874 $dbw = wfGetDB( DB_MASTER );
875 $dbw->update( 'ipblocks',
876 [ /* SET */
877 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
878 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
880 [ /* WHERE */
881 'ipb_id' => $this->getId(),
883 __METHOD__
889 * Get the IP address at the start of the range in Hex form
890 * @throws MWException
891 * @return string IP in Hex form
893 public function getRangeStart() {
894 switch ( $this->type ) {
895 case self::TYPE_USER:
896 return '';
897 case self::TYPE_IP:
898 return IP::toHex( $this->target );
899 case self::TYPE_RANGE:
900 list( $start, /*...*/ ) = IP::parseRange( $this->target );
901 return $start;
902 default:
903 throw new MWException( "Block with invalid type" );
908 * Get the IP address at the end of the range in Hex form
909 * @throws MWException
910 * @return string IP in Hex form
912 public function getRangeEnd() {
913 switch ( $this->type ) {
914 case self::TYPE_USER:
915 return '';
916 case self::TYPE_IP:
917 return IP::toHex( $this->target );
918 case self::TYPE_RANGE:
919 list( /*...*/, $end ) = IP::parseRange( $this->target );
920 return $end;
921 default:
922 throw new MWException( "Block with invalid type" );
927 * Get the user id of the blocking sysop
929 * @return int (0 for foreign users)
931 public function getBy() {
932 $blocker = $this->getBlocker();
933 return ( $blocker instanceof User )
934 ? $blocker->getId()
935 : 0;
939 * Get the username of the blocking sysop
941 * @return string
943 public function getByName() {
944 $blocker = $this->getBlocker();
945 return ( $blocker instanceof User )
946 ? $blocker->getName()
947 : (string)$blocker; // username
951 * Get the block ID
952 * @return int
954 public function getId() {
955 return $this->mId;
959 * Get the system block type, if any
960 * @return string|null
962 public function getSystemBlockType() {
963 return $this->systemBlockType;
967 * Get/set a flag determining whether the master is used for reads
969 * @param bool|null $x
970 * @return bool
972 public function fromMaster( $x = null ) {
973 return wfSetVar( $this->mFromMaster, $x );
977 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
978 * @param bool|null $x
979 * @return bool
981 public function isHardblock( $x = null ) {
982 wfSetVar( $this->isHardblock, $x );
984 # You can't *not* hardblock a user
985 return $this->getType() == self::TYPE_USER
986 ? true
987 : $this->isHardblock;
991 * @param null|bool $x
992 * @return bool
994 public function isAutoblocking( $x = null ) {
995 wfSetVar( $this->isAutoblocking, $x );
997 # You can't put an autoblock on an IP or range as we don't have any history to
998 # look over to get more IPs from
999 return $this->getType() == self::TYPE_USER
1000 ? $this->isAutoblocking
1001 : false;
1005 * Get/set whether the Block prevents a given action
1007 * @param string $action Action to check
1008 * @param bool|null $x Value for set, or null to just get value
1009 * @return bool|null Null for unrecognized rights.
1011 public function prevents( $action, $x = null ) {
1012 global $wgBlockDisablesLogin;
1013 $res = null;
1014 switch ( $action ) {
1015 case 'edit':
1016 # For now... <evil laugh>
1017 $res = true;
1018 break;
1019 case 'createaccount':
1020 $res = wfSetVar( $this->mCreateAccount, $x );
1021 break;
1022 case 'sendemail':
1023 $res = wfSetVar( $this->mBlockEmail, $x );
1024 break;
1025 case 'editownusertalk':
1026 $res = wfSetVar( $this->mDisableUsertalk, $x );
1027 break;
1028 case 'read':
1029 $res = false;
1030 break;
1032 if ( !$res && $wgBlockDisablesLogin ) {
1033 // If a block would disable login, then it should
1034 // prevent any action that all users cannot do
1035 $anon = new User;
1036 $res = $anon->isAllowed( $action ) ? $res : true;
1039 return $res;
1043 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1044 * @return string Text is escaped
1046 public function getRedactedName() {
1047 if ( $this->mAuto ) {
1048 return Html::rawElement(
1049 'span',
1050 [ 'class' => 'mw-autoblockid' ],
1051 wfMessage( 'autoblockid', $this->mId )
1053 } else {
1054 return htmlspecialchars( $this->getTarget() );
1059 * Get a timestamp of the expiry for autoblocks
1061 * @param string|int $timestamp
1062 * @return string
1064 public static function getAutoblockExpiry( $timestamp ) {
1065 global $wgAutoblockExpiry;
1067 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1071 * Purge expired blocks from the ipblocks table
1073 public static function purgeExpired() {
1074 if ( wfReadOnly() ) {
1075 return;
1078 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
1079 wfGetDB( DB_MASTER ),
1080 __METHOD__,
1081 function ( IDatabase $dbw, $fname ) {
1082 $dbw->delete(
1083 'ipblocks',
1084 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1085 $fname
1088 ) );
1092 * Given a target and the target's type, get an existing Block object if possible.
1093 * @param string|User|int $specificTarget A block target, which may be one of several types:
1094 * * A user to block, in which case $target will be a User
1095 * * An IP to block, in which case $target will be a User generated by using
1096 * User::newFromName( $ip, false ) to turn off name validation
1097 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1098 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1099 * usernames
1100 * Calling this with a user, IP address or range will not select autoblocks, and will
1101 * only select a block where the targets match exactly (so looking for blocks on
1102 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1103 * @param string|User|int $vagueTarget As above, but we will search for *any* block which
1104 * affects that target (so for an IP address, get ranges containing that IP; and also
1105 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1106 * @param bool $fromMaster Whether to use the DB_MASTER database
1107 * @return Block|null (null if no relevant block could be found). The target and type
1108 * of the returned Block will refer to the actual block which was found, which might
1109 * not be the same as the target you gave if you used $vagueTarget!
1111 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1113 list( $target, $type ) = self::parseTarget( $specificTarget );
1114 if ( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ) {
1115 return Block::newFromID( $target );
1117 } elseif ( $target === null && $vagueTarget == '' ) {
1118 # We're not going to find anything useful here
1119 # Be aware that the == '' check is explicit, since empty values will be
1120 # passed by some callers (bug 29116)
1121 return null;
1123 } elseif ( in_array(
1124 $type,
1125 [ Block::TYPE_USER, Block::TYPE_IP, Block::TYPE_RANGE, null ] )
1127 $block = new Block();
1128 $block->fromMaster( $fromMaster );
1130 if ( $type !== null ) {
1131 $block->setTarget( $target );
1134 if ( $block->newLoad( $vagueTarget ) ) {
1135 return $block;
1138 return null;
1142 * Get all blocks that match any IP from an array of IP addresses
1144 * @param array $ipChain List of IPs (strings), usually retrieved from the
1145 * X-Forwarded-For header of the request
1146 * @param bool $isAnon Exclude anonymous-only blocks if false
1147 * @param bool $fromMaster Whether to query the master or replica DB
1148 * @return array Array of Blocks
1149 * @since 1.22
1151 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1152 if ( !count( $ipChain ) ) {
1153 return [];
1156 $conds = [];
1157 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1158 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1159 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1160 # necessarily trust the header given to us, make sure that we are only
1161 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1162 # Do not treat private IP spaces as special as it may be desirable for wikis
1163 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1164 if ( !IP::isValid( $ipaddr ) ) {
1165 continue;
1167 # Don't check trusted IPs (includes local squids which will be in every request)
1168 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1169 continue;
1171 # Check both the original IP (to check against single blocks), as well as build
1172 # the clause to check for rangeblocks for the given IP.
1173 $conds['ipb_address'][] = $ipaddr;
1174 $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1177 if ( !count( $conds ) ) {
1178 return [];
1181 if ( $fromMaster ) {
1182 $db = wfGetDB( DB_MASTER );
1183 } else {
1184 $db = wfGetDB( DB_REPLICA );
1186 $conds = $db->makeList( $conds, LIST_OR );
1187 if ( !$isAnon ) {
1188 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1190 $selectFields = array_merge(
1191 [ 'ipb_range_start', 'ipb_range_end' ],
1192 Block::selectFields()
1194 $rows = $db->select( 'ipblocks',
1195 $selectFields,
1196 $conds,
1197 __METHOD__
1200 $blocks = [];
1201 foreach ( $rows as $row ) {
1202 $block = self::newFromRow( $row );
1203 if ( !$block->isExpired() ) {
1204 $blocks[] = $block;
1208 return $blocks;
1212 * From a list of multiple blocks, find the most exact and strongest Block.
1214 * The logic for finding the "best" block is:
1215 * - Blocks that match the block's target IP are preferred over ones in a range
1216 * - Hardblocks are chosen over softblocks that prevent account creation
1217 * - Softblocks that prevent account creation are chosen over other softblocks
1218 * - Other softblocks are chosen over autoblocks
1219 * - If there are multiple exact or range blocks at the same level, the one chosen
1220 * is random
1221 * This should be used when $blocks where retrieved from the user's IP address
1222 * and $ipChain is populated from the same IP address information.
1224 * @param array $blocks Array of Block objects
1225 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1226 * a block is to the server, and if a block matches exactly, or is in a range.
1227 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1228 * local-squid, ...)
1229 * @throws MWException
1230 * @return Block|null The "best" block from the list
1232 public static function chooseBlock( array $blocks, array $ipChain ) {
1233 if ( !count( $blocks ) ) {
1234 return null;
1235 } elseif ( count( $blocks ) == 1 ) {
1236 return $blocks[0];
1239 // Sort hard blocks before soft ones and secondarily sort blocks
1240 // that disable account creation before those that don't.
1241 usort( $blocks, function ( Block $a, Block $b ) {
1242 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1243 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1244 return strcmp( $bWeight, $aWeight ); // highest weight first
1245 } );
1247 $blocksListExact = [
1248 'hard' => false,
1249 'disable_create' => false,
1250 'other' => false,
1251 'auto' => false
1253 $blocksListRange = [
1254 'hard' => false,
1255 'disable_create' => false,
1256 'other' => false,
1257 'auto' => false
1259 $ipChain = array_reverse( $ipChain );
1261 /** @var Block $block */
1262 foreach ( $blocks as $block ) {
1263 // Stop searching if we have already have a "better" block. This
1264 // is why the order of the blocks matters
1265 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1266 break;
1267 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1268 break;
1271 foreach ( $ipChain as $checkip ) {
1272 $checkipHex = IP::toHex( $checkip );
1273 if ( (string)$block->getTarget() === $checkip ) {
1274 if ( $block->isHardblock() ) {
1275 $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1276 } elseif ( $block->prevents( 'createaccount' ) ) {
1277 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1278 } elseif ( $block->mAuto ) {
1279 $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1280 } else {
1281 $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1283 // We found closest exact match in the ip list, so go to the next Block
1284 break;
1285 } elseif ( array_filter( $blocksListExact ) == []
1286 && $block->getRangeStart() <= $checkipHex
1287 && $block->getRangeEnd() >= $checkipHex
1289 if ( $block->isHardblock() ) {
1290 $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1291 } elseif ( $block->prevents( 'createaccount' ) ) {
1292 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1293 } elseif ( $block->mAuto ) {
1294 $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1295 } else {
1296 $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1298 break;
1303 if ( array_filter( $blocksListExact ) == [] ) {
1304 $blocksList = &$blocksListRange;
1305 } else {
1306 $blocksList = &$blocksListExact;
1309 $chosenBlock = null;
1310 if ( $blocksList['hard'] ) {
1311 $chosenBlock = $blocksList['hard'];
1312 } elseif ( $blocksList['disable_create'] ) {
1313 $chosenBlock = $blocksList['disable_create'];
1314 } elseif ( $blocksList['other'] ) {
1315 $chosenBlock = $blocksList['other'];
1316 } elseif ( $blocksList['auto'] ) {
1317 $chosenBlock = $blocksList['auto'];
1318 } else {
1319 throw new MWException( "Proxy block found, but couldn't be classified." );
1322 return $chosenBlock;
1326 * From an existing Block, get the target and the type of target.
1327 * Note that, except for null, it is always safe to treat the target
1328 * as a string; for User objects this will return User::__toString()
1329 * which in turn gives User::getName().
1331 * @param string|int|User|null $target
1332 * @return array( User|String|null, Block::TYPE_ constant|null )
1334 public static function parseTarget( $target ) {
1335 # We may have been through this before
1336 if ( $target instanceof User ) {
1337 if ( IP::isValid( $target->getName() ) ) {
1338 return [ $target, self::TYPE_IP ];
1339 } else {
1340 return [ $target, self::TYPE_USER ];
1342 } elseif ( $target === null ) {
1343 return [ null, null ];
1346 $target = trim( $target );
1348 if ( IP::isValid( $target ) ) {
1349 # We can still create a User if it's an IP address, but we need to turn
1350 # off validation checking (which would exclude IP addresses)
1351 return [
1352 User::newFromName( IP::sanitizeIP( $target ), false ),
1353 Block::TYPE_IP
1356 } elseif ( IP::isValidBlock( $target ) ) {
1357 # Can't create a User from an IP range
1358 return [ IP::sanitizeRange( $target ), Block::TYPE_RANGE ];
1361 # Consider the possibility that this is not a username at all
1362 # but actually an old subpage (bug #29797)
1363 if ( strpos( $target, '/' ) !== false ) {
1364 # An old subpage, drill down to the user behind it
1365 $target = explode( '/', $target )[0];
1368 $userObj = User::newFromName( $target );
1369 if ( $userObj instanceof User ) {
1370 # Note that since numbers are valid usernames, a $target of "12345" will be
1371 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1372 # since hash characters are not valid in usernames or titles generally.
1373 return [ $userObj, Block::TYPE_USER ];
1375 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1376 # Autoblock reference in the form "#12345"
1377 return [ substr( $target, 1 ), Block::TYPE_AUTO ];
1379 } else {
1380 # WTF?
1381 return [ null, null ];
1386 * Get the type of target for this particular block
1387 * @return int Block::TYPE_ constant, will never be TYPE_ID
1389 public function getType() {
1390 return $this->mAuto
1391 ? self::TYPE_AUTO
1392 : $this->type;
1396 * Get the target and target type for this particular Block. Note that for autoblocks,
1397 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1398 * in this situation.
1399 * @return array( User|String, Block::TYPE_ constant )
1400 * @todo FIXME: This should be an integral part of the Block member variables
1402 public function getTargetAndType() {
1403 return [ $this->getTarget(), $this->getType() ];
1407 * Get the target for this particular Block. Note that for autoblocks,
1408 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1409 * in this situation.
1410 * @return User|string
1412 public function getTarget() {
1413 return $this->target;
1417 * @since 1.19
1419 * @return mixed|string
1421 public function getExpiry() {
1422 return $this->mExpiry;
1426 * Set the target for this block, and update $this->type accordingly
1427 * @param mixed $target
1429 public function setTarget( $target ) {
1430 list( $this->target, $this->type ) = self::parseTarget( $target );
1434 * Get the user who implemented this block
1435 * @return User|string Local User object or string for a foreign user
1437 public function getBlocker() {
1438 return $this->blocker;
1442 * Set the user who implemented (or will implement) this block
1443 * @param User|string $user Local User object or username string for foreign users
1445 public function setBlocker( $user ) {
1446 $this->blocker = $user;
1450 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1451 * the same as the block's, to a maximum of 24 hours.
1453 * An empty value can also be set, in order to retain the cookie but remove the block ID
1454 * (e.g. as used in User::getBlockedStatus).
1456 * @param WebResponse $response The response on which to set the cookie.
1457 * @param boolean $setEmpty Whether to set the cookie's value to the empty string.
1459 public function setCookie( WebResponse $response, $setEmpty = false ) {
1460 // Calculate the default expiry time.
1461 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1463 // Use the Block's expiry time only if it's less than the default.
1464 $expiryTime = $this->getExpiry();
1465 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1466 $expiryTime = $maxExpiryTime;
1469 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1470 $cookieValue = $setEmpty ? '' : $this->getId();
1471 $expiryValue = DateTime::createFromFormat( "YmdHis", $expiryTime );
1472 $response->setCookie( 'BlockID', $cookieValue, $expiryValue->format( "U" ) );
1476 * Get the key and parameters for the corresponding error message.
1478 * @since 1.22
1479 * @param IContextSource $context
1480 * @return array
1482 public function getPermissionsError( IContextSource $context ) {
1483 $blocker = $this->getBlocker();
1484 if ( $blocker instanceof User ) { // local user
1485 $blockerUserpage = $blocker->getUserPage();
1486 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1487 } else { // foreign user
1488 $link = $blocker;
1491 $reason = $this->mReason;
1492 if ( $reason == '' ) {
1493 $reason = $context->msg( 'blockednoreason' )->text();
1496 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1497 * This could be a username, an IP range, or a single IP. */
1498 $intended = $this->getTarget();
1500 $systemBlockType = $this->getSystemBlockType();
1502 $lang = $context->getLanguage();
1503 return [
1504 $systemBlockType !== null
1505 ? 'systemblockedtext'
1506 : ( $this->mAuto ? 'autoblockedtext' : 'blockedtext' ),
1507 $link,
1508 $reason,
1509 $context->getRequest()->getIP(),
1510 $this->getByName(),
1511 $systemBlockType !== null ? $systemBlockType : $this->getId(),
1512 $lang->formatExpiry( $this->mExpiry ),
1513 (string)$intended,
1514 $lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),